Minor bootstrapper code refactor

This commit is contained in:
pizzaboxer 2023-02-11 20:19:59 +00:00
parent 1805e31f86
commit a0be3fa970
2 changed files with 53 additions and 60 deletions

View File

@ -183,6 +183,8 @@ namespace Bloxstrap
Task bootstrapperTask = Task.Run(() => bootstrapper.Run()).ContinueWith(t => Task bootstrapperTask = Task.Run(() => bootstrapper.Run()).ContinueWith(t =>
{ {
// TODO: add error logging
if (t.Exception is null) if (t.Exception is null)
return; return;

View File

@ -28,7 +28,6 @@ namespace Bloxstrap
public const int ERROR_SUCCESS = 0; public const int ERROR_SUCCESS = 0;
public const int ERROR_INSTALL_USEREXIT = 1602; public const int ERROR_INSTALL_USEREXIT = 1602;
public const int ERROR_INSTALL_FAILURE = 1603; public const int ERROR_INSTALL_FAILURE = 1603;
public const int ERROR_PRODUCT_UNINSTALLED = 1614;
// in case a new package is added, you can find the corresponding directory // in case a new package is added, you can find the corresponding directory
// by opening the stock bootstrapper in a hex editor // by opening the stock bootstrapper in a hex editor
@ -58,26 +57,25 @@ namespace Bloxstrap
{ "extracontent-places.zip", @"ExtraContent\places\" }, { "extracontent-places.zip", @"ExtraContent\places\" },
}; };
private static readonly string AppSettings = private const string AppSettings =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<Settings>\n" + "<Settings>\n" +
" <ContentFolder>content</ContentFolder>\n" + " <ContentFolder>content</ContentFolder>\n" +
" <BaseUrl>http://www.roblox.com</BaseUrl>\n" + " <BaseUrl>http://www.roblox.com</BaseUrl>\n" +
"</Settings>\n"; "</Settings>\n";
private string? LaunchCommandLine; private static bool FreshInstall => String.IsNullOrEmpty(App.State.Prop.VersionGuid);
private string VersionGuid = null!; private string? _launchCommandLine;
private PackageManifest VersionPackageManifest = null!;
private string VersionFolder = null!;
private readonly bool FreshInstall; private string _versionGuid = null!;
private PackageManifest _versionPackageManifest = null!;
private string _versionFolder = null!;
private double ProgressIncrement; private double _progressIncrement;
private long TotalBytes = 0; private long _totalDownloadedBytes = 0;
private long TotalDownloadedBytes = 0; private int _packagesExtracted = 0;
private int PackagesExtracted = 0; private bool _cancelFired = false;
private bool CancelFired = false;
public IBootstrapperDialog? Dialog = null; public IBootstrapperDialog? Dialog = null;
#endregion #endregion
@ -85,8 +83,7 @@ namespace Bloxstrap
#region Core #region Core
public Bootstrapper(string? launchCommandLine = null) public Bootstrapper(string? launchCommandLine = null)
{ {
LaunchCommandLine = launchCommandLine; _launchCommandLine = launchCommandLine;
FreshInstall = String.IsNullOrEmpty(App.State.Prop.VersionGuid);
} }
public void SetStatus(string message) public void SetStatus(string message)
@ -97,7 +94,6 @@ namespace Bloxstrap
Dialog.Message = message; Dialog.Message = message;
} }
// this is called from BootstrapperStyleForm.SetupDialog()
public async Task Run() public async Task Run()
{ {
if (App.IsUninstall) if (App.IsUninstall)
@ -115,14 +111,11 @@ namespace Bloxstrap
// if bloxstrap is installing for the first time but is running, prompt to close roblox // if bloxstrap is installing for the first time but is running, prompt to close roblox
// if roblox needs updating but is running, ignore update for now // if roblox needs updating but is running, ignore update for now
if (!Directory.Exists(VersionFolder) && CheckIfRunning(true) || App.State.Prop.VersionGuid != VersionGuid && !CheckIfRunning(false)) if (!Directory.Exists(_versionFolder) && CheckIfRunning(true) || App.State.Prop.VersionGuid != _versionGuid && !CheckIfRunning(false))
await InstallLatestVersion(); await InstallLatestVersion();
if (App.IsFirstRun) if (App.IsFirstRun)
{
//App.Settings.ShouldSave = App.State.ShouldSave = true;
App.ShouldSaveConfigs = true; App.ShouldSaveConfigs = true;
}
await ApplyModifications(); await ApplyModifications();
@ -148,7 +141,7 @@ namespace Bloxstrap
var releaseInfo = await Utilities.GetJson<GithubRelease>($"https://api.github.com/repos/{App.ProjectRepository}/releases/latest"); var releaseInfo = await Utilities.GetJson<GithubRelease>($"https://api.github.com/repos/{App.ProjectRepository}/releases/latest");
if (releaseInfo is null || releaseInfo.Name is null || releaseInfo.Assets is null || currentVersion == releaseInfo.Name) if (releaseInfo?.Assets is null || currentVersion == releaseInfo.Name)
return; return;
SetStatus($"Getting the latest {App.ProjectName}..."); SetStatus($"Getting the latest {App.ProjectName}...");
@ -191,9 +184,9 @@ namespace Bloxstrap
SetStatus("Connecting to Roblox..."); SetStatus("Connecting to Roblox...");
ClientVersion clientVersion = await DeployManager.GetLastDeploy(App.Settings.Prop.Channel); ClientVersion clientVersion = await DeployManager.GetLastDeploy(App.Settings.Prop.Channel);
VersionGuid = clientVersion.VersionGuid; _versionGuid = clientVersion.VersionGuid;
VersionFolder = Path.Combine(Directories.Versions, VersionGuid); _versionFolder = Path.Combine(Directories.Versions, _versionGuid);
VersionPackageManifest = await PackageManifest.Get(VersionGuid); _versionPackageManifest = await PackageManifest.Get(_versionGuid);
} }
private bool CheckIfRunning(bool shutdown) private bool CheckIfRunning(bool shutdown)
@ -229,22 +222,22 @@ namespace Bloxstrap
SetStatus("Starting Roblox..."); SetStatus("Starting Roblox...");
if (LaunchCommandLine == "--app" && App.Settings.Prop.UseDisableAppPatch) if (_launchCommandLine == "--app" && App.Settings.Prop.UseDisableAppPatch)
{ {
Utilities.OpenWebsite("https://www.roblox.com/games"); Utilities.OpenWebsite("https://www.roblox.com/games");
return; return;
} }
// launch time isn't really required for all launches, but it's usually just safest to do this // launch time isn't really required for all launches, but it's usually just safest to do this
LaunchCommandLine += " --launchtime=" + DateTimeOffset.Now.ToUnixTimeMilliseconds(); _launchCommandLine += " --launchtime=" + DateTimeOffset.Now.ToUnixTimeMilliseconds();
if (App.Settings.Prop.Channel.ToLower() != DeployManager.DefaultChannel.ToLower()) if (App.Settings.Prop.Channel.ToLower() != DeployManager.DefaultChannel.ToLower())
LaunchCommandLine += " -channel " + App.Settings.Prop.Channel.ToLower(); _launchCommandLine += " -channel " + App.Settings.Prop.Channel.ToLower();
LaunchCommandLine += " -startEvent " + startEventName; _launchCommandLine += " -startEvent " + startEventName;
bool shouldWait = false; bool shouldWait = false;
Process gameClient = Process.Start(Path.Combine(VersionFolder, "RobloxPlayerBeta.exe"), LaunchCommandLine); Process gameClient = Process.Start(Path.Combine(_versionFolder, "RobloxPlayerBeta.exe"), _launchCommandLine);
Process? rbxFpsUnlocker = null; Process? rbxFpsUnlocker = null;
DiscordRichPresence? richPresence = null; DiscordRichPresence? richPresence = null;
Mutex? singletonMutex = null; Mutex? singletonMutex = null;
@ -311,14 +304,14 @@ namespace Bloxstrap
return; return;
} }
CancelFired = true; _cancelFired = true;
try try
{ {
if (App.IsFirstRun) if (App.IsFirstRun)
Directory.Delete(Directories.Base, true); Directory.Delete(Directories.Base, true);
else if (Directory.Exists(VersionFolder)) else if (Directory.Exists(_versionFolder))
Directory.Delete(VersionFolder, true); Directory.Delete(_versionFolder, true);
} }
catch (Exception) { } catch (Exception) { }
@ -340,7 +333,10 @@ namespace Bloxstrap
if (Directory.Exists(oldInstallLocation)) if (Directory.Exists(oldInstallLocation))
Directory.Delete(oldInstallLocation, true); Directory.Delete(oldInstallLocation, true);
} }
catch (Exception) { } catch (Exception)
{
// ignored
}
applicationKey.DeleteValue("OldInstallLocation"); applicationKey.DeleteValue("OldInstallLocation");
} }
@ -475,7 +471,7 @@ namespace Bloxstrap
#region Roblox Install #region Roblox Install
private void UpdateProgressbar() private void UpdateProgressbar()
{ {
int newProgress = (int)Math.Floor(ProgressIncrement * TotalDownloadedBytes); int newProgress = (int)Math.Floor(_progressIncrement * _totalDownloadedBytes);
// bugcheck: if we're restoring a file from a package, it'll incorrectly increment the progress beyond 100 // bugcheck: if we're restoring a file from a package, it'll incorrectly increment the progress beyond 100
// too lazy to fix properly so lol // too lazy to fix properly so lol
@ -507,21 +503,17 @@ namespace Bloxstrap
} }
// compute total bytes to download // compute total bytes to download
_progressIncrement = (double)100 / _versionPackageManifest.Sum(package => package.PackedSize);
foreach (Package package in VersionPackageManifest)
TotalBytes += package.PackedSize;
ProgressIncrement = (double)1 / TotalBytes * 100;
Directory.CreateDirectory(Directories.Downloads); Directory.CreateDirectory(Directories.Downloads);
Directory.CreateDirectory(Directories.Versions); Directory.CreateDirectory(Directories.Versions);
foreach (Package package in VersionPackageManifest) foreach (Package package in _versionPackageManifest)
{ {
// download all the packages synchronously // download all the packages synchronously
await DownloadPackage(package); await DownloadPackage(package);
// extract the package immediately after download // extract the package immediately after download asynchronously
ExtractPackage(package); ExtractPackage(package);
} }
@ -535,12 +527,12 @@ namespace Bloxstrap
} }
// wait for all packages to finish extracting // wait for all packages to finish extracting
while (PackagesExtracted < VersionPackageManifest.Count) while (_packagesExtracted < _versionPackageManifest.Count)
{ {
await Task.Delay(100); await Task.Delay(100);
} }
string appSettingsLocation = Path.Combine(VersionFolder, "AppSettings.xml"); string appSettingsLocation = Path.Combine(_versionFolder, "AppSettings.xml");
await File.WriteAllTextAsync(appSettingsLocation, AppSettings); await File.WriteAllTextAsync(appSettingsLocation, AppSettings);
if (!FreshInstall) if (!FreshInstall)
@ -550,13 +542,13 @@ namespace Bloxstrap
// let's take this opportunity to delete any packages we don't need anymore // let's take this opportunity to delete any packages we don't need anymore
foreach (string filename in Directory.GetFiles(Directories.Downloads)) foreach (string filename in Directory.GetFiles(Directories.Downloads))
{ {
if (!VersionPackageManifest.Exists(package => filename.Contains(package.Signature))) if (!_versionPackageManifest.Exists(package => filename.Contains(package.Signature)))
File.Delete(filename); File.Delete(filename);
} }
string oldVersionFolder = Path.Combine(Directories.Versions, App.State.Prop.VersionGuid); string oldVersionFolder = Path.Combine(Directories.Versions, App.State.Prop.VersionGuid);
if (VersionGuid != App.State.Prop.VersionGuid && Directory.Exists(oldVersionFolder)) if (_versionGuid != App.State.Prop.VersionGuid && Directory.Exists(oldVersionFolder))
{ {
// and also to delete our old version folder // and also to delete our old version folder
Directory.Delete(oldVersionFolder, true); Directory.Delete(oldVersionFolder, true);
@ -566,7 +558,7 @@ namespace Bloxstrap
if (Dialog is not null) if (Dialog is not null)
Dialog.CancelEnabled = false; Dialog.CancelEnabled = false;
App.State.Prop.VersionGuid = VersionGuid; App.State.Prop.VersionGuid = _versionGuid;
} }
private async Task ApplyModifications() private async Task ApplyModifications()
@ -609,7 +601,7 @@ namespace Bloxstrap
foreach (string file in modFolderFiles) foreach (string file in modFolderFiles)
{ {
string fileModFolder = Path.Combine(modFolder, file); string fileModFolder = Path.Combine(modFolder, file);
string fileVersionFolder = Path.Combine(VersionFolder, file); string fileVersionFolder = Path.Combine(_versionFolder, file);
if (File.Exists(fileVersionFolder)) if (File.Exists(fileVersionFolder))
{ {
@ -645,7 +637,7 @@ namespace Bloxstrap
catch (InvalidOperationException) catch (InvalidOperationException)
{ {
// package doesn't exist, likely mistakenly placed file // package doesn't exist, likely mistakenly placed file
string versionFileLocation = Path.Combine(VersionFolder, fileLocation); string versionFileLocation = Path.Combine(_versionFolder, fileLocation);
File.Delete(versionFileLocation); File.Delete(versionFileLocation);
@ -688,7 +680,7 @@ namespace Bloxstrap
private async Task DownloadPackage(Package package) private async Task DownloadPackage(Package package)
{ {
string packageUrl = $"{DeployManager.BaseUrl}/{VersionGuid}-{package.Name}"; string packageUrl = $"{DeployManager.BaseUrl}/{_versionGuid}-{package.Name}";
string packageLocation = Path.Combine(Directories.Downloads, package.Signature); string packageLocation = Path.Combine(Directories.Downloads, package.Signature);
string robloxPackageLocation = Path.Combine(Directories.LocalAppData, "Roblox", "Downloads", package.Signature); string robloxPackageLocation = Path.Combine(Directories.LocalAppData, "Roblox", "Downloads", package.Signature);
@ -705,7 +697,7 @@ namespace Bloxstrap
else else
{ {
Debug.WriteLine($"{package.Name} is already downloaded, skipping..."); Debug.WriteLine($"{package.Name} is already downloaded, skipping...");
TotalDownloadedBytes += package.PackedSize; _totalDownloadedBytes += package.PackedSize;
UpdateProgressbar(); UpdateProgressbar();
return; return;
} }
@ -717,7 +709,7 @@ namespace Bloxstrap
Debug.WriteLine($"Found existing version of {package.Name} ({robloxPackageLocation})! Copying to Downloads folder..."); Debug.WriteLine($"Found existing version of {package.Name} ({robloxPackageLocation})! Copying to Downloads folder...");
File.Copy(robloxPackageLocation, packageLocation); File.Copy(robloxPackageLocation, packageLocation);
TotalDownloadedBytes += package.PackedSize; _totalDownloadedBytes += package.PackedSize;
UpdateProgressbar(); UpdateProgressbar();
return; return;
} }
@ -726,7 +718,7 @@ namespace Bloxstrap
{ {
Debug.WriteLine($"Downloading {package.Name}..."); Debug.WriteLine($"Downloading {package.Name}...");
if (CancelFired) if (_cancelFired)
return; return;
{ {
@ -745,7 +737,7 @@ namespace Bloxstrap
await fileStream.WriteAsync(buffer, 0, bytesRead); await fileStream.WriteAsync(buffer, 0, bytesRead);
TotalDownloadedBytes += bytesRead; _totalDownloadedBytes += bytesRead;
UpdateProgressbar(); UpdateProgressbar();
} }
} }
@ -756,13 +748,12 @@ namespace Bloxstrap
private async void ExtractPackage(Package package) private async void ExtractPackage(Package package)
{ {
if (CancelFired) if (_cancelFired)
return; return;
string packageLocation = Path.Combine(Directories.Downloads, package.Signature); string packageLocation = Path.Combine(Directories.Downloads, package.Signature);
string packageFolder = Path.Combine(VersionFolder, PackageDirectories[package.Name]); string packageFolder = Path.Combine(_versionFolder, PackageDirectories[package.Name]);
string extractPath; string extractPath;
string? directory;
Debug.WriteLine($"Extracting {package.Name} to {packageFolder}..."); Debug.WriteLine($"Extracting {package.Name} to {packageFolder}...");
@ -770,7 +761,7 @@ namespace Bloxstrap
{ {
foreach (ZipArchiveEntry entry in archive.Entries) foreach (ZipArchiveEntry entry in archive.Entries)
{ {
if (CancelFired) if (_cancelFired)
return; return;
if (entry.FullName.EndsWith('\\')) if (entry.FullName.EndsWith('\\'))
@ -780,7 +771,7 @@ namespace Bloxstrap
//Debug.WriteLine($"[{package.Name}] Writing {extractPath}..."); //Debug.WriteLine($"[{package.Name}] Writing {extractPath}...");
directory = Path.GetDirectoryName(extractPath); string? directory = Path.GetDirectoryName(extractPath);
if (directory is null) if (directory is null)
continue; continue;
@ -793,12 +784,12 @@ namespace Bloxstrap
Debug.WriteLine($"Finished extracting {package.Name}"); Debug.WriteLine($"Finished extracting {package.Name}");
PackagesExtracted += 1; _packagesExtracted += 1;
} }
private void ExtractFileFromPackage(string packageName, string fileName) private void ExtractFileFromPackage(string packageName, string fileName)
{ {
Package? package = VersionPackageManifest.Find(x => x.Name == packageName); Package? package = _versionPackageManifest.Find(x => x.Name == packageName);
if (package is null) if (package is null)
return; return;
@ -806,7 +797,7 @@ namespace Bloxstrap
DownloadPackage(package).GetAwaiter().GetResult(); DownloadPackage(package).GetAwaiter().GetResult();
string packageLocation = Path.Combine(Directories.Downloads, package.Signature); string packageLocation = Path.Combine(Directories.Downloads, package.Signature);
string packageFolder = Path.Combine(VersionFolder, PackageDirectories[package.Name]); string packageFolder = Path.Combine(_versionFolder, PackageDirectories[package.Name]);
using ZipArchive archive = ZipFile.OpenRead(packageLocation); using ZipArchive archive = ZipFile.OpenRead(packageLocation);