Skip to content

Commit

Permalink
Consolidate stuff
Browse files Browse the repository at this point in the history
yea
  • Loading branch information
pizzaboxer committed Jul 2, 2023
1 parent 94fe522 commit 0a7ae17
Show file tree
Hide file tree
Showing 12 changed files with 110 additions and 95 deletions.
50 changes: 18 additions & 32 deletions Bloxstrap/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

using Microsoft.Win32;

using Bloxstrap.Enums;
using Bloxstrap.Extensions;
using Bloxstrap.Models;
using Bloxstrap.Models.Attributes;
Expand All @@ -34,6 +35,7 @@ public partial class App : Application

// used only for communicating between app and menu - use Directories.Base for anything else
public static string BaseDirectory = null!;

public static bool ShouldSaveConfigs { get; set; } = false;
public static bool IsSetupComplete { get; set; } = true;
public static bool IsFirstRun { get; private set; } = true;
Expand All @@ -56,39 +58,23 @@ public partial class App : Application

public static System.Windows.Forms.NotifyIcon Notification { get; private set; } = null!;

public static void Terminate(int code = Bootstrapper.ERROR_SUCCESS)
{
Logger.WriteLine($"[App::Terminate] Terminating with exit code {code}");
Settings.Save();
State.Save();
Notification.Dispose();
Environment.Exit(code);
}

private void InitLog()
public static void Terminate(ErrorCode exitCode = ErrorCode.ERROR_SUCCESS)
{
// if we're running for the first time or uninstalling, log to temp folder
// else, log to bloxstrap folder
if (IsFirstRun)
{
if (exitCode == ErrorCode.ERROR_CANCELLED)
exitCode = ErrorCode.ERROR_INSTALL_USEREXIT;
}

bool isUsingTempDir = IsFirstRun || IsUninstall;
string logdir = isUsingTempDir ? Path.Combine(Directories.LocalAppData, "Temp") : Path.Combine(Directories.Base, "Logs");
string timestamp = DateTime.UtcNow.ToString("yyyyMMdd'T'HHmmss'Z'");
int processId = Process.GetCurrentProcess().Id;
int exitCodeNum = (int)exitCode;

Logger.Initialize(Path.Combine(logdir, $"{ProjectName}_{timestamp}_{processId}.log"));
Logger.WriteLine($"[App::Terminate] Terminating with exit code {exitCodeNum} ({exitCode})");

// clean up any logs older than a week
if (!isUsingTempDir)
{
foreach (FileInfo log in new DirectoryInfo(logdir).GetFiles())
{
if (log.LastWriteTimeUtc.AddDays(7) > DateTime.UtcNow)
continue;
Settings.Save();
State.Save();
Notification.Dispose();

Logger.WriteLine($"[App::InitLog] Cleaning up old log file '{log.Name}'");
log.Delete();
}
}
Environment.Exit(exitCodeNum);
}

void GlobalExceptionHandler(object sender, DispatcherUnhandledExceptionEventArgs e)
Expand All @@ -111,7 +97,7 @@ void FinalizeExceptionHandling(Exception exception)
if (!IsQuiet)
Controls.ShowExceptionDialog(exception);

Terminate(Bootstrapper.ERROR_INSTALL_FAILURE);
Terminate(ErrorCode.ERROR_INSTALL_FAILURE);
#pragma warning restore 162
}

Expand Down Expand Up @@ -193,7 +179,7 @@ protected override void OnStartup(StartupEventArgs e)
Logger.WriteLine("[App::OnStartup] Running first-time install");

BaseDirectory = Path.Combine(Directories.LocalAppData, ProjectName);
InitLog();
Logger.Initialize(true);

if (!IsQuiet)
{
Expand All @@ -213,7 +199,7 @@ protected override void OnStartup(StartupEventArgs e)
if (!IsSetupComplete)
{
Logger.WriteLine("[App::OnStartup] Installation cancelled!");
Environment.Exit(Bootstrapper.ERROR_INSTALL_USEREXIT);
Terminate(ErrorCode.ERROR_CANCELLED);
}

Directories.Initialize(BaseDirectory);
Expand All @@ -222,7 +208,7 @@ protected override void OnStartup(StartupEventArgs e)
// just in case the user decides to cancel the install
if (!IsFirstRun)
{
InitLog();
Logger.Initialize(IsUninstall);
Settings.Load();
State.Load();
FastFlags.Load();
Expand Down
30 changes: 12 additions & 18 deletions Bloxstrap/Bootstrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,6 @@ namespace Bloxstrap
public class Bootstrapper
{
#region Properties

// https://learn.microsoft.com/en-us/windows/win32/msi/error-codes
public const int ERROR_SUCCESS = 0;
public const int ERROR_INSTALL_USEREXIT = 1602;
public const int ERROR_INSTALL_FAILURE = 1603;

// in case a new package is added, you can find the corresponding directory
// by opening the stock bootstrapper in a hex editor
// TODO - there ideally should be a less static way to do this that's not hardcoded?
Expand Down Expand Up @@ -109,7 +103,7 @@ private void SetStatus(string message)
Dialog.Message = message;
}

private void UpdateProgressbar()
private void UpdateProgressBar()
{
int newProgress = (int)Math.Floor(_progressIncrement * _totalDownloadedBytes);

Expand Down Expand Up @@ -378,7 +372,7 @@ public void CancelInstall()
{
if (!_isInstalling)
{
App.Terminate(ERROR_INSTALL_USEREXIT);
App.Terminate(ErrorCode.ERROR_CANCELLED);
return;
}

Expand All @@ -401,7 +395,7 @@ public void CancelInstall()
App.Logger.WriteLine($"[Bootstrapper::CancelInstall] {ex}");
}

App.Terminate(ERROR_INSTALL_USEREXIT);
App.Terminate(ErrorCode.ERROR_CANCELLED);
}
#endregion

Expand Down Expand Up @@ -581,9 +575,9 @@ private async Task CheckForUpdates()
return;
}

App.Logger.WriteLine($"[Bootstrapper::CheckForUpdates] Checking for {App.ProjectName} updates...");
App.Logger.WriteLine($"[Bootstrapper::CheckForUpdates] Checking for updates...");

var releaseInfo = await Utilities.GetJson<GithubRelease>($"https://api.github.com/repos/{App.ProjectRepository}/releases/latest");
var releaseInfo = await Utility.Http.GetJson<GithubRelease>($"https://api.github.com/repos/{App.ProjectRepository}/releases/latest");

if (releaseInfo is null || releaseInfo.Assets is null)
{
Expand Down Expand Up @@ -629,10 +623,11 @@ private async Task CheckForUpdates()
startInfo.ArgumentList.Add(arg);

App.Settings.Save();
App.ShouldSaveConfigs = false;

Process.Start(startInfo);

Environment.Exit(0);
App.Terminate();
}

private void Uninstall()
Expand All @@ -649,7 +644,7 @@ private void Uninstall()
);

if (result != MessageBoxResult.OK)
Environment.Exit(ERROR_INSTALL_USEREXIT);
App.Terminate(ErrorCode.ERROR_CANCELLED);

try
{
Expand All @@ -669,7 +664,6 @@ private void Uninstall()

SetStatus($"Uninstalling {App.ProjectName}...");

//App.Settings.ShouldSave = false;
App.ShouldSaveConfigs = false;

// check if stock bootstrapper is still installed
Expand Down Expand Up @@ -759,7 +753,7 @@ private async Task InstallLatestVersion()
MessageBoxImage.Error
);

App.Terminate(ERROR_INSTALL_FAILURE);
App.Terminate(ErrorCode.ERROR_INSTALL_FAILURE);
return;
}

Expand Down Expand Up @@ -1135,7 +1129,7 @@ private async Task DownloadPackage(Package package)
{
App.Logger.WriteLine($"[Bootstrapper::DownloadPackage] {package.Name} is already downloaded, skipping...");
_totalDownloadedBytes += package.PackedSize;
UpdateProgressbar();
UpdateProgressBar();
return;
}
}
Expand All @@ -1147,7 +1141,7 @@ private async Task DownloadPackage(Package package)
App.Logger.WriteLine($"[Bootstrapper::DownloadPackage] Found existing version of {package.Name} ({robloxPackageLocation})! Copying to Downloads folder...");
File.Copy(robloxPackageLocation, packageLocation);
_totalDownloadedBytes += package.PackedSize;
UpdateProgressbar();
UpdateProgressBar();
return;
}

Expand Down Expand Up @@ -1179,7 +1173,7 @@ private async Task DownloadPackage(Package package)
await fileStream.WriteAsync(buffer, 0, bytesRead, _cancelTokenSource.Token);

_totalDownloadedBytes += bytesRead;
UpdateProgressbar();
UpdateProgressBar();
}
}

Expand Down
14 changes: 14 additions & 0 deletions Bloxstrap/Enums/ErrorCode.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace Bloxstrap.Enums
{
// https://learn.microsoft.com/en-us/windows/win32/msi/error-codes
// https://i-logic.com/serial/errorcodes.htm
// just the ones that we're interested in

public enum ErrorCode
{
ERROR_SUCCESS = 0,
ERROR_INSTALL_USEREXIT = 1602,
ERROR_INSTALL_FAILURE = 1603,
ERROR_CANCELLED = 1223
}
}
7 changes: 1 addition & 6 deletions Bloxstrap/FastFlagManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,6 @@ public override void Load()

public override void Save()
{
App.Logger.WriteLine($"[FastFlagManager::Save] Attempting to save JSON to {FileLocation}...");

// reload for any changes made while the menu was open
Load();

Expand All @@ -163,12 +161,9 @@ public override void Save()
Prop[change.Key] = change.Value;
}

Directory.CreateDirectory(Path.GetDirectoryName(FileLocation)!);
File.WriteAllText(FileLocation, JsonSerializer.Serialize(Prop, new JsonSerializerOptions { WriteIndented = true }));
base.Save();

Changes.Clear();

App.Logger.WriteLine($"[FastFlagManager::Save] JSON saved!");
}
}
}
6 changes: 3 additions & 3 deletions Bloxstrap/Integrations/DiscordRichPresence.cs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public async Task<bool> SetCurrentGame()

App.Logger.WriteLine($"[DiscordRichPresence::SetCurrentGame] Setting presence for Place ID {_activityWatcher.ActivityPlaceId}");

var universeIdResponse = await Utilities.GetJson<UniverseIdResponse>($"https://apis.roblox.com/universes/v1/places/{_activityWatcher.ActivityPlaceId}/universe");
var universeIdResponse = await Utility.Http.GetJson<UniverseIdResponse>($"https://apis.roblox.com/universes/v1/places/{_activityWatcher.ActivityPlaceId}/universe");
if (universeIdResponse is null)
{
App.Logger.WriteLine($"[DiscordRichPresence::SetCurrentGame] Could not get Universe ID!");
Expand All @@ -129,7 +129,7 @@ public async Task<bool> SetCurrentGame()
_activityWatcher.ActivityIsTeleport = false;
_currentUniverseId = universeId;

var gameDetailResponse = await Utilities.GetJson<ApiArrayResponse<GameDetailResponse>>($"https://games.roblox.com/v1/games?universeIds={universeId}");
var gameDetailResponse = await Utility.Http.GetJson<ApiArrayResponse<GameDetailResponse>>($"https://games.roblox.com/v1/games?universeIds={universeId}");
if (gameDetailResponse is null || !gameDetailResponse.Data.Any())
{
App.Logger.WriteLine($"[DiscordRichPresence::SetCurrentGame] Could not get Universe info!");
Expand All @@ -139,7 +139,7 @@ public async Task<bool> SetCurrentGame()
GameDetailResponse universeDetails = gameDetailResponse.Data.ToArray()[0];
App.Logger.WriteLine($"[DiscordRichPresence::SetCurrentGame] Got Universe details");

var universeThumbnailResponse = await Utilities.GetJson<ApiArrayResponse<ThumbnailResponse>>($"https://thumbnails.roblox.com/v1/games/icons?universeIds={universeId}&returnPolicy=PlaceHolder&size=512x512&format=Png&isCircular=false");
var universeThumbnailResponse = await Utility.Http.GetJson<ApiArrayResponse<ThumbnailResponse>>($"https://thumbnails.roblox.com/v1/games/icons?universeIds={universeId}&returnPolicy=PlaceHolder&size=512x512&format=Png&isCircular=false");
if (universeThumbnailResponse is null || !universeThumbnailResponse.Data.Any())
{
App.Logger.WriteLine($"[DiscordRichPresence::SetCurrentGame] Could not get Universe thumbnail info!");
Expand Down
14 changes: 7 additions & 7 deletions Bloxstrap/JsonManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace Bloxstrap

public virtual void Load()
{
App.Logger.WriteLine($"[JsonManager<{typeof(T).Name}>::Load] Loading JSON from {FileLocation}...");
App.Logger.WriteLine($"[JsonManager<{typeof(T).Name}>::Load] Loading from {FileLocation}...");

try
{
Expand All @@ -22,28 +22,28 @@ public virtual void Load()

Prop = settings;

App.Logger.WriteLine($"[JsonManager<{typeof(T).Name}>::Load] JSON loaded successfully!");
App.Logger.WriteLine($"[JsonManager<{typeof(T).Name}>::Load] Loaded successfully!");
}
catch (Exception ex)
{
App.Logger.WriteLine($"[JsonManager<{typeof(T).Name}>::Load] Failed to load JSON! ({ex.Message})");
App.Logger.WriteLine($"[JsonManager<{typeof(T).Name}>::Load] Failed to load! ({ex.Message})");
}
}

public virtual void Save()
{
App.Logger.WriteLine($"[JsonManager<{typeof(T).Name}>::Save] Attempting to save JSON to {FileLocation}...");

if (!App.ShouldSaveConfigs)
{
App.Logger.WriteLine($"[JsonManager<{typeof(T).Name}>::Save] Aborted save (ShouldSave set to false)");
App.Logger.WriteLine($"[JsonManager<{typeof(T).Name}>::Save] Save request ignored");
return;
}

App.Logger.WriteLine($"[JsonManager<{typeof(T).Name}>::Save] Saving to {FileLocation}...");

Directory.CreateDirectory(Path.GetDirectoryName(FileLocation)!);
File.WriteAllText(FileLocation, JsonSerializer.Serialize(Prop, new JsonSerializerOptions { WriteIndented = true }));

App.Logger.WriteLine($"[JsonManager<{typeof(T).Name}>::Save] JSON saved!");
App.Logger.WriteLine($"[JsonManager<{typeof(T).Name}>::Save] Save complete!");
}
}
}
37 changes: 27 additions & 10 deletions Bloxstrap/Logger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,27 +20,44 @@ public class Logger

public readonly List<string> Backlog = new();
public bool Initialized = false;
public string? Filename;
public string? FileLocation;

public void Initialize(string filename)
public void Initialize(bool useTempDir = false)
{
if (_filestream is not null)
throw new Exception("Logger is already initialized");
string directory = useTempDir ? Path.Combine(Directories.LocalAppData, "Temp") : Path.Combine(Directories.Base, "Logs");
string timestamp = DateTime.UtcNow.ToString("yyyyMMdd'T'HHmmss'Z'");
string filename = $"{App.ProjectName}_{timestamp}.log";
string location = Path.Combine(directory, filename);

WriteLine($"[Logger::Initialize] Initializing at {location}");

string? directory = Path.GetDirectoryName(filename);
if (Initialized)
throw new Exception("Logger is already initialized");

if (directory is not null)
Directory.CreateDirectory(directory);
Directory.CreateDirectory(directory);

_filestream = File.Open(filename, FileMode.Create, FileAccess.Write, FileShare.Read);
_filestream = File.Open(location, FileMode.Create, FileAccess.Write, FileShare.Read);

if (Backlog.Count > 0)
WriteToLog(string.Join("\r\n", Backlog));

WriteLine($"[Logger::Logger] Initialized at {filename}");
WriteLine($"[Logger::Initialize] Finished initializing!");

Initialized = true;
Filename = filename;
FileLocation = location;

// clean up any logs older than a week
if (!useTempDir)
{
foreach (FileInfo log in new DirectoryInfo(directory).GetFiles())
{
if (log.LastWriteTimeUtc.AddDays(7) > DateTime.UtcNow)
continue;

App.Logger.WriteLine($"[Logger::Initialize] Cleaning up old log file '{log.Name}'");
log.Delete();
}
}
}

public void WriteLine(string message)
Expand Down
2 changes: 1 addition & 1 deletion Bloxstrap/ProtocolHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public static string ParseUri(string protocol)
MessageBoxResult result = App.Settings.Prop.ChannelChangeMode == ChannelChangeMode.Automatic
? MessageBoxResult.Yes
: Controls.ShowMessageBox(
$"{App.ProjectName} was launched with the Roblox build channel set to {val}, however your current preferred channel is {App.Settings.Prop.Channel}.\n\n" +
$"Roblox is attempting to set your channel to {val}, however your current preferred channel is {App.Settings.Prop.Channel}.\n\n" +
$"Would you like to switch channels from {App.Settings.Prop.Channel} to {val}?",
MessageBoxImage.Question,
MessageBoxButton.YesNo
Expand Down
Loading

0 comments on commit 0a7ae17

Please sign in to comment.