VersionsDownloaderViewModel.cs 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  1. using DynamicData;
  2. using ReactiveUI;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Collections.ObjectModel;
  6. using System.ComponentModel;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Text.Json;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using VeloeMinecraftLauncher.Entity.LauncherProfiles;
  13. using VeloeMinecraftLauncher.Entity.VersionManifest;
  14. using VeloeMinecraftLauncher.Utils;
  15. using VeloeMinecraftLauncher.Models.Entity;
  16. using VeloeMinecraftLauncher.Entity.Version;
  17. using System.Diagnostics;
  18. using System.Linq.Expressions;
  19. namespace VeloeMinecraftLauncher.ViewModels;
  20. public class VersionsDownloaderViewModel : ViewModelBase
  21. {
  22. private string _downloadButtonText = "Download";
  23. private bool _showOld = false;
  24. private bool _showSnaps = false;
  25. private bool _installFabric = false;
  26. private bool _installForge = false;
  27. private bool _installOptifine = false;
  28. private bool _installForgeOptifine = false;
  29. private bool _installFabricVisible = false;
  30. private bool _installForgeVisible = false;
  31. private bool _installOptifineVisible = false;
  32. private bool _installForgeOptifineVisible = false;
  33. private bool _downloadJava = false;
  34. private bool _isControlsEnabled = true;
  35. private long _progress = 0;
  36. private long _maxprogressvalue = 100;
  37. private string _downloadingFileName = "No active downloads";
  38. private string _tasksStatusLine = "No tasks started yet";
  39. /// <summary>
  40. /// Token source for downloading tasks
  41. /// </summary>
  42. private CancellationTokenSource _tokenSource = new();
  43. /// <summary>
  44. /// Token source for checking downloading options on selection from verions available for downloading
  45. /// </summary>
  46. private CancellationTokenSource _filteredVersionTokenSource = new();
  47. Serilog.ILogger _logger;
  48. ObservableCollection<Entity.VersionManifest.Version> _filteredVersions;
  49. ObservableCollection<DownloadedVersion> _downloadedVersions;
  50. ObservableCollection<Modpack> _modpackVersions;
  51. ObservableCollection<TreeNode> _downloadedVersionTree;
  52. TreeNode _libraries;
  53. List<Entity.VersionManifest.Version> _modpackVersionsAsVersion;
  54. Entity.VersionManifest.Version _filteredVersion;
  55. DownloadedVersion _downloadedVersion;
  56. Modpack? _selectedModpack;
  57. VersionManifest _versionManifest;
  58. public VersionsDownloaderViewModel()
  59. {
  60. IsControlsEnabled = false;
  61. try
  62. {
  63. _logger = Settings.logger;
  64. Task.Run(async () =>
  65. {
  66. if (FilteredVersions is null)
  67. {
  68. FilteredVersions = new();
  69. }
  70. if (_modpackVersions is null)
  71. {
  72. _modpackVersions = new();
  73. }
  74. if (DownloadedVersionTree is null)
  75. {
  76. _downloadedVersionTree = new();
  77. }
  78. if (DownloadedVersionsDictionary is null)
  79. {
  80. DownloadedVersionsDictionary = new();
  81. }
  82. _logger.Debug("Getting versionManifest.json");
  83. _versionManifest = await Downloader.DownloadAndDeserializeJsonData<VersionManifest>("https://launchermeta.mojang.com/mc/game/version_manifest_v2.json") ?? new();
  84. _modpackVersions.AddRange(await Downloader.DownloadAndDeserializeJsonData<List<Modpack>>("https://files.veloe.link/launcher/modpacks.json") ?? new());
  85. _modpackVersionsAsVersion = _modpackVersions.Select(v=> new Entity.VersionManifest.Version() { Id = v.Name, Type = "modpack", ComplianceLevel = v.Revision}).ToList();
  86. _logger.Debug("Updating available versions to download.");
  87. UpdateList();
  88. SearchGameFolderForVersions();
  89. IsControlsEnabled = true;
  90. });
  91. }
  92. catch (Exception ex)
  93. {
  94. OpenErrorWindow(ex);
  95. }
  96. }
  97. public Entity.VersionManifest.Version FilteredVersion
  98. {
  99. get { return _filteredVersion; }
  100. set {
  101. this.RaiseAndSetIfChanged(ref _filteredVersion, value);
  102. InstallFabric = false;
  103. InstallForge = false;
  104. InstallOptifine = false;
  105. InstallForgeOptifine = false;
  106. if (value is null)
  107. return;
  108. if (value.Type == "modpack")
  109. {
  110. try
  111. {
  112. if (System.IO.File.Exists(Settings.minecraftForlderPath + $"versions/{value.Id}/revision.json"))
  113. {
  114. if (value.ComplianceLevel > JsonSerializer.Deserialize<int>(System.IO.File.ReadAllText(Settings.minecraftForlderPath + $"versions/{value.Id}/revision.json")))
  115. DownloadButtonText = "Update Modpack";
  116. else
  117. DownloadButtonText = "Reinstall Modpack";
  118. }
  119. else
  120. if (System.IO.Directory.Exists($"{Settings.minecraftForlderPath}versions/{value.Id}") && System.IO.File.Exists($"{Settings.minecraftForlderPath}versions/{value.Id}/{value.Id}.json"))
  121. DownloadButtonText = "Update Modpack";
  122. else
  123. DownloadButtonText = "Download Modpack";
  124. }
  125. catch (Exception)
  126. {
  127. DownloadButtonText = "Update Modpack";
  128. }
  129. }
  130. else
  131. {
  132. if (System.IO.File.Exists(Settings.minecraftForlderPath + $"versions/{value.Id}/{value.Id}.json"))
  133. DownloadButtonText = "Reinstall";
  134. else
  135. DownloadButtonText = "Download";
  136. }
  137. try
  138. {
  139. Task.Run(() =>
  140. {
  141. _filteredVersionTokenSource.Cancel();
  142. _filteredVersionTokenSource.Dispose();
  143. _filteredVersionTokenSource = new();
  144. try
  145. {
  146. if (Downloader.IsFileAvaliable(@$"https://files.veloe.link/launcher/forge/Forge{value.Id}/Forge{value.Id}.json", _filteredVersionTokenSource.Token).Result)
  147. {
  148. if (Downloader.IsFileAvaliable(@$"https://files.veloe.link/launcher/forge/Forge{value.Id}/Optifine{value.Id}.jar", _filteredVersionTokenSource.Token).Result)
  149. InstallForgeOptifineVisible = true;
  150. InstallForgeVisible = true;
  151. }
  152. else
  153. {
  154. InstallForgeVisible = false;
  155. InstallForgeOptifineVisible = false;
  156. }
  157. if (Downloader.IsFileAvaliable(@$"https://files.veloe.link/launcher/fabric/Fabric{value.Id}/Fabric{value.Id}.json", _filteredVersionTokenSource.Token).Result)
  158. InstallFabricVisible = true;
  159. else
  160. InstallFabricVisible = false;
  161. if (Downloader.IsFileAvaliable(@$"https://files.veloe.link/launcher/optifine/Optifine{value.Id}/Optifine{value.Id}.json", _filteredVersionTokenSource.Token).Result)
  162. InstallOptifineVisible = true;
  163. else
  164. InstallOptifineVisible = false;
  165. }
  166. catch (OperationCanceledException)
  167. {
  168. InstallForgeVisible = false;
  169. InstallForgeOptifineVisible = false;
  170. InstallFabricVisible = false;
  171. InstallOptifineVisible = false;
  172. }
  173. });
  174. }
  175. catch (Exception ex)
  176. {
  177. OpenErrorWindow(ex);
  178. }
  179. }
  180. }
  181. public DownloadedVersion DownloadedVersion
  182. {
  183. get => _downloadedVersion;
  184. set
  185. {
  186. this.RaiseAndSetIfChanged(ref _downloadedVersion, value);
  187. Task.Run(() =>
  188. {
  189. try
  190. {
  191. IsControlsEnabled = false;
  192. DownloadedVersionTree.Clear();
  193. DownloadedVersionTree = new();
  194. this.RaisePropertyChanged(nameof(DownloadedVersionTree));
  195. DownloadedVersionsDictionary.Clear();
  196. if (value is null)
  197. {
  198. IsControlsEnabled = true;
  199. return;
  200. }
  201. Entity.Version.Version? version = null;
  202. foreach (var dversion in DownloadedVersions)
  203. {
  204. string json;
  205. using (StreamReader reader = new StreamReader(dversion.path))
  206. {
  207. json = reader.ReadToEnd();
  208. }
  209. var versionObject = JsonSerializer.Deserialize<Entity.Version.Version>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
  210. DownloadedVersionsDictionary.Add(dversion.version, versionObject);
  211. if (dversion == _downloadedVersion)
  212. {
  213. version = versionObject;
  214. }
  215. }
  216. if (version is null)
  217. {
  218. OpenErrorWindow("Json file is invalid!");
  219. return;
  220. }
  221. var versionDir = new FileInfo(value.path)?.Directory?.FullName;
  222. if (versionDir is null)
  223. {
  224. OpenErrorWindow("Version folder is invalid!");
  225. return;
  226. }
  227. //get version
  228. DownloadedVersionTree.Add(new TreeNode() { Title = "Version: " + (version.InheritsFrom ?? version.Id) });
  229. //calc Size
  230. var allSize = 0L;
  231. var dirSize = 0L;
  232. var dirInfo = new DirectoryInfo(versionDir);
  233. var sizeTreeNode = new TreeNode();
  234. var dirTreeNode = new TreeNode();
  235. dirTreeNode.SubNode.AddRange(DirectoryToTreeNode(dirInfo,out dirSize));
  236. dirTreeNode.Title = "versions/" + dirInfo.Name + " (" + BytesToString(dirSize) + ")";
  237. sizeTreeNode.SubNode.Add(dirTreeNode);
  238. allSize += dirSize;
  239. if (version.InheritsFrom is null)
  240. {
  241. dirInfo = new DirectoryInfo(Settings.minecraftForlderPath);
  242. sizeTreeNode.SubNode.AddRange(
  243. DirectoryToTreeNode(
  244. dirInfo,
  245. out dirSize,
  246. (dir) => dir.Name == ".mixin.out" ||
  247. dir.Name == "assets" ||
  248. dir.Name == "javaruntime" ||
  249. dir.Name == "libraries" ||
  250. dir.Name == "logs" ||
  251. dir.Name == "versions",
  252. (file) => file.Name.Contains("Veloe") ||
  253. file.Name.Contains("log") ||
  254. file.Name.Contains("exe") ||
  255. file.Name == "launcher_profiles.json" ||
  256. file.Name == "libHarfBuzzSharp.dll" ||
  257. file.Name == "libSkiaSharp.dll" ||
  258. file.Name == "settings.json")
  259. );
  260. allSize += dirSize;
  261. }
  262. sizeTreeNode.Title = "Size: " + BytesToString(allSize);
  263. DownloadedVersionTree.Add(sizeTreeNode);
  264. //calc Worlds
  265. dirInfo = null;
  266. if (version.InheritsFrom is null && Directory.Exists(Settings.minecraftForlderPath + "saves"))
  267. dirInfo = new DirectoryInfo(Settings.minecraftForlderPath + "saves");
  268. else
  269. if (Directory.Exists(versionDir + "/saves"))
  270. dirInfo = new DirectoryInfo(versionDir + "/saves");
  271. if (dirInfo is not null)
  272. {
  273. var worldsTreeNode = new TreeNode() { Title = "Worlds: " + dirInfo.GetDirectories().Count() };
  274. foreach (var world in dirInfo.GetDirectories())
  275. { worldsTreeNode.SubNode.Add(new TreeNode() { Title = world.Name }); }
  276. DownloadedVersionTree.Add(worldsTreeNode);
  277. }
  278. //check modloader
  279. var modsTreeNode = new TreeNode();
  280. if (version.InheritsFrom is null)
  281. modsTreeNode.Title = "Modloader: No";
  282. else if (version.Libraries.Any(l => l.Downloads?.Artifact?.Url?.Contains("forge") ?? false))
  283. {
  284. modsTreeNode.Title = "Modloader: Forge";
  285. OpenErrorWindow("This version contains forge modloader, it installs some libraries that can't be displayed and deleted in current launcher versions manager.");
  286. }
  287. else if (version.Libraries.Any(l => l.Name.Contains("fabric")))
  288. modsTreeNode.Title = "Modloader: Fabric";
  289. //get mods list
  290. if (modsTreeNode.Title != "No" && Directory.Exists(versionDir + "/mods"))
  291. {
  292. dirInfo = new DirectoryInfo(versionDir + "/mods");
  293. modsTreeNode.Title += " (" + dirInfo.EnumerateFiles("*.jar", SearchOption.TopDirectoryOnly).Count() + ")";
  294. foreach (var mod in dirInfo.EnumerateFiles("*.jar", SearchOption.TopDirectoryOnly))
  295. { modsTreeNode.SubNode.Add(new TreeNode() { Title = mod.Name }); }
  296. }
  297. DownloadedVersionTree.Add(modsTreeNode);
  298. //calc resourcepacks
  299. dirInfo = null;
  300. if (version.InheritsFrom is null && Directory.Exists(Settings.minecraftForlderPath + "resourcepacks"))
  301. dirInfo = new DirectoryInfo(Settings.minecraftForlderPath + "resourcepacks");
  302. else
  303. if (Directory.Exists(versionDir + "/resourcepacks"))
  304. dirInfo = new DirectoryInfo(versionDir + "/resourcepacks");
  305. if (dirInfo is not null)
  306. {
  307. var resourcepacksTreeNode = new TreeNode();
  308. resourcepacksTreeNode.Title = "Resoursepacks: " + (dirInfo?.GetDirectories()?.Count() + dirInfo?.GetFiles().Count() ?? 0).ToString();
  309. foreach (var resourcepack in dirInfo?.GetFileSystemInfos())
  310. { resourcepacksTreeNode.SubNode.Add(new TreeNode() { Title = resourcepack.Name }); }
  311. DownloadedVersionTree.Add(resourcepacksTreeNode);
  312. }
  313. //calc assets
  314. var assetsFolderName = version.Assets;
  315. if (version.Assets is null &&
  316. version.InheritsFrom is not null &&
  317. DownloadedVersionsDictionary.TryGetValue(version.InheritsFrom, out var outVersion) &&
  318. outVersion?.Assets is not null)
  319. {
  320. assetsFolderName = outVersion.Assets;
  321. }
  322. if (Directory.Exists(Settings.minecraftForlderPath + "assets/" + assetsFolderName))
  323. {
  324. dirInfo = new DirectoryInfo(Settings.minecraftForlderPath + "assets/" + assetsFolderName);
  325. allSize = 0;
  326. foreach (var file in dirInfo.EnumerateFiles("*", SearchOption.AllDirectories))
  327. { allSize += file.Length; }
  328. var assetsTreeNode = new TreeNode();
  329. var usedByVersionCount = 0;
  330. foreach (var dictionaryVersion in DownloadedVersionsDictionary)
  331. {
  332. if ((dictionaryVersion.Value?.Assets == assetsFolderName &&
  333. dictionaryVersion.Value?.InheritsFrom is null) ||
  334. (dictionaryVersion.Value?.InheritsFrom is not null &&
  335. DownloadedVersionsDictionary.TryGetValue(dictionaryVersion.Value.InheritsFrom, out outVersion) &&
  336. outVersion?.Assets == assetsFolderName))
  337. {
  338. usedByVersionCount++;
  339. assetsTreeNode.SubNode.Add(new TreeNode() { Title = dictionaryVersion.Key });
  340. }
  341. }
  342. assetsTreeNode.Title = "Assets: " + version.Assets + " (" + BytesToString(allSize) + ") (" + usedByVersionCount + ")";
  343. DownloadedVersionTree.Add(assetsTreeNode);
  344. }
  345. // calc libraries
  346. var usedLibraries = version.Libraries;
  347. var libTreeNode = new TreeNode();
  348. libTreeNode.Title = "Libraries";
  349. if (version.InheritsFrom is not null && DownloadedVersionsDictionary.TryGetValue(version.InheritsFrom, out outVersion) && outVersion is not null)
  350. {
  351. usedLibraries.AddRange(outVersion.Libraries);
  352. }
  353. usedLibraries =
  354. usedLibraries
  355. .Where(l =>
  356. File.Exists(Path.Combine(Settings.minecraftForlderPath + "libraries/" + l.Downloads?.Artifact?.Path)) ||
  357. File.Exists(Path.Combine(Settings.minecraftForlderPath + "libraries/" + l.Downloads?.Classifiers?.NativesLinux?.Path)) ||
  358. File.Exists(Path.Combine(Settings.minecraftForlderPath + "libraries/" + l.Downloads?.Classifiers?.NativesWindows?.Path)) ||
  359. File.Exists(Path.Combine(Settings.minecraftForlderPath + "libraries/" + l.Downloads?.Classifiers?.NativesWindows64?.Path)) ||
  360. File.Exists(Path.Combine(Settings.minecraftForlderPath + "libraries/" + l.Downloads?.Classifiers?.NativesWindows32?.Path)) ||
  361. File.Exists(Path.Combine(Settings.minecraftForlderPath + "libraries/" + StartCommandBuilder.GetLibPathFromName(l.Name, true)))
  362. )
  363. .ToList();
  364. var libraries = GetLibrariesFromVersions(DownloadedVersionsDictionary)
  365. .Where(v => usedLibraries.Any(u => v.Value.Name == u.Name))
  366. .GroupBy(a => a.Value.Name)
  367. .Select(g =>
  368. {
  369. return new {
  370. Name = g.Key,
  371. Count = g.Select(a => a.Key).Distinct().Count(),
  372. Versions = g.Select(a => a.Key).Distinct(),
  373. LibraryUniqueInstances = g.Select(a => a.Value).Distinct() //IEnumerable cause there can be several lib blocks with different rules in one version json
  374. };
  375. });
  376. foreach (var lib in libraries)
  377. {
  378. var subLibTreeNode = new TreeNode()
  379. {
  380. Title = lib.Name + " (" + lib.Count + ")",
  381. };
  382. //if only one version uses it (selected version), then add path to lib in Tag for deletion
  383. if (lib.Count == 1)
  384. {
  385. subLibTreeNode.Tag = lib.LibraryUniqueInstances.Where(l => l.Downloads?.Artifact?.Path is not null).Select(l => l.Downloads?.Artifact?.Path).FirstOrDefault() ?? string.Empty;
  386. //if fabric library
  387. if (File.Exists(Settings.minecraftForlderPath + "libraries/" + StartCommandBuilder.GetLibPathFromName(lib.Name,true)))
  388. subLibTreeNode.Tag = StartCommandBuilder.GetLibPathFromName(lib.Name,true);
  389. }
  390. var subLibUsedVersionsTreeNodeHeader = new TreeNode() { Title = "Using in versions:" };
  391. foreach (var ver in lib.Versions)
  392. subLibUsedVersionsTreeNodeHeader.SubNode.Add(new TreeNode() { Title = ver });
  393. if (subLibUsedVersionsTreeNodeHeader.SubNode.Count > 0)
  394. subLibTreeNode.SubNode.Add(subLibUsedVersionsTreeNodeHeader);
  395. if (lib.LibraryUniqueInstances.Any(l=>l.Natives is not null) || lib.LibraryUniqueInstances.Any(l=>l.Downloads?.Classifiers is not null))
  396. {
  397. var subLibNativesTreeNodeHeader = new TreeNode() { Title = "Natives:" };
  398. //check classifiers
  399. var libraryNativeInstance = lib.LibraryUniqueInstances.Where(l => l.Natives is not null || l.Downloads?.Classifiers is not null).First();
  400. if (libraryNativeInstance.Downloads?.Classifiers?.NativesWindows is not null)
  401. {
  402. subLibNativesTreeNodeHeader.SubNode.Add(new TreeNode()
  403. {
  404. Title = Path.GetFileName(libraryNativeInstance.Downloads?.Classifiers?.NativesWindows.Path) ?? "No lib name",
  405. Tag = lib.Count == 1 ? libraryNativeInstance.Downloads?.Classifiers?.NativesWindows?.Path ?? string.Empty : string.Empty
  406. });
  407. }
  408. if (libraryNativeInstance.Downloads?.Classifiers?.NativesWindows32 is not null)
  409. {
  410. subLibNativesTreeNodeHeader.SubNode.Add(new TreeNode()
  411. {
  412. Title = Path.GetFileName(libraryNativeInstance.Downloads?.Classifiers?.NativesWindows32.Path) ?? "No lib name",
  413. Tag = lib.Count == 1 ? libraryNativeInstance.Downloads?.Classifiers?.NativesWindows32?.Path ?? string.Empty : string.Empty
  414. });
  415. }
  416. if (libraryNativeInstance.Downloads?.Classifiers?.NativesWindows64 is not null)
  417. {
  418. subLibNativesTreeNodeHeader.SubNode.Add(new TreeNode()
  419. {
  420. Title = Path.GetFileName(libraryNativeInstance.Downloads?.Classifiers?.NativesWindows64.Path) ?? "No lib name",
  421. Tag = lib.Count == 1 ? libraryNativeInstance.Downloads?.Classifiers?.NativesWindows64?.Path ?? string.Empty : string.Empty
  422. });
  423. }
  424. if (libraryNativeInstance.Downloads?.Classifiers?.NativesLinux is not null)
  425. {
  426. subLibNativesTreeNodeHeader.SubNode.Add(new TreeNode()
  427. {
  428. Title = Path.GetFileName(libraryNativeInstance.Downloads?.Classifiers?.NativesLinux.Path) ?? "No lib name",
  429. Tag = lib.Count == 1 ? libraryNativeInstance.Downloads?.Classifiers?.NativesLinux?.Path ?? string.Empty : string.Empty
  430. });
  431. }
  432. if (subLibNativesTreeNodeHeader.SubNode.Count > 0)
  433. subLibTreeNode.SubNode.Add(subLibNativesTreeNodeHeader);
  434. }
  435. libTreeNode.SubNode.Add(subLibTreeNode);
  436. }
  437. _libraries = libTreeNode;
  438. DownloadedVersionTree.Add(libTreeNode);
  439. }
  440. finally
  441. {
  442. this.RaisePropertyChanged(nameof(DownloadedVersionTree));
  443. IsControlsEnabled = true;
  444. }
  445. });
  446. }
  447. }
  448. public Dictionary<string,Entity.Version.Version?> DownloadedVersionsDictionary { get; set; }
  449. public ObservableCollection<Entity.VersionManifest.Version> FilteredVersions
  450. {
  451. get => _filteredVersions;
  452. set => this.RaiseAndSetIfChanged(ref _filteredVersions, value);
  453. }
  454. public ObservableCollection<DownloadedVersion> DownloadedVersions
  455. {
  456. get => _downloadedVersions;
  457. set => this.RaiseAndSetIfChanged(ref _downloadedVersions, value);
  458. }
  459. public ObservableCollection<TreeNode> DownloadedVersionTree
  460. {
  461. get => _downloadedVersionTree;
  462. set => this.RaiseAndSetIfChanged(ref _downloadedVersionTree, value);
  463. }
  464. public string DownloadButtonText
  465. {
  466. get => _downloadButtonText;
  467. set => this.RaiseAndSetIfChanged(ref _downloadButtonText, value);
  468. }
  469. public bool ShowOld
  470. {
  471. get => _showOld;
  472. set {
  473. this.RaiseAndSetIfChanged(ref _showOld, value);
  474. UpdateList();
  475. }
  476. }
  477. public bool ShowSnaps
  478. {
  479. get => _showSnaps;
  480. set {
  481. this.RaiseAndSetIfChanged(ref _showSnaps, value);
  482. UpdateList();
  483. }
  484. }
  485. public long Progress
  486. {
  487. get => _progress;
  488. set => this.RaiseAndSetIfChanged(ref _progress, value);
  489. }
  490. public long MaxProgressValue
  491. {
  492. get => _maxprogressvalue;
  493. set => this.RaiseAndSetIfChanged(ref _maxprogressvalue, value);
  494. }
  495. public string DownloadingFileName
  496. {
  497. get => _downloadingFileName;
  498. set => this.RaiseAndSetIfChanged(ref _downloadingFileName, value);
  499. }
  500. public string TasksStatusLine
  501. {
  502. get => _tasksStatusLine;
  503. set => this.RaiseAndSetIfChanged(ref _tasksStatusLine, value);
  504. }
  505. public bool InstallForge
  506. {
  507. get => _installForge;
  508. set
  509. {
  510. this.RaiseAndSetIfChanged(ref _installForge, value);
  511. if (InstallFabric)
  512. InstallFabric = false;
  513. }
  514. }
  515. public bool InstallFabric
  516. {
  517. get => _installFabric;
  518. set
  519. {
  520. this.RaiseAndSetIfChanged(ref _installFabric, value);
  521. if (InstallForge)
  522. InstallForge = false;
  523. }
  524. }
  525. public bool InstallOptifine
  526. {
  527. get => _installOptifine;
  528. set => this.RaiseAndSetIfChanged(ref _installOptifine, value);
  529. }
  530. public bool InstallForgeOptifine
  531. {
  532. get { return _installForgeOptifine; }
  533. set
  534. {
  535. this.RaiseAndSetIfChanged(ref _installForgeOptifine, value);
  536. if (value)
  537. InstallForge = true;
  538. }
  539. }
  540. public bool InstallForgeVisible
  541. {
  542. get => _installForgeVisible;
  543. set => this.RaiseAndSetIfChanged(ref _installForgeVisible, value);
  544. }
  545. public bool InstallFabricVisible
  546. {
  547. get => _installFabricVisible;
  548. set => this.RaiseAndSetIfChanged(ref _installFabricVisible, value);
  549. }
  550. public bool InstallOptifineVisible
  551. {
  552. get => _installOptifineVisible;
  553. set => this.RaiseAndSetIfChanged(ref _installOptifineVisible, value);
  554. }
  555. public bool InstallForgeOptifineVisible
  556. {
  557. get => _installForgeOptifineVisible;
  558. set => this.RaiseAndSetIfChanged(ref _installForgeOptifineVisible, value);
  559. }
  560. public bool DownloadJava
  561. {
  562. get => _downloadJava;
  563. set => this.RaiseAndSetIfChanged(ref _downloadJava, value);
  564. }
  565. public bool IsControlsEnabled
  566. {
  567. get => _isControlsEnabled;
  568. set => this.RaiseAndSetIfChanged(ref _isControlsEnabled, value);
  569. }
  570. public async Task OnStartBunttonClick()
  571. {
  572. await Task.Run(async () => {
  573. if (FilteredVersion is null)
  574. return TaskStatus.Faulted;
  575. if (FilteredVersion.Type == "modpack")
  576. {
  577. _selectedModpack = _modpackVersions.Where(m => m.Name == FilteredVersion.Id).FirstOrDefault();
  578. if (_selectedModpack is null)
  579. return TaskStatus.Faulted;
  580. if (FilteredVersions.Where(x => x.Id == _selectedModpack.Version).FirstOrDefault() is null)
  581. return TaskStatus.Faulted;
  582. await Task.Run(async () => await Downloader.StartDownloadModpack(
  583. value => DownloadingFileName = value,
  584. value => TasksStatusLine = value,
  585. value => IsControlsEnabled = value,
  586. value => Progress = value,
  587. FilteredVersions,
  588. _selectedModpack,
  589. _tokenSource.Token,
  590. DownloadJava,
  591. InstallFabric = _selectedModpack.Fabric,
  592. InstallForge = _selectedModpack.Forge,
  593. InstallOptifine = _selectedModpack.Optifine,
  594. InstallForgeOptifine = _selectedModpack.ForgeOptifine));
  595. }
  596. else
  597. {
  598. _logger.Debug("Downloading {0}.json", FilteredVersion.Id);
  599. DownloadingFileName = $"{FilteredVersion.Id}.json";
  600. var versionJson = await Downloader.DownloadAndDeserializeJsonData<Entity.Version.Version>(FilteredVersion.Url, Settings.minecraftForlderPath + "versions/" + FilteredVersion.Id + "/", FilteredVersion.Id + ".json");
  601. if (versionJson is not null)
  602. await Downloader.StartDownload(
  603. value => DownloadingFileName = value,
  604. value => TasksStatusLine = value,
  605. value => IsControlsEnabled = value,
  606. value => Progress = value,
  607. versionJson,
  608. _tokenSource.Token,
  609. DownloadJava,
  610. InstallForge,
  611. InstallOptifine,
  612. InstallForgeOptifine,
  613. InstallFabric);
  614. }
  615. SearchGameFolderForVersions();
  616. return TaskStatus.RanToCompletion;
  617. });
  618. }
  619. public async Task OnDeleteButtonClick()
  620. {
  621. await Task.Run(() => {
  622. try
  623. {
  624. IsControlsEnabled = false;
  625. DownloadedVersionTree.Clear();
  626. DownloadedVersionTree = new();
  627. this.RaisePropertyChanged(nameof(DownloadedVersionTree));
  628. DownloadedVersionsDictionary.Clear();
  629. DownloadedVersionsDictionary = new();
  630. Entity.Version.Version? version = null;
  631. foreach (var dversion in DownloadedVersions)
  632. {
  633. string json;
  634. using (StreamReader reader = new StreamReader(dversion.path))
  635. {
  636. json = reader.ReadToEnd();
  637. }
  638. var versionObject = JsonSerializer.Deserialize<Entity.Version.Version>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
  639. DownloadedVersionsDictionary.Add(dversion.version, versionObject);
  640. if (dversion == _downloadedVersion)
  641. {
  642. version = versionObject;
  643. }
  644. }
  645. if (version is null)
  646. {
  647. OpenErrorWindow("Json file is invalid!");
  648. return;
  649. }
  650. var versionDir = new FileInfo(DownloadedVersion.path)?.Directory?.FullName;
  651. if (versionDir is null)
  652. {
  653. OpenErrorWindow("Version folder is invalid!");
  654. return;
  655. }
  656. var dirInfo = new DirectoryInfo(versionDir);
  657. if (version.InheritsFrom is null && DownloadedVersionsDictionary.Where(v=>v.Value.InheritsFrom is null).Count() == 1)
  658. {
  659. //if vanilla
  660. Debug.WriteLine("Vanilla root directories deleted!");
  661. if (Directory.Exists(Settings.minecraftForlderPath + "saves"))
  662. Directory.Delete(Settings.minecraftForlderPath + "saves", true);
  663. if (Directory.Exists(Settings.minecraftForlderPath + "resourcepacks"))
  664. Directory.Delete(Settings.minecraftForlderPath + "resourcepacks", true);
  665. if (Directory.Exists(Settings.minecraftForlderPath + "shaderpacks"))
  666. Directory.Delete(Settings.minecraftForlderPath + "shaderpacks", true);
  667. }
  668. //calc assets
  669. var assetsFolderName = version.Assets;
  670. if (version.Assets is null &&
  671. version.InheritsFrom is not null &&
  672. DownloadedVersionsDictionary.TryGetValue(version.InheritsFrom, out var outVersion) &&
  673. outVersion?.Assets is not null)
  674. {
  675. assetsFolderName = outVersion.Assets;
  676. }
  677. if (Directory.Exists(Settings.minecraftForlderPath + "assets/" + assetsFolderName))
  678. {
  679. var usedByVersionCount = 0;
  680. foreach (var dictionaryVersion in DownloadedVersionsDictionary)
  681. {
  682. if ((dictionaryVersion.Value?.Assets == assetsFolderName &&
  683. dictionaryVersion.Value?.InheritsFrom is null) ||
  684. (dictionaryVersion.Value?.InheritsFrom is not null &&
  685. DownloadedVersionsDictionary.TryGetValue(dictionaryVersion.Value.InheritsFrom, out outVersion) &&
  686. outVersion?.Assets == assetsFolderName))
  687. {
  688. usedByVersionCount++;
  689. }
  690. }
  691. //delete assets if only deleting version used it
  692. if (usedByVersionCount == 1)
  693. {
  694. Debug.WriteLine(Settings.minecraftForlderPath + "assets/" + assetsFolderName);
  695. Directory.Delete(Settings.minecraftForlderPath + "assets/" + assetsFolderName,true);
  696. }
  697. }
  698. // calc libraries
  699. DeleteLibrariesFromTreeNode(_libraries);
  700. // delete version dir
  701. Debug.WriteLine(versionDir);
  702. Directory.Delete(versionDir, true);
  703. }
  704. catch (Exception ex)
  705. {
  706. OpenErrorWindow(ex);
  707. }
  708. finally
  709. {
  710. SearchGameFolderForVersions();
  711. IsControlsEnabled = true;
  712. }
  713. });
  714. }
  715. static string[] _size_label = { "bytes", "KB", "MB", "GB" };
  716. private string BytesToString(long size)
  717. {
  718. var j = 0;
  719. var result = (double)size;
  720. while (j < _size_label.Length && result > 1024)
  721. {
  722. result = result / 1024;
  723. j++;
  724. }
  725. return string.Format("{0:N2}", result) + " " + _size_label[j];
  726. }
  727. private List<TreeNode> DirectoryToTreeNode(DirectoryInfo? dirInfo, out long size, Expression<Func<DirectoryInfo?, bool>>? dirExpression = null, Expression<Func<FileInfo?,bool>>? fileExpression = null)
  728. {
  729. size = 0L;
  730. var nodes = new List<TreeNode>();
  731. if (!(dirInfo is not null && dirInfo.Exists)) return nodes;
  732. if (dirExpression is null)
  733. dirExpression = (x) => false;
  734. if (fileExpression is null)
  735. fileExpression = (x) => false;
  736. var dirDelegate = dirExpression.Compile();
  737. var fileDelegate = fileExpression.Compile();
  738. foreach (var dir in dirInfo.EnumerateDirectories("*", SearchOption.TopDirectoryOnly))
  739. {
  740. if (dirDelegate(dir)) continue;
  741. var subDirSize = 0L;
  742. var subDirTreeNode = new TreeNode();
  743. subDirTreeNode.SubNode.AddRange(DirectoryToTreeNode(dir,out subDirSize));
  744. subDirTreeNode.Title = dir.Name + " (" + BytesToString(subDirSize) + ")";
  745. nodes.Add(subDirTreeNode);
  746. size += subDirSize;
  747. }
  748. foreach (var file in dirInfo.EnumerateFiles("*", SearchOption.TopDirectoryOnly))
  749. {
  750. if (fileDelegate(file)) continue;
  751. nodes.Add(new TreeNode() { Title = file.Name + " (" + BytesToString(file.Length) + ")" });
  752. size += file.Length;
  753. }
  754. return nodes;
  755. }
  756. private void DeleteLibrariesFromTreeNode(TreeNode library)
  757. {
  758. foreach (var node in library.SubNode)
  759. DeleteLibrariesFromTreeNode(node);
  760. if (!string.IsNullOrEmpty(library.Tag))
  761. {
  762. var libFileInfo = new FileInfo(Settings.minecraftForlderPath + "libraries/" + library.Tag);
  763. var libDir = libFileInfo.Directory;
  764. if(libDir?.Exists == false)
  765. {
  766. Debug.WriteLine($"Directory {libDir.FullName} does not exists! Subnode: {library.Title}");
  767. _logger.Warning($"Directory {libDir.FullName} does not exists!");
  768. return;
  769. }
  770. if (libDir?.GetFileSystemInfos().Count() > 1)
  771. {
  772. Debug.WriteLine(libFileInfo.FullName);
  773. libFileInfo.Delete();
  774. }
  775. else
  776. {
  777. Debug.WriteLine(libDir?.FullName);
  778. libDir?.Delete(true);
  779. }
  780. }
  781. }
  782. private void UpdateList()
  783. {
  784. try
  785. {
  786. FilteredVersions.Clear();
  787. if (_versionManifest.Versions is null)
  788. return;
  789. FilteredVersions.AddRange(_modpackVersionsAsVersion);
  790. FilteredVersions.AddRange(_versionManifest.Versions.Where(version => ShowSnaps && version.Type == "snapshot" || ShowOld && version.Type is ("old_alpha" or "old_beta") || version.Type == "release"));
  791. }
  792. catch (Exception ex)
  793. {
  794. OpenErrorWindow(ex);
  795. }
  796. }
  797. private void SearchGameFolderForVersions()
  798. {
  799. if (DownloadedVersions is null)
  800. DownloadedVersions = new();
  801. DownloadedVersions.Clear();
  802. DownloadedVersions = new();
  803. DirectoryInfo versions = new(Settings.minecraftForlderPath + "versions");
  804. try
  805. {
  806. var dirs = versions.GetDirectories("*", SearchOption.TopDirectoryOnly);
  807. LauncherProfiles profiles = new LauncherProfiles();
  808. profiles.SelectedProfile = "NotImplemented";
  809. foreach (var dir in dirs)
  810. {
  811. _logger.Debug("Checking folder {0}", dir.Name);
  812. string checkedPath;
  813. if (File.Exists(checkedPath = dir.FullName + "/" + dir.Name + ".json"))
  814. {
  815. _logger.Debug("Found version {0}", dir.Name);
  816. DownloadedVersions.Add(new DownloadedVersion(checkedPath, dir.Name));
  817. profiles.Profiles.Add($"Version {dir.Name}", new Profile() { Name = dir.Name, LastVersionId = dir.Name, LauncherVisibilityOnGameClose = "keep the launcher open" });
  818. }
  819. }
  820. }
  821. catch (DirectoryNotFoundException)
  822. {
  823. Directory.CreateDirectory(Settings.minecraftForlderPath + "versions");
  824. return;
  825. }
  826. }
  827. public void OnOpenForlder()
  828. {
  829. if (DownloadedVersion?.version is not null && Path.Exists(Settings.minecraftForlderPath + "versions/" + DownloadedVersion.version))
  830. Process.Start(new System.Diagnostics.ProcessStartInfo() { FileName = Settings.minecraftForlderPath + "versions/" + DownloadedVersion.version, UseShellExecute = true });
  831. }
  832. public void OnClosing(object sender, CancelEventArgs args)
  833. {
  834. _tokenSource.Cancel();
  835. _tokenSource.Dispose();
  836. _filteredVersionTokenSource.Cancel();
  837. _filteredVersionTokenSource.Dispose();
  838. }
  839. private IEnumerable<KeyValuePair<string,Library>> GetLibrariesFromVersions(Dictionary<string, Entity.Version.Version?> versions)
  840. {
  841. foreach (var version in versions)
  842. {
  843. if (version.Value is null) continue;
  844. if (version.Value.InheritsFrom is not null && versions.TryGetValue(version.Value.InheritsFrom,out var inheritVersion) && inheritVersion?.Libraries is not null)
  845. {
  846. foreach (var lib in inheritVersion.Libraries)
  847. yield return new KeyValuePair<string, Library>(version.Key, lib);
  848. }
  849. foreach (var lib in version.Value.Libraries)
  850. yield return new KeyValuePair<string, Library>(version.Key,lib);
  851. }
  852. }
  853. }
  854. public class TreeNode
  855. {
  856. public TreeNode()
  857. {
  858. Title = "Default";
  859. SubNode = new();
  860. Tag = string.Empty;
  861. }
  862. public string Title { get; set; }
  863. public string Tag { get; set; }
  864. public List<TreeNode> SubNode { get; set; }
  865. public override string ToString()
  866. {
  867. return Title;
  868. }
  869. }