1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030 |
- using DynamicData;
- using ReactiveUI;
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.ComponentModel;
- using System.IO;
- using System.Linq;
- using System.Text.Json;
- using System.Threading;
- using System.Threading.Tasks;
- using VeloeMinecraftLauncher.Entity.LauncherProfiles;
- using VeloeMinecraftLauncher.Entity.VersionManifest;
- using VeloeMinecraftLauncher.Utils;
- using VeloeMinecraftLauncher.Models.Entity;
- using VeloeMinecraftLauncher.Entity.Version;
- using System.Diagnostics;
- using System.Linq.Expressions;
- namespace VeloeMinecraftLauncher.ViewModels;
- public class VersionsDownloaderViewModel : ViewModelBase
- {
- private string _downloadButtonText = "Download";
- private bool _showOld = false;
- private bool _showSnaps = false;
- private bool _installFabric = false;
- private bool _installForge = false;
- private bool _installOptifine = false;
- private bool _installForgeOptifine = false;
- private bool _installFabricVisible = false;
- private bool _installForgeVisible = false;
- private bool _installOptifineVisible = false;
- private bool _installForgeOptifineVisible = false;
- private bool _downloadJava = false;
- private bool _isControlsEnabled = true;
- private long _progress = 0;
- private long _maxprogressvalue = 100;
- private string _downloadingFileName = "No active downloads";
- private string _tasksStatusLine = "No tasks started yet";
- /// <summary>
- /// Token source for downloading tasks
- /// </summary>
- private CancellationTokenSource _tokenSource = new();
- /// <summary>
- /// Token source for checking downloading options on selection from verions available for downloading
- /// </summary>
- private CancellationTokenSource _filteredVersionTokenSource = new();
- Serilog.ILogger _logger;
- ObservableCollection<Entity.VersionManifest.Version> _filteredVersions;
- ObservableCollection<DownloadedVersion> _downloadedVersions;
- ObservableCollection<Modpack> _modpackVersions;
- ObservableCollection<TreeNode> _downloadedVersionTree;
- TreeNode _libraries;
- List<Entity.VersionManifest.Version> _modpackVersionsAsVersion;
- Entity.VersionManifest.Version _filteredVersion;
- DownloadedVersion _downloadedVersion;
- Modpack? _selectedModpack;
- VersionManifest _versionManifest;
- public VersionsDownloaderViewModel()
- {
- IsControlsEnabled = false;
- try
- {
- _logger = Settings.logger;
- Task.Run(async () =>
- {
- if (FilteredVersions is null)
- {
- FilteredVersions = new();
- }
- if (_modpackVersions is null)
- {
- _modpackVersions = new();
- }
- if (DownloadedVersionTree is null)
- {
- _downloadedVersionTree = new();
- }
- if (DownloadedVersionsDictionary is null)
- {
- DownloadedVersionsDictionary = new();
- }
- _logger.Debug("Getting versionManifest.json");
- _versionManifest = await Downloader.DownloadAndDeserializeJsonData<VersionManifest>("https://launchermeta.mojang.com/mc/game/version_manifest_v2.json") ?? new();
- _modpackVersions.AddRange(await Downloader.DownloadAndDeserializeJsonData<List<Modpack>>("https://files.veloe.link/launcher/modpacks.json") ?? new());
- _modpackVersionsAsVersion = _modpackVersions.Select(v=> new Entity.VersionManifest.Version() { Id = v.Name, Type = "modpack", ComplianceLevel = v.Revision}).ToList();
- _logger.Debug("Updating available versions to download.");
- UpdateList();
- SearchGameFolderForVersions();
- IsControlsEnabled = true;
- });
- }
- catch (Exception ex)
- {
- OpenErrorWindow(ex);
- }
- }
- public Entity.VersionManifest.Version FilteredVersion
- {
- get { return _filteredVersion; }
- set {
- this.RaiseAndSetIfChanged(ref _filteredVersion, value);
- InstallFabric = false;
- InstallForge = false;
- InstallOptifine = false;
- InstallForgeOptifine = false;
- if (value is null)
- return;
- if (value.Type == "modpack")
- {
- try
- {
- if (System.IO.File.Exists(Settings.minecraftForlderPath + $"versions/{value.Id}/revision.json"))
- {
- if (value.ComplianceLevel > JsonSerializer.Deserialize<int>(System.IO.File.ReadAllText(Settings.minecraftForlderPath + $"versions/{value.Id}/revision.json")))
- DownloadButtonText = "Update Modpack";
- else
- DownloadButtonText = "Reinstall Modpack";
- }
- else
- if (System.IO.Directory.Exists($"{Settings.minecraftForlderPath}versions/{value.Id}") && System.IO.File.Exists($"{Settings.minecraftForlderPath}versions/{value.Id}/{value.Id}.json"))
- DownloadButtonText = "Update Modpack";
- else
- DownloadButtonText = "Download Modpack";
- }
- catch (Exception)
- {
- DownloadButtonText = "Update Modpack";
- }
- }
- else
- {
- if (System.IO.File.Exists(Settings.minecraftForlderPath + $"versions/{value.Id}/{value.Id}.json"))
- DownloadButtonText = "Reinstall";
- else
- DownloadButtonText = "Download";
- }
- try
- {
- Task.Run(() =>
- {
- _filteredVersionTokenSource.Cancel();
- _filteredVersionTokenSource.Dispose();
- _filteredVersionTokenSource = new();
- try
- {
- if (Downloader.IsFileAvaliable(@$"https://files.veloe.link/launcher/forge/Forge{value.Id}/Forge{value.Id}.json", _filteredVersionTokenSource.Token).Result)
- {
- if (Downloader.IsFileAvaliable(@$"https://files.veloe.link/launcher/forge/Forge{value.Id}/Optifine{value.Id}.jar", _filteredVersionTokenSource.Token).Result)
- InstallForgeOptifineVisible = true;
- InstallForgeVisible = true;
- }
- else
- {
- InstallForgeVisible = false;
- InstallForgeOptifineVisible = false;
- }
- if (Downloader.IsFileAvaliable(@$"https://files.veloe.link/launcher/fabric/Fabric{value.Id}/Fabric{value.Id}.json", _filteredVersionTokenSource.Token).Result)
- InstallFabricVisible = true;
- else
- InstallFabricVisible = false;
- if (Downloader.IsFileAvaliable(@$"https://files.veloe.link/launcher/optifine/Optifine{value.Id}/Optifine{value.Id}.json", _filteredVersionTokenSource.Token).Result)
- InstallOptifineVisible = true;
- else
- InstallOptifineVisible = false;
- }
- catch (OperationCanceledException)
- {
- InstallForgeVisible = false;
- InstallForgeOptifineVisible = false;
- InstallFabricVisible = false;
- InstallOptifineVisible = false;
- }
- });
- }
- catch (Exception ex)
- {
- OpenErrorWindow(ex);
- }
- }
- }
- public DownloadedVersion DownloadedVersion
- {
- get => _downloadedVersion;
- set
- {
- this.RaiseAndSetIfChanged(ref _downloadedVersion, value);
- Task.Run(() =>
- {
- try
- {
- IsControlsEnabled = false;
- DownloadedVersionTree.Clear();
- DownloadedVersionTree = new();
- this.RaisePropertyChanged(nameof(DownloadedVersionTree));
- DownloadedVersionsDictionary.Clear();
- if (value is null)
- {
- IsControlsEnabled = true;
- return;
- }
- Entity.Version.Version? version = null;
- foreach (var dversion in DownloadedVersions)
- {
- string json;
- using (StreamReader reader = new StreamReader(dversion.path))
- {
- json = reader.ReadToEnd();
- }
- var versionObject = JsonSerializer.Deserialize<Entity.Version.Version>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
- DownloadedVersionsDictionary.Add(dversion.version, versionObject);
- if (dversion == _downloadedVersion)
- {
- version = versionObject;
- }
- }
- if (version is null)
- {
- OpenErrorWindow("Json file is invalid!");
- return;
- }
- var versionDir = new FileInfo(value.path)?.Directory?.FullName;
- if (versionDir is null)
- {
- OpenErrorWindow("Version folder is invalid!");
- return;
- }
- //get version
- DownloadedVersionTree.Add(new TreeNode() { Title = "Version: " + (version.InheritsFrom ?? version.Id) });
- //calc Size
- var allSize = 0L;
- var dirSize = 0L;
- var dirInfo = new DirectoryInfo(versionDir);
- var sizeTreeNode = new TreeNode();
- var dirTreeNode = new TreeNode();
- dirTreeNode.SubNode.AddRange(DirectoryToTreeNode(dirInfo,out dirSize));
- dirTreeNode.Title = "versions/" + dirInfo.Name + " (" + BytesToString(dirSize) + ")";
- sizeTreeNode.SubNode.Add(dirTreeNode);
- allSize += dirSize;
- if (version.InheritsFrom is null)
- {
- dirInfo = new DirectoryInfo(Settings.minecraftForlderPath);
- sizeTreeNode.SubNode.AddRange(
- DirectoryToTreeNode(
- dirInfo,
- out dirSize,
- (dir) => dir.Name == ".mixin.out" ||
- dir.Name == "assets" ||
- dir.Name == "javaruntime" ||
- dir.Name == "libraries" ||
- dir.Name == "logs" ||
- dir.Name == "versions",
- (file) => file.Name.Contains("Veloe") ||
- file.Name.Contains("log") ||
- file.Name.Contains("exe") ||
- file.Name == "launcher_profiles.json" ||
- file.Name == "libHarfBuzzSharp.dll" ||
- file.Name == "libSkiaSharp.dll" ||
- file.Name == "settings.json")
- );
- allSize += dirSize;
- }
- sizeTreeNode.Title = "Size: " + BytesToString(allSize);
- DownloadedVersionTree.Add(sizeTreeNode);
- //calc Worlds
- dirInfo = null;
- if (version.InheritsFrom is null && Directory.Exists(Settings.minecraftForlderPath + "saves"))
- dirInfo = new DirectoryInfo(Settings.minecraftForlderPath + "saves");
- else
- if (Directory.Exists(versionDir + "/saves"))
- dirInfo = new DirectoryInfo(versionDir + "/saves");
- if (dirInfo is not null)
- {
- var worldsTreeNode = new TreeNode() { Title = "Worlds: " + dirInfo.GetDirectories().Count() };
- foreach (var world in dirInfo.GetDirectories())
- { worldsTreeNode.SubNode.Add(new TreeNode() { Title = world.Name }); }
- DownloadedVersionTree.Add(worldsTreeNode);
- }
- //check modloader
- var modsTreeNode = new TreeNode();
- if (version.InheritsFrom is null)
- modsTreeNode.Title = "Modloader: No";
- else if (version.Libraries.Any(l => l.Downloads?.Artifact?.Url?.Contains("forge") ?? false))
- {
- modsTreeNode.Title = "Modloader: Forge";
- OpenErrorWindow("This version contains forge modloader, it installs some libraries that can't be displayed and deleted in current launcher versions manager.");
- }
- else if (version.Libraries.Any(l => l.Name.Contains("fabric")))
- modsTreeNode.Title = "Modloader: Fabric";
- //get mods list
- if (modsTreeNode.Title != "No" && Directory.Exists(versionDir + "/mods"))
- {
- dirInfo = new DirectoryInfo(versionDir + "/mods");
- modsTreeNode.Title += " (" + dirInfo.EnumerateFiles("*.jar", SearchOption.TopDirectoryOnly).Count() + ")";
- foreach (var mod in dirInfo.EnumerateFiles("*.jar", SearchOption.TopDirectoryOnly))
- { modsTreeNode.SubNode.Add(new TreeNode() { Title = mod.Name }); }
- }
- DownloadedVersionTree.Add(modsTreeNode);
- //calc resourcepacks
- dirInfo = null;
- if (version.InheritsFrom is null && Directory.Exists(Settings.minecraftForlderPath + "resourcepacks"))
- dirInfo = new DirectoryInfo(Settings.minecraftForlderPath + "resourcepacks");
- else
- if (Directory.Exists(versionDir + "/resourcepacks"))
- dirInfo = new DirectoryInfo(versionDir + "/resourcepacks");
- if (dirInfo is not null)
- {
- var resourcepacksTreeNode = new TreeNode();
- resourcepacksTreeNode.Title = "Resoursepacks: " + (dirInfo?.GetDirectories()?.Count() + dirInfo?.GetFiles().Count() ?? 0).ToString();
- foreach (var resourcepack in dirInfo?.GetFileSystemInfos())
- { resourcepacksTreeNode.SubNode.Add(new TreeNode() { Title = resourcepack.Name }); }
- DownloadedVersionTree.Add(resourcepacksTreeNode);
- }
- //calc assets
- var assetsFolderName = version.Assets;
- if (version.Assets is null &&
- version.InheritsFrom is not null &&
- DownloadedVersionsDictionary.TryGetValue(version.InheritsFrom, out var outVersion) &&
- outVersion?.Assets is not null)
- {
- assetsFolderName = outVersion.Assets;
- }
- if (Directory.Exists(Settings.minecraftForlderPath + "assets/" + assetsFolderName))
- {
- dirInfo = new DirectoryInfo(Settings.minecraftForlderPath + "assets/" + assetsFolderName);
- allSize = 0;
- foreach (var file in dirInfo.EnumerateFiles("*", SearchOption.AllDirectories))
- { allSize += file.Length; }
- var assetsTreeNode = new TreeNode();
- var usedByVersionCount = 0;
- foreach (var dictionaryVersion in DownloadedVersionsDictionary)
- {
- if ((dictionaryVersion.Value?.Assets == assetsFolderName &&
- dictionaryVersion.Value?.InheritsFrom is null) ||
- (dictionaryVersion.Value?.InheritsFrom is not null &&
- DownloadedVersionsDictionary.TryGetValue(dictionaryVersion.Value.InheritsFrom, out outVersion) &&
- outVersion?.Assets == assetsFolderName))
- {
- usedByVersionCount++;
- assetsTreeNode.SubNode.Add(new TreeNode() { Title = dictionaryVersion.Key });
- }
- }
- assetsTreeNode.Title = "Assets: " + version.Assets + " (" + BytesToString(allSize) + ") (" + usedByVersionCount + ")";
- DownloadedVersionTree.Add(assetsTreeNode);
- }
- // calc libraries
- var usedLibraries = version.Libraries;
- var libTreeNode = new TreeNode();
- libTreeNode.Title = "Libraries";
- if (version.InheritsFrom is not null && DownloadedVersionsDictionary.TryGetValue(version.InheritsFrom, out outVersion) && outVersion is not null)
- {
- usedLibraries.AddRange(outVersion.Libraries);
- }
- usedLibraries =
- usedLibraries
- .Where(l =>
- File.Exists(Path.Combine(Settings.minecraftForlderPath + "libraries/" + l.Downloads?.Artifact?.Path)) ||
- File.Exists(Path.Combine(Settings.minecraftForlderPath + "libraries/" + l.Downloads?.Classifiers?.NativesLinux?.Path)) ||
- File.Exists(Path.Combine(Settings.minecraftForlderPath + "libraries/" + l.Downloads?.Classifiers?.NativesWindows?.Path)) ||
- File.Exists(Path.Combine(Settings.minecraftForlderPath + "libraries/" + l.Downloads?.Classifiers?.NativesWindows64?.Path)) ||
- File.Exists(Path.Combine(Settings.minecraftForlderPath + "libraries/" + l.Downloads?.Classifiers?.NativesWindows32?.Path)) ||
- File.Exists(Path.Combine(Settings.minecraftForlderPath + "libraries/" + StartCommandBuilder.GetLibPathFromName(l.Name, true)))
- )
- .ToList();
- var libraries = GetLibrariesFromVersions(DownloadedVersionsDictionary)
- .Where(v => usedLibraries.Any(u => v.Value.Name == u.Name))
- .GroupBy(a => a.Value.Name)
- .Select(g =>
- {
- return new {
- Name = g.Key,
- Count = g.Select(a => a.Key).Distinct().Count(),
- Versions = g.Select(a => a.Key).Distinct(),
- LibraryUniqueInstances = g.Select(a => a.Value).Distinct() //IEnumerable cause there can be several lib blocks with different rules in one version json
- };
- });
- foreach (var lib in libraries)
- {
- var subLibTreeNode = new TreeNode()
- {
- Title = lib.Name + " (" + lib.Count + ")",
- };
- //if only one version uses it (selected version), then add path to lib in Tag for deletion
- if (lib.Count == 1)
- {
- subLibTreeNode.Tag = lib.LibraryUniqueInstances.Where(l => l.Downloads?.Artifact?.Path is not null).Select(l => l.Downloads?.Artifact?.Path).FirstOrDefault() ?? string.Empty;
- //if fabric library
- if (File.Exists(Settings.minecraftForlderPath + "libraries/" + StartCommandBuilder.GetLibPathFromName(lib.Name,true)))
- subLibTreeNode.Tag = StartCommandBuilder.GetLibPathFromName(lib.Name,true);
- }
- var subLibUsedVersionsTreeNodeHeader = new TreeNode() { Title = "Using in versions:" };
- foreach (var ver in lib.Versions)
- subLibUsedVersionsTreeNodeHeader.SubNode.Add(new TreeNode() { Title = ver });
- if (subLibUsedVersionsTreeNodeHeader.SubNode.Count > 0)
- subLibTreeNode.SubNode.Add(subLibUsedVersionsTreeNodeHeader);
- if (lib.LibraryUniqueInstances.Any(l=>l.Natives is not null) || lib.LibraryUniqueInstances.Any(l=>l.Downloads?.Classifiers is not null))
- {
- var subLibNativesTreeNodeHeader = new TreeNode() { Title = "Natives:" };
- //check classifiers
- var libraryNativeInstance = lib.LibraryUniqueInstances.Where(l => l.Natives is not null || l.Downloads?.Classifiers is not null).First();
- if (libraryNativeInstance.Downloads?.Classifiers?.NativesWindows is not null)
- {
- subLibNativesTreeNodeHeader.SubNode.Add(new TreeNode()
- {
- Title = Path.GetFileName(libraryNativeInstance.Downloads?.Classifiers?.NativesWindows.Path) ?? "No lib name",
- Tag = lib.Count == 1 ? libraryNativeInstance.Downloads?.Classifiers?.NativesWindows?.Path ?? string.Empty : string.Empty
- });
- }
- if (libraryNativeInstance.Downloads?.Classifiers?.NativesWindows32 is not null)
- {
- subLibNativesTreeNodeHeader.SubNode.Add(new TreeNode()
- {
- Title = Path.GetFileName(libraryNativeInstance.Downloads?.Classifiers?.NativesWindows32.Path) ?? "No lib name",
- Tag = lib.Count == 1 ? libraryNativeInstance.Downloads?.Classifiers?.NativesWindows32?.Path ?? string.Empty : string.Empty
- });
- }
- if (libraryNativeInstance.Downloads?.Classifiers?.NativesWindows64 is not null)
- {
- subLibNativesTreeNodeHeader.SubNode.Add(new TreeNode()
- {
- Title = Path.GetFileName(libraryNativeInstance.Downloads?.Classifiers?.NativesWindows64.Path) ?? "No lib name",
- Tag = lib.Count == 1 ? libraryNativeInstance.Downloads?.Classifiers?.NativesWindows64?.Path ?? string.Empty : string.Empty
- });
- }
- if (libraryNativeInstance.Downloads?.Classifiers?.NativesLinux is not null)
- {
- subLibNativesTreeNodeHeader.SubNode.Add(new TreeNode()
- {
- Title = Path.GetFileName(libraryNativeInstance.Downloads?.Classifiers?.NativesLinux.Path) ?? "No lib name",
- Tag = lib.Count == 1 ? libraryNativeInstance.Downloads?.Classifiers?.NativesLinux?.Path ?? string.Empty : string.Empty
- });
- }
- if (subLibNativesTreeNodeHeader.SubNode.Count > 0)
- subLibTreeNode.SubNode.Add(subLibNativesTreeNodeHeader);
- }
- libTreeNode.SubNode.Add(subLibTreeNode);
- }
- _libraries = libTreeNode;
- DownloadedVersionTree.Add(libTreeNode);
- }
- finally
- {
- this.RaisePropertyChanged(nameof(DownloadedVersionTree));
- IsControlsEnabled = true;
- }
- });
- }
- }
- public Dictionary<string,Entity.Version.Version?> DownloadedVersionsDictionary { get; set; }
- public ObservableCollection<Entity.VersionManifest.Version> FilteredVersions
- {
- get => _filteredVersions;
- set => this.RaiseAndSetIfChanged(ref _filteredVersions, value);
- }
- public ObservableCollection<DownloadedVersion> DownloadedVersions
- {
- get => _downloadedVersions;
- set => this.RaiseAndSetIfChanged(ref _downloadedVersions, value);
- }
- public ObservableCollection<TreeNode> DownloadedVersionTree
- {
- get => _downloadedVersionTree;
- set => this.RaiseAndSetIfChanged(ref _downloadedVersionTree, value);
- }
- public string DownloadButtonText
- {
- get => _downloadButtonText;
- set => this.RaiseAndSetIfChanged(ref _downloadButtonText, value);
- }
- public bool ShowOld
- {
- get => _showOld;
- set {
- this.RaiseAndSetIfChanged(ref _showOld, value);
- UpdateList();
- }
- }
- public bool ShowSnaps
- {
- get => _showSnaps;
- set {
- this.RaiseAndSetIfChanged(ref _showSnaps, value);
- UpdateList();
- }
- }
- public long Progress
- {
- get => _progress;
- set => this.RaiseAndSetIfChanged(ref _progress, value);
- }
- public long MaxProgressValue
- {
- get => _maxprogressvalue;
- set => this.RaiseAndSetIfChanged(ref _maxprogressvalue, value);
- }
- public string DownloadingFileName
- {
- get => _downloadingFileName;
- set => this.RaiseAndSetIfChanged(ref _downloadingFileName, value);
- }
- public string TasksStatusLine
- {
- get => _tasksStatusLine;
- set => this.RaiseAndSetIfChanged(ref _tasksStatusLine, value);
- }
- public bool InstallForge
- {
- get => _installForge;
- set
- {
- this.RaiseAndSetIfChanged(ref _installForge, value);
- if (InstallFabric)
- InstallFabric = false;
- }
- }
- public bool InstallFabric
- {
- get => _installFabric;
- set
- {
- this.RaiseAndSetIfChanged(ref _installFabric, value);
- if (InstallForge)
- InstallForge = false;
- }
- }
- public bool InstallOptifine
- {
- get => _installOptifine;
- set => this.RaiseAndSetIfChanged(ref _installOptifine, value);
- }
- public bool InstallForgeOptifine
- {
- get { return _installForgeOptifine; }
- set
- {
- this.RaiseAndSetIfChanged(ref _installForgeOptifine, value);
- if (value)
- InstallForge = true;
- }
- }
- public bool InstallForgeVisible
- {
- get => _installForgeVisible;
- set => this.RaiseAndSetIfChanged(ref _installForgeVisible, value);
- }
- public bool InstallFabricVisible
- {
- get => _installFabricVisible;
- set => this.RaiseAndSetIfChanged(ref _installFabricVisible, value);
- }
- public bool InstallOptifineVisible
- {
- get => _installOptifineVisible;
- set => this.RaiseAndSetIfChanged(ref _installOptifineVisible, value);
- }
- public bool InstallForgeOptifineVisible
- {
- get => _installForgeOptifineVisible;
- set => this.RaiseAndSetIfChanged(ref _installForgeOptifineVisible, value);
- }
- public bool DownloadJava
- {
- get => _downloadJava;
- set => this.RaiseAndSetIfChanged(ref _downloadJava, value);
- }
- public bool IsControlsEnabled
- {
- get => _isControlsEnabled;
- set => this.RaiseAndSetIfChanged(ref _isControlsEnabled, value);
- }
- public async Task OnStartBunttonClick()
- {
- await Task.Run(async () => {
- if (FilteredVersion is null)
- return TaskStatus.Faulted;
- if (FilteredVersion.Type == "modpack")
- {
- _selectedModpack = _modpackVersions.Where(m => m.Name == FilteredVersion.Id).FirstOrDefault();
- if (_selectedModpack is null)
- return TaskStatus.Faulted;
- if (FilteredVersions.Where(x => x.Id == _selectedModpack.Version).FirstOrDefault() is null)
- return TaskStatus.Faulted;
- await Task.Run(async () => await Downloader.StartDownloadModpack(
- value => DownloadingFileName = value,
- value => TasksStatusLine = value,
- value => IsControlsEnabled = value,
- value => Progress = value,
- FilteredVersions,
- _selectedModpack,
- _tokenSource.Token,
- DownloadJava,
- InstallFabric = _selectedModpack.Fabric,
- InstallForge = _selectedModpack.Forge,
- InstallOptifine = _selectedModpack.Optifine,
- InstallForgeOptifine = _selectedModpack.ForgeOptifine));
- }
- else
- {
- _logger.Debug("Downloading {0}.json", FilteredVersion.Id);
- DownloadingFileName = $"{FilteredVersion.Id}.json";
- var versionJson = await Downloader.DownloadAndDeserializeJsonData<Entity.Version.Version>(FilteredVersion.Url, Settings.minecraftForlderPath + "versions/" + FilteredVersion.Id + "/", FilteredVersion.Id + ".json");
- if (versionJson is not null)
- await Downloader.StartDownload(
- value => DownloadingFileName = value,
- value => TasksStatusLine = value,
- value => IsControlsEnabled = value,
- value => Progress = value,
- versionJson,
- _tokenSource.Token,
- DownloadJava,
- InstallForge,
- InstallOptifine,
- InstallForgeOptifine,
- InstallFabric);
- }
- SearchGameFolderForVersions();
- return TaskStatus.RanToCompletion;
- });
- }
- public async Task OnDeleteButtonClick()
- {
- await Task.Run(() => {
- try
- {
- IsControlsEnabled = false;
- DownloadedVersionTree.Clear();
- DownloadedVersionTree = new();
- this.RaisePropertyChanged(nameof(DownloadedVersionTree));
- DownloadedVersionsDictionary.Clear();
- DownloadedVersionsDictionary = new();
- Entity.Version.Version? version = null;
- foreach (var dversion in DownloadedVersions)
- {
- string json;
- using (StreamReader reader = new StreamReader(dversion.path))
- {
- json = reader.ReadToEnd();
- }
- var versionObject = JsonSerializer.Deserialize<Entity.Version.Version>(json, new JsonSerializerOptions { PropertyNameCaseInsensitive = true });
- DownloadedVersionsDictionary.Add(dversion.version, versionObject);
- if (dversion == _downloadedVersion)
- {
- version = versionObject;
- }
- }
- if (version is null)
- {
- OpenErrorWindow("Json file is invalid!");
- return;
- }
- var versionDir = new FileInfo(DownloadedVersion.path)?.Directory?.FullName;
- if (versionDir is null)
- {
- OpenErrorWindow("Version folder is invalid!");
- return;
- }
- var dirInfo = new DirectoryInfo(versionDir);
-
- if (version.InheritsFrom is null && DownloadedVersionsDictionary.Where(v=>v.Value.InheritsFrom is null).Count() == 1)
- {
- //if vanilla
- Debug.WriteLine("Vanilla root directories deleted!");
-
- if (Directory.Exists(Settings.minecraftForlderPath + "saves"))
- Directory.Delete(Settings.minecraftForlderPath + "saves", true);
- if (Directory.Exists(Settings.minecraftForlderPath + "resourcepacks"))
- Directory.Delete(Settings.minecraftForlderPath + "resourcepacks", true);
- if (Directory.Exists(Settings.minecraftForlderPath + "shaderpacks"))
- Directory.Delete(Settings.minecraftForlderPath + "shaderpacks", true);
- }
- //calc assets
- var assetsFolderName = version.Assets;
- if (version.Assets is null &&
- version.InheritsFrom is not null &&
- DownloadedVersionsDictionary.TryGetValue(version.InheritsFrom, out var outVersion) &&
- outVersion?.Assets is not null)
- {
- assetsFolderName = outVersion.Assets;
- }
- if (Directory.Exists(Settings.minecraftForlderPath + "assets/" + assetsFolderName))
- {
- var usedByVersionCount = 0;
- foreach (var dictionaryVersion in DownloadedVersionsDictionary)
- {
- if ((dictionaryVersion.Value?.Assets == assetsFolderName &&
- dictionaryVersion.Value?.InheritsFrom is null) ||
- (dictionaryVersion.Value?.InheritsFrom is not null &&
- DownloadedVersionsDictionary.TryGetValue(dictionaryVersion.Value.InheritsFrom, out outVersion) &&
- outVersion?.Assets == assetsFolderName))
- {
- usedByVersionCount++;
- }
- }
- //delete assets if only deleting version used it
- if (usedByVersionCount == 1)
- {
- Debug.WriteLine(Settings.minecraftForlderPath + "assets/" + assetsFolderName);
- Directory.Delete(Settings.minecraftForlderPath + "assets/" + assetsFolderName,true);
- }
- }
- // calc libraries
- DeleteLibrariesFromTreeNode(_libraries);
- // delete version dir
- Debug.WriteLine(versionDir);
- Directory.Delete(versionDir, true);
- }
- catch (Exception ex)
- {
- OpenErrorWindow(ex);
- }
- finally
- {
- SearchGameFolderForVersions();
- IsControlsEnabled = true;
- }
- });
- }
- static string[] _size_label = { "bytes", "KB", "MB", "GB" };
- private string BytesToString(long size)
- {
- var j = 0;
- var result = (double)size;
- while (j < _size_label.Length && result > 1024)
- {
- result = result / 1024;
- j++;
- }
- return string.Format("{0:N2}", result) + " " + _size_label[j];
- }
- private List<TreeNode> DirectoryToTreeNode(DirectoryInfo? dirInfo, out long size, Expression<Func<DirectoryInfo?, bool>>? dirExpression = null, Expression<Func<FileInfo?,bool>>? fileExpression = null)
- {
- size = 0L;
- var nodes = new List<TreeNode>();
- if (!(dirInfo is not null && dirInfo.Exists)) return nodes;
- if (dirExpression is null)
- dirExpression = (x) => false;
- if (fileExpression is null)
- fileExpression = (x) => false;
- var dirDelegate = dirExpression.Compile();
- var fileDelegate = fileExpression.Compile();
- foreach (var dir in dirInfo.EnumerateDirectories("*", SearchOption.TopDirectoryOnly))
- {
- if (dirDelegate(dir)) continue;
- var subDirSize = 0L;
- var subDirTreeNode = new TreeNode();
- subDirTreeNode.SubNode.AddRange(DirectoryToTreeNode(dir,out subDirSize));
- subDirTreeNode.Title = dir.Name + " (" + BytesToString(subDirSize) + ")";
- nodes.Add(subDirTreeNode);
- size += subDirSize;
- }
- foreach (var file in dirInfo.EnumerateFiles("*", SearchOption.TopDirectoryOnly))
- {
- if (fileDelegate(file)) continue;
- nodes.Add(new TreeNode() { Title = file.Name + " (" + BytesToString(file.Length) + ")" });
- size += file.Length;
- }
- return nodes;
- }
- private void DeleteLibrariesFromTreeNode(TreeNode library)
- {
- foreach (var node in library.SubNode)
- DeleteLibrariesFromTreeNode(node);
-
- if (!string.IsNullOrEmpty(library.Tag))
- {
- var libFileInfo = new FileInfo(Settings.minecraftForlderPath + "libraries/" + library.Tag);
- var libDir = libFileInfo.Directory;
- if(libDir?.Exists == false)
- {
- Debug.WriteLine($"Directory {libDir.FullName} does not exists! Subnode: {library.Title}");
- _logger.Warning($"Directory {libDir.FullName} does not exists!");
- return;
- }
- if (libDir?.GetFileSystemInfos().Count() > 1)
- {
- Debug.WriteLine(libFileInfo.FullName);
- libFileInfo.Delete();
- }
- else
- {
- Debug.WriteLine(libDir?.FullName);
- libDir?.Delete(true);
- }
- }
- }
- private void UpdateList()
- {
- try
- {
- FilteredVersions.Clear();
- if (_versionManifest.Versions is null)
- return;
- FilteredVersions.AddRange(_modpackVersionsAsVersion);
- FilteredVersions.AddRange(_versionManifest.Versions.Where(version => ShowSnaps && version.Type == "snapshot" || ShowOld && version.Type is ("old_alpha" or "old_beta") || version.Type == "release"));
- }
- catch (Exception ex)
- {
- OpenErrorWindow(ex);
- }
- }
- private void SearchGameFolderForVersions()
- {
- if (DownloadedVersions is null)
- DownloadedVersions = new();
- DownloadedVersions.Clear();
- DownloadedVersions = new();
- 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)
- {
- _logger.Debug("Checking folder {0}", dir.Name);
- string checkedPath;
- if (File.Exists(checkedPath = dir.FullName + "/" + dir.Name + ".json"))
- {
- _logger.Debug("Found version {0}", dir.Name);
- DownloadedVersions.Add(new DownloadedVersion(checkedPath, dir.Name));
- profiles.Profiles.Add($"Version {dir.Name}", new Profile() { Name = dir.Name, LastVersionId = dir.Name, LauncherVisibilityOnGameClose = "keep the launcher open" });
- }
- }
- }
- catch (DirectoryNotFoundException)
- {
- Directory.CreateDirectory(Settings.minecraftForlderPath + "versions");
- return;
- }
- }
- public void OnOpenForlder()
- {
- if (DownloadedVersion?.version is not null && Path.Exists(Settings.minecraftForlderPath + "versions/" + DownloadedVersion.version))
- Process.Start(new System.Diagnostics.ProcessStartInfo() { FileName = Settings.minecraftForlderPath + "versions/" + DownloadedVersion.version, UseShellExecute = true });
- }
- public void OnClosing(object sender, CancelEventArgs args)
- {
- _tokenSource.Cancel();
- _tokenSource.Dispose();
- _filteredVersionTokenSource.Cancel();
- _filteredVersionTokenSource.Dispose();
- }
- private IEnumerable<KeyValuePair<string,Library>> GetLibrariesFromVersions(Dictionary<string, Entity.Version.Version?> versions)
- {
- foreach (var version in versions)
- {
- if (version.Value is null) continue;
- if (version.Value.InheritsFrom is not null && versions.TryGetValue(version.Value.InheritsFrom,out var inheritVersion) && inheritVersion?.Libraries is not null)
- {
- foreach (var lib in inheritVersion.Libraries)
- yield return new KeyValuePair<string, Library>(version.Key, lib);
- }
- foreach (var lib in version.Value.Libraries)
- yield return new KeyValuePair<string, Library>(version.Key,lib);
- }
- }
- }
- public class TreeNode
- {
- public TreeNode()
- {
- Title = "Default";
- SubNode = new();
- Tag = string.Empty;
- }
- public string Title { get; set; }
- public string Tag { get; set; }
- public List<TreeNode> SubNode { get; set; }
- public override string ToString()
- {
- return Title;
- }
- }
|