123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987 |
- 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;
- 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
- long allSize = 0;
- string[] size_label = { "bytes", "KB", "MB", "GB" };
- var dirInfo = new DirectoryInfo(versionDir);
- foreach (var file in dirInfo.EnumerateFiles("*", SearchOption.AllDirectories))
- { allSize += file.Length; }
- if (version.InheritsFrom is null)
- {
- //TODO add subnodes with size
- dirInfo = new DirectoryInfo(Settings.minecraftForlderPath);
- foreach (var dir in dirInfo.GetDirectories())
- {
- if (dir.Name != ".mixin.out" &&
- dir.Name != "assets" &&
- dir.Name != "javaruntime" &&
- dir.Name != "libraries" &&
- dir.Name != "logs" &&
- dir.Name != "versions")
- foreach (var file in dir.EnumerateFiles("*", SearchOption.AllDirectories))
- { allSize += file.Length; }
- }
- foreach (var file in dirInfo.GetFiles("*"))
- {
- if (!(file.Name.Contains("Veloe") &&
- file.Name.Contains("log") &&
- file.Name.Contains("exe")) &&
- file.Name == "launcher_profiles.json")
- allSize += file.Length;
- }
- }
- var j = 0;
- var result = (double)allSize;
- while (j < size_label.Length && result > 1024)
- {
- result = result / 1024;
- j++;
- }
- DownloadedVersionTree.Add(new TreeNode() { Title = "Size: " + string.Format("{0:N2}", result) + " " + size_label[j] });
- //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";
- 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; }
- j = 0;
- result = (double)allSize;
- while (j < size_label.Length && result > 1024)
- {
- result = result / 1024;
- j++;
- }
- 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 + " (" + string.Format("{0:N2}", result) + " " + size_label[j] + ") (" + 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(async () => {
- 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;
- }
- });
- }
- 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);
- }
- }
- }
- public 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);
- }
- }
- public 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();
- }
- public 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;
- }
- }
|