MainWindowViewModel.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. using Avalonia.Controls.ApplicationLifetimes;
  2. using ReactiveUI;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Collections.ObjectModel;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Text;
  9. using System.Text.Json;
  10. using System.Threading.Tasks;
  11. using VeloeMinecraftLauncher.Entity.LauncherProfiles;
  12. using VeloeMinecraftLauncher.Entity.VersionManifest;
  13. using VeloeMinecraftLauncher.MinecraftLauncher;
  14. using VeloeMinecraftLauncher.Views;
  15. using System;
  16. using System.Threading.Tasks;
  17. using System.Windows;
  18. using Microsoft.AspNetCore.SignalR.Client;
  19. using VeloeMinecraftLauncher.Entity.McStatus;
  20. using System.Timers;
  21. using System.ComponentModel;
  22. using System.Reflection;
  23. using Serilog;
  24. using Serilog.Events;
  25. using Serilog.Formatting;
  26. using Avalonia.Controls;
  27. using Avalonia.Threading;
  28. namespace VeloeMinecraftLauncher.ViewModels
  29. {
  30. public class MainWindowViewModel : ViewModelBase
  31. {
  32. public MainWindowViewModel()
  33. {
  34. //creating logger
  35. EventSink eventSink = new(null);
  36. eventSink.DataReceived += LogHandler;
  37. logger = new LoggerConfiguration()
  38. .MinimumLevel.Debug()
  39. .WriteTo.Sink(eventSink)
  40. .WriteTo.File("launcher.log", LogEventLevel.Debug, fileSizeLimitBytes: 100000000)// restricted... is Optional
  41. .CreateLogger();
  42. Settings.logger = logger;
  43. //loading settings
  44. logger.Debug("Loading settings.");
  45. Settings.LoadSettings();
  46. username = Settings.Username;
  47. //loading local verions
  48. logger.Debug("Loading local versions.");
  49. updateAvailable();
  50. //check launcher update
  51. logger.Debug("Checking launcher versions updates.");
  52. latestLauncherInfo = Downloader.DownloadAndDeserializeJsonData<LatestLauncherVersion>("https://files.veloe.link/launcher/update/versions.json");
  53. if (latestLauncherInfo is not null)
  54. {
  55. logger.Debug("Launcher version on server: {0}", latestLauncherInfo.latest);
  56. logger.Debug("Launcher version: {0}", Assembly.GetExecutingAssembly().GetName().Version);
  57. string[] version = latestLauncherInfo.latest.Split('.');
  58. var vat = Assembly.GetExecutingAssembly().GetName().Version;
  59. if (Int16.Parse(version[0]) > Assembly.GetExecutingAssembly().GetName().Version.Major ||
  60. Int16.Parse(version[1]) > Assembly.GetExecutingAssembly().GetName().Version.Minor ||
  61. Int16.Parse(version[2]) > Assembly.GetExecutingAssembly().GetName().Version.Build ||
  62. Int16.Parse(version[3]) > Assembly.GetExecutingAssembly().GetName().Version.Revision)
  63. {
  64. logger.Debug("Update available!");
  65. IsUpdateAvailable = true;
  66. }
  67. }
  68. logger.Debug("Connecting to WebSoket");
  69. //conection to my servers
  70. connection = new HubConnectionBuilder()
  71. .WithUrl("https://monitor.veloe.link/hubs/data")
  72. .WithAutomaticReconnect()
  73. .Build();
  74. Func<Exception, Task> reconnecting = ex => Task.Run(() => {
  75. logger.Warning("Reconnecting to WebCoket...");
  76. });
  77. Func<string, Task> reconnected = str => Task.Run(() => {
  78. logger.Warning("Reconnected to WebCoket.");
  79. connection.InvokeAsync("ConnectToGroup", "McTFC");
  80. connection.InvokeAsync("ConnectToGroup", "McVanilla");
  81. connection.InvokeAsync("ConnectToGroup", "McTech");
  82. });
  83. connection.Reconnecting += reconnecting;
  84. connection.Reconnected += reconnected;
  85. connection.On<string>("UpdateMcTFC", (message) =>
  86. {
  87. McStatus status = JsonSerializer.Deserialize<McStatus>(message);
  88. McTfcBlock = $"McTFC: Online {status.NumPlayers}/{status.MaxPlayers}";
  89. mcTfcTimer.Stop();
  90. mcTfcTimer.Start();
  91. //ConsoleText += message;
  92. });
  93. connection.On<string>("UpdateMcVanilla", (message) =>
  94. {
  95. McStatus status = JsonSerializer.Deserialize<McStatus>(message);
  96. McTfcBlock = $"McVanilla: Online {status.NumPlayers}/{status.MaxPlayers}";
  97. mcTechTimer.Stop();
  98. mcTechTimer.Start();
  99. //ConsoleText += message;
  100. });
  101. connection.On<string>("UpdateMcTech", (message) =>
  102. {
  103. McStatus status = JsonSerializer.Deserialize<McStatus>(message);
  104. McTfcBlock = $"McTech: Online {status.NumPlayers}/{status.MaxPlayers}";
  105. mcVanillaTimer.Stop();
  106. mcVanillaTimer.Start();
  107. //ConsoleText += message;
  108. });
  109. mcTfcTimer.Elapsed += OnTimedEventMcTfc;
  110. mcTfcTimer.Start();
  111. mcTechTimer.Elapsed += OnTimedEventMcTech;
  112. mcTechTimer.Start();
  113. mcVanillaTimer.Elapsed += OnTimedEventMcVanilla;
  114. mcVanillaTimer.Start();
  115. connection.StartAsync();
  116. connection.InvokeAsync("ConnectToGroup", "McTFC");
  117. connection.InvokeAsync("ConnectToGroup", "McVanilla");
  118. connection.InvokeAsync("ConnectToGroup", "McTech");
  119. consoleOutputTimer.Elapsed += UpdateConsoleOutput;
  120. consoleOutputTimer.AutoReset = false;
  121. }
  122. int i = 0;
  123. System.Timers.Timer mcTfcTimer = new System.Timers.Timer(30000);
  124. System.Timers.Timer mcTechTimer = new System.Timers.Timer(30000);
  125. System.Timers.Timer mcVanillaTimer = new System.Timers.Timer(30000);
  126. System.Timers.Timer consoleOutputTimer = new(250);
  127. private HubConnection connection;
  128. private string downloadButton = "Download versions";
  129. private string startButton = "Start Minecraft";
  130. private string username;
  131. private StringBuilder consoleText = new StringBuilder();
  132. private int downloadedIndex;
  133. private string argumentsBox;
  134. private bool isNoGameRunning = true;
  135. private bool isUpdateAvailable = false;
  136. private string settingsButton = "Settings";
  137. private string mcTfcBlock = "Wait for update...";
  138. private string mcTechBlock = "Wait for update...";
  139. private string mcVanillaBlock = "Wait for update...";
  140. ILogger logger;
  141. LatestLauncherVersion latestLauncherInfo;
  142. DownloadedVerion downloadedVersion;
  143. ObservableCollection<DownloadedVerion> downloadedVersions;
  144. public ObservableCollection<DownloadedVerion> DownloadedVersions {
  145. get => downloadedVersions;
  146. set
  147. {
  148. this.RaiseAndSetIfChanged(ref downloadedVersions, value);
  149. }
  150. }
  151. public DownloadedVerion DownloadedVerion
  152. {
  153. get => downloadedVersion;
  154. set
  155. {
  156. this.RaiseAndSetIfChanged(ref downloadedVersion, value);
  157. //Settings.lastChosenVersion = value.version;
  158. //logger.Debug("Version choosen: {0}",value.version);
  159. //logger.Debug("Version json: {0}", value.path);
  160. }
  161. }
  162. public int DownloadedIndex
  163. {
  164. get => downloadedIndex;
  165. set
  166. {
  167. this.RaiseAndSetIfChanged(ref downloadedIndex, value);
  168. if (value >= 0 && value < DownloadedVersions.Count)
  169. DownloadedVerion = DownloadedVersions[value];
  170. }
  171. }
  172. public string Greeting => "Welcome to Cringe Launcher!";
  173. public string DownloadButton {
  174. get => downloadButton;
  175. set
  176. {
  177. this.RaiseAndSetIfChanged(ref downloadButton, value);
  178. }
  179. }
  180. public string StartButton
  181. {
  182. get => startButton;
  183. set
  184. {
  185. this.RaiseAndSetIfChanged(ref startButton, value);
  186. }
  187. }
  188. public string Username
  189. {
  190. get => username;
  191. set => this.RaiseAndSetIfChanged(ref username, value);
  192. }
  193. public string ConsoleText
  194. {
  195. get
  196. {
  197. if (consoleText.Length < UInt16.MaxValue)
  198. return consoleText.ToString();
  199. else
  200. return consoleText.ToString(consoleText.Length - UInt16.MaxValue, UInt16.MaxValue);
  201. }
  202. set
  203. {
  204. consoleText.Clear();
  205. consoleText.Append(value);
  206. this.RaisePropertyChanged(nameof(ConsoleText));
  207. ConsoleTextCaretIndex = int.MaxValue;
  208. }
  209. }
  210. public string ArgumentsBox
  211. {
  212. get => argumentsBox;
  213. set
  214. {
  215. this.RaiseAndSetIfChanged(ref argumentsBox, value);
  216. }
  217. }
  218. public string SettingsButton
  219. {
  220. get => settingsButton;
  221. set
  222. {
  223. this.RaiseAndSetIfChanged(ref settingsButton, value);
  224. }
  225. }
  226. public bool IsNoGameRunning
  227. {
  228. get => isNoGameRunning;
  229. set
  230. {
  231. this.RaiseAndSetIfChanged(ref isNoGameRunning, value);
  232. }
  233. }
  234. public bool IsUpdateAvailable
  235. {
  236. get => isUpdateAvailable;
  237. set
  238. {
  239. this.RaiseAndSetIfChanged(ref isUpdateAvailable, value);
  240. }
  241. }
  242. public string McTfcBlock
  243. {
  244. get => mcTfcBlock;
  245. set
  246. {
  247. this.RaiseAndSetIfChanged(ref mcTfcBlock, value);
  248. }
  249. }
  250. public string McTechBlock
  251. {
  252. get => mcTechBlock;
  253. set
  254. {
  255. this.RaiseAndSetIfChanged(ref mcTechBlock, value);
  256. }
  257. }
  258. public string McVanillaBlock
  259. {
  260. get => mcVanillaBlock;
  261. set
  262. {
  263. this.RaiseAndSetIfChanged(ref mcVanillaBlock, value);
  264. }
  265. }
  266. public int ConsoleTextCaretIndex
  267. {
  268. get { return int.MaxValue; }
  269. set
  270. {
  271. this.RaisePropertyChanged(nameof(ConsoleTextCaretIndex));
  272. }
  273. }
  274. public void OnClickCommand()
  275. {
  276. var versionsDownloader = new VersionsDownloader { DataContext = new VersionsDownloaderViewModel() };
  277. if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  278. {
  279. //var versionsDownloaderTask =
  280. versionsDownloader.Closed += updateAvailable;
  281. versionsDownloader.ShowDialog(desktop.MainWindow);
  282. //versionsDownloaderTask.Wait();
  283. }
  284. }
  285. public void StartMinecraft()
  286. {
  287. logger.Debug("Starting minecraft.");
  288. if (DownloadedVerion is null)
  289. return;
  290. int version = 0;
  291. //var verionJsonFileStream = File.OpenRead(DownloadedVerion.path);
  292. using (StreamReader reader = new StreamReader(DownloadedVerion.path))
  293. {
  294. string json = reader.ReadToEnd();
  295. var versionJson = JsonSerializer.Deserialize<Entity.Version.Version>(json);
  296. string arguments = StartCommandBuilder.Build(versionJson, Username);
  297. if (!Settings.useCustomJava)
  298. {
  299. if (versionJson.javaVersion != null)
  300. {
  301. logger.Debug("Java version required: {0}", versionJson.javaVersion.majorVersion);
  302. version = versionJson.javaVersion.majorVersion;
  303. }
  304. else
  305. {
  306. if (versionJson.inheritsFrom != null)
  307. {
  308. using (StreamReader inheritsFromReader = new StreamReader(Settings.MinecraftForlderPath + "versions/" + versionJson.inheritsFrom + "/" + versionJson.inheritsFrom + ".json"))
  309. {
  310. string jsonInheritsFrom = inheritsFromReader.ReadToEnd();
  311. var inheritsFromJson = JsonSerializer.Deserialize<Entity.Version.Version>(jsonInheritsFrom);
  312. if (inheritsFromJson.javaVersion != null)
  313. {
  314. logger.Debug("Java version required: {0}", inheritsFromJson.javaVersion.majorVersion);
  315. version = inheritsFromJson.javaVersion.majorVersion;
  316. }
  317. }
  318. }
  319. }
  320. }
  321. ConsoleText += arguments;
  322. ArgumentsBox = arguments;
  323. }
  324. if (DownloadedVerion is null)
  325. return;
  326. string javaPath = Settings.JavaPath;
  327. if (!Settings.useCustomJava)
  328. javaPath = Settings.MinecraftForlderPath + "javaruntime/" + version + "/bin/java.exe";
  329. logger.Debug("Java version path: {0}", javaPath);
  330. logger.Debug("Minecraft arguments: {0}", ArgumentsBox);
  331. ProcessStartInfo proc;
  332. proc = new ProcessStartInfo
  333. {
  334. UseShellExecute = false,
  335. RedirectStandardOutput = true,
  336. RedirectStandardError = true,
  337. WindowStyle = ProcessWindowStyle.Hidden,
  338. CreateNoWindow = true,
  339. FileName = System.IO.Path.Combine(Settings.MinecraftForlderPath, javaPath),
  340. StandardErrorEncoding = Encoding.UTF8,
  341. WorkingDirectory = Settings.MinecraftForlderPath,
  342. Arguments = ArgumentsBox
  343. };
  344. Process minecraft = new Process();
  345. minecraft.StartInfo = proc;
  346. Task.Run(() =>
  347. {
  348. logger.Debug("Starting java process.");
  349. minecraft.OutputDataReceived += OutputHandler;
  350. minecraft.ErrorDataReceived += OutputHandler;
  351. //minecraft.Exited += ProcessExited; //dont work properly
  352. //* Start process and handlers
  353. //minecraft.WaitForExit();
  354. minecraft.Start();
  355. minecraft.BeginOutputReadLine();
  356. minecraft.BeginErrorReadLine();
  357. if (!Settings.gameLogToLauncher)
  358. {
  359. minecraft.OutputDataReceived -= OutputHandler;
  360. minecraft.CancelOutputRead();
  361. }
  362. return Task.CompletedTask;
  363. });
  364. logger.Debug("Updating Username in Settings");
  365. Settings.Username = username;
  366. Settings.lastChosenVersion = DownloadedVerion.version;
  367. Settings.SaveSettings();
  368. }
  369. void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
  370. {
  371. //Todo create multiple TextBlocks if char limit
  372. if (!consoleOutputTimer.Enabled)
  373. {
  374. consoleOutputTimer.Stop();
  375. consoleOutputTimer.Start();
  376. }
  377. consoleText.Append(outLine.Data + "\n");
  378. }
  379. void LogHandler(object sendingProcess, EventArgs args)
  380. {
  381. if (!consoleOutputTimer.Enabled)
  382. {
  383. consoleOutputTimer.Stop();
  384. consoleOutputTimer.Start();
  385. }
  386. consoleText.Append(((MyEventArgs)args).Data);
  387. }
  388. void UpdateConsoleOutput(Object source, ElapsedEventArgs e)
  389. {
  390. this.RaisePropertyChanged(nameof(ConsoleText));
  391. ScrollToEnd("ConsoleScroll");
  392. }
  393. void ScrollToEnd(string ScrollName)
  394. {
  395. if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  396. {
  397. Dispatcher.UIThread.InvokeAsync(() =>
  398. {
  399. var scroll = desktop.MainWindow.GetControl<ScrollViewer>("ConsoleScroll");
  400. scroll.ScrollToEnd();
  401. });
  402. }
  403. }
  404. //dont work properly
  405. void ProcessExited(object sendingProcess, EventArgs e)
  406. {
  407. IsNoGameRunning = true;
  408. ((Process)sendingProcess).Dispose();
  409. }
  410. public void updateAvailable()
  411. {
  412. if (DownloadedVersions is null)
  413. DownloadedVersions = new();
  414. DownloadedVersions.Clear();
  415. DirectoryInfo versions = new( Settings.MinecraftForlderPath + "versions");
  416. try
  417. {
  418. var dirs = versions.GetDirectories("*", SearchOption.TopDirectoryOnly);
  419. LauncherProfiles profiles = new LauncherProfiles();
  420. profiles.selectedProfile = "NotImplemented";
  421. foreach (var dir in dirs)
  422. {
  423. string checkedPath;
  424. if (File.Exists(checkedPath = dir.FullName + "\\" + dir.Name + ".json"))
  425. {
  426. DownloadedVersions.Add(new DownloadedVerion() { path = checkedPath, version = dir.Name });
  427. profiles.profiles.Add($"Version {dir.Name}", new Profile() { name = dir.Name, lastVersionId = dir.Name, launcherVisibilityOnGameClose = "keep the launcher open" });
  428. }
  429. }
  430. if (Settings.lastChosenVersion != null)
  431. {
  432. DownloadedIndex = 0;
  433. for (int i = 0; i < DownloadedVersions.Count; i++)
  434. {
  435. if (DownloadedVersions[i].version == Settings.lastChosenVersion)
  436. {
  437. DownloadedIndex = i;
  438. break;
  439. }
  440. }
  441. }
  442. if (!File.Exists(Settings.MinecraftForlderPath + "launcher_profiles.json"))
  443. {
  444. var file = File.Create(Settings.MinecraftForlderPath + "launcher_profiles.json");
  445. file.Close();
  446. file.Dispose();
  447. }
  448. var lpString = JsonSerializer.Serialize(profiles);
  449. File.WriteAllText(Settings.MinecraftForlderPath + "launcher_profiles.json", lpString);
  450. }
  451. catch (DirectoryNotFoundException ex)
  452. {
  453. Directory.CreateDirectory(Settings.MinecraftForlderPath + "versions");
  454. return;
  455. }
  456. }
  457. public void updateAvailable(object sendingObject, EventArgs e)
  458. {
  459. updateAvailable();
  460. switch (sendingObject)
  461. {
  462. case VersionsDownloader:
  463. ((VersionsDownloader)sendingObject).Closed -= updateAvailable;
  464. break;
  465. case SettingsWindow:
  466. ((SettingsWindow)sendingObject).Closed -= updateAvailable;
  467. break;
  468. }
  469. }
  470. void OpenSettings()
  471. {
  472. var settingsWindow = new SettingsWindow { DataContext = new SettingsWindowViewModel() };
  473. if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  474. {
  475. //var versionsDownloaderTask =
  476. settingsWindow.Closed += updateAvailable;
  477. settingsWindow.ShowDialog(desktop.MainWindow);
  478. //versionsDownloaderTask.Wait();
  479. //updateAvailable();
  480. }
  481. }
  482. public void DownloadUpdate()
  483. {
  484. logger.Debug("Started updater.exe");
  485. Process updater = new Process();
  486. updater.StartInfo.FileName = "updater.exe";
  487. updater.Start();
  488. if (Avalonia.Application.Current.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
  489. {
  490. //var versionsDownloaderTask =
  491. desktop.MainWindow.Close();
  492. //versionsDownloaderTask.Wait();
  493. //updateAvailable();
  494. }
  495. }
  496. private void OnTimedEventMcTfc(Object source, ElapsedEventArgs e)
  497. {
  498. McTfcBlock = "McTFC: Offline";
  499. }
  500. private void OnTimedEventMcTech(Object source, ElapsedEventArgs e)
  501. {
  502. McTechBlock = "McTech: Offline";
  503. }
  504. private void OnTimedEventMcVanilla(Object source, ElapsedEventArgs e)
  505. {
  506. McVanillaBlock = "McVanilla: Offline";
  507. }
  508. }
  509. public class LatestLauncherVersion
  510. {
  511. public string latest { get; set; }
  512. public string url { get; set; }
  513. }
  514. public class DownloadedVerion
  515. {
  516. public string path;
  517. public string version;
  518. public override string ToString()
  519. {
  520. return version;
  521. }
  522. }
  523. }