Skip to content

Commit

Permalink
Use static JSON models and some cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
pizzaboxer committed Aug 22, 2022
1 parent 0da759d commit 3e42c75
Show file tree
Hide file tree
Showing 14 changed files with 157 additions and 111 deletions.
31 changes: 14 additions & 17 deletions Bloxstrap/Bootstrapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,6 @@ namespace Bloxstrap
public partial class Bootstrapper
{
#region Properties
private string? LaunchCommandLine;

private string VersionGuid;
private PackageManifest VersionPackageManifest;
private string VersionFolder;

private readonly bool FreshInstall;

private int ProgressIncrement;
private bool CancelFired = false;

private static readonly HttpClient Client = new();

// 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 @@ -79,8 +66,18 @@ public partial class Bootstrapper
"By default, two mod presets are provided for restoring the old death\n" +
"sound and the old mouse cursor.\n";

// TODO: reduce reliance on event handlers for signalling property changes to the bootstrapper dialog
// i mean, chances are we can just use IBootstrapperDialog now?
private static readonly HttpClient Client = new();

private string? LaunchCommandLine;

private string VersionGuid;
private PackageManifest VersionPackageManifest;
private string VersionFolder;

private readonly bool FreshInstall;

private int ProgressIncrement;
private bool CancelFired = false;

public IBootstrapperDialog Dialog;
#endregion
Expand Down Expand Up @@ -498,7 +495,7 @@ private void ApplyModifications()
string relativeFile = file.Substring(modFolder.Length + 1);

// ignore files placed in the root directory
if (!relativeFile.Contains(@"\"))
if (!relativeFile.Contains('\\'))
continue;

modFolderFiles.Add(relativeFile);
Expand Down Expand Up @@ -554,7 +551,7 @@ private void ApplyModifications()
File.WriteAllLines(manifestFile, modFolderFiles);
}

private void CheckModPreset(bool condition, string location, string base64Contents)
private static void CheckModPreset(bool condition, string location, string base64Contents)
{
string modFolderLocation = Path.Combine(Directories.Modifications, location);

Expand Down
10 changes: 5 additions & 5 deletions Bloxstrap/Dialogs/BootstrapperStyles/BootstrapperStyleForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public class BootstrapperStyleForm : Form, IBootstrapperDialog
{
public Bootstrapper? Bootstrapper { get; set; }

protected virtual string _message { get; set; }
protected virtual string _message { get; set; } = "Please wait...";
protected virtual ProgressBarStyle _progressStyle { get; set; }
protected virtual int _progressValue { get; set; }
protected virtual bool _cancelEnabled { get; set; }
Expand All @@ -18,7 +18,7 @@ public string Message
set
{
if (this.InvokeRequired)
this.Invoke(new Action(() => { Message = value; }));
this.Invoke(new Action(() => { _message = value; }));
else
_message = value;
}
Expand All @@ -30,7 +30,7 @@ public ProgressBarStyle ProgressStyle
set
{
if (this.InvokeRequired)
this.Invoke(new Action(() => { ProgressStyle = value; }));
this.Invoke(new Action(() => { _progressStyle = value; }));
else
_progressStyle = value;
}
Expand All @@ -42,7 +42,7 @@ public int ProgressValue
set
{
if (this.InvokeRequired)
this.Invoke(new Action(() => { ProgressValue = value; }));
this.Invoke(new Action(() => { _progressValue = value; }));
else
_progressValue = value;
}
Expand All @@ -54,7 +54,7 @@ public bool CancelEnabled
set
{
if (this.InvokeRequired)
this.Invoke(new Action(() => { CancelEnabled = value; }));
this.Invoke(new Action(() => { _cancelEnabled = value; }));
else
_cancelEnabled = value;
}
Expand Down
4 changes: 2 additions & 2 deletions Bloxstrap/Dialogs/Preferences.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public partial class Preferences : Form

private BootstrapperStyle SelectedStyle
{
get => (BootstrapperStyle)_selectedStyle;
get => _selectedStyle ?? BootstrapperStyle.ProgressDialog;

set
{
Expand All @@ -53,7 +53,7 @@ private BootstrapperStyle SelectedStyle

private BootstrapperIcon SelectedIcon
{
get => (BootstrapperIcon)_selectedIcon;
get => _selectedIcon ?? BootstrapperIcon.IconBloxstrap;

set
{
Expand Down
27 changes: 12 additions & 15 deletions Bloxstrap/Helpers/Integrations/DiscordRichPresence.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
using Newtonsoft.Json.Linq;
using Bloxstrap.Models;
using DiscordRPC;

namespace Bloxstrap.Helpers.Integrations
Expand All @@ -9,22 +9,19 @@ internal class DiscordRichPresence : IDisposable

public async Task<bool> SetPresence(string placeId)
{
string placeName;
string placeThumbnail;
string creatorName;

// null checking could probably be a lot more concrete here
JObject placeInfo = await Utilities.GetJson($"https://economy.roblox.com/v2/assets/{placeId}/details");
var placeInfo = await Utilities.GetJson<RobloxAsset>($"https://economy.roblox.com/v2/assets/{placeId}/details");

placeName = placeInfo["Name"].Value<string>();
creatorName = placeInfo["Creator"]["Name"].Value<string>();

JObject thumbnailInfo = await Utilities.GetJson($"https://thumbnails.roblox.com/v1/places/gameicons?placeIds={placeId}&returnPolicy=PlaceHolder&size=512x512&format=Png&isCircular=false");

if (thumbnailInfo["data"] is null)
if (placeInfo is null || placeInfo.Creator is null)
return false;

placeThumbnail = thumbnailInfo["data"][0]["imageUrl"].Value<string>();
var thumbnailInfo = await Utilities.GetJson<RobloxThumbnails>($"https://thumbnails.roblox.com/v1/places/gameicons?placeIds={placeId}&returnPolicy=PlaceHolder&size=512x512&format=Png&isCircular=false");

if (thumbnailInfo is null)
placeThumbnail = "roblox"; //fallback
else
placeThumbnail = thumbnailInfo.Data[0].ImageUrl;

DiscordRPC.Button[]? buttons = null;

Expand All @@ -50,14 +47,14 @@ public async Task<bool> SetPresence(string placeId)

RichPresence.SetPresence(new RichPresence()
{
Details = placeName,
State = $"by {creatorName}",
Details = placeInfo.Name,
State = $"by {placeInfo.Creator.Name}",
Timestamps = new Timestamps() { Start = DateTime.UtcNow },
Buttons = buttons,
Assets = new Assets()
{
LargeImageKey = placeThumbnail,
LargeImageText = placeName,
LargeImageText = placeInfo.Name,
SmallImageKey = "roblox",
SmallImageText = "Roblox"
}
Expand Down
25 changes: 9 additions & 16 deletions Bloxstrap/Helpers/Integrations/RbxFpsUnlocker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

using Newtonsoft.Json.Linq;

using Bloxstrap.Models;

namespace Bloxstrap.Helpers.Integrations
{
internal class RbxFpsUnlocker
Expand Down Expand Up @@ -35,30 +37,21 @@ public static async Task CheckInstall()
if (!Program.Settings.RFUEnabled)
{
if (Directory.Exists(folderLocation))
{
Directory.Delete(folderLocation, true);
}

return;
}

DateTime lastReleasePublish;
string downloadUrl;

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

// so... rbxfpsunlocker does not actually have any version info for the executable
// meaning the best way we can check for a new version is comparing time last download to time last release published
lastReleasePublish = DateTime.Parse(releaseInfo["created_at"].Value<string>());
downloadUrl = releaseInfo["assets"][0]["browser_download_url"].Value<string>();
}
catch (Exception ex)
{
Debug.WriteLine($"Failed to fetch latest version info! ({ex.Message})");
if (releaseInfo is null || releaseInfo.CreatedAt is null || releaseInfo.Assets is null)
return;
}

lastReleasePublish = DateTime.Parse(releaseInfo.CreatedAt);
downloadUrl = releaseInfo.Assets[0].BrowserDownloadUrl;

Directory.CreateDirectory(folderLocation);

Expand All @@ -79,9 +72,9 @@ public static async Task CheckInstall()
{
byte[] bytes = await client.GetByteArrayAsync(downloadUrl);

using (MemoryStream zipStream = new MemoryStream(bytes))
using (MemoryStream zipStream = new(bytes))
{
ZipArchive zip = new ZipArchive(zipStream);
ZipArchive zip = new(zipStream);
zip.ExtractToDirectory(folderLocation, true);
}
}
Expand Down
9 changes: 2 additions & 7 deletions Bloxstrap/Helpers/RSMM/Package.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,11 @@ namespace Bloxstrap.Helpers.RSMM
{
internal class Package
{
public string Name { get; set; }
public string Signature { get; set; }
public string Name { get; set; } = "";
public string Signature { get; set; } = "";
public int PackedSize { get; set; }
public int Size { get; set; }

public bool Exists { get; set; }
public bool ShouldInstall { get; set; }

internal byte[] Data { get; set; }

public override string ToString()
{
return $"[{Signature}] {Name}";
Expand Down
21 changes: 9 additions & 12 deletions Bloxstrap/Helpers/Updater.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Text.Json;

using Newtonsoft.Json.Linq;

using Bloxstrap.Models;

namespace Bloxstrap.Helpers
{
public class Updater
Expand Down Expand Up @@ -52,20 +56,13 @@ public static async Task Check()
string latestVersion;
string releaseNotes;

// get the latest version according to the latest github release info
// it should contain the latest product version, which we can check against
try
{
JObject releaseInfo = await Utilities.GetJson($"https://api.github.com/repos/{Program.ProjectRepository}/releases/latest");
var releaseInfo = await Utilities.GetJson<GithubRelease>($"https://api.github.com/repos/{Program.ProjectRepository}/releases/latest");

latestVersion = releaseInfo["name"].Value<string>();
releaseNotes = releaseInfo["body"].Value<string>();
}
catch (Exception ex)
{
Debug.WriteLine($"Failed to fetch latest version info! ({ex.Message})");
if (releaseInfo is null || releaseInfo.Name is null || releaseInfo.Body is null)
return;
}

latestVersion = releaseInfo.Name;
releaseNotes = releaseInfo.Body;

if (currentVersion != latestVersion)
{
Expand Down
24 changes: 11 additions & 13 deletions Bloxstrap/Helpers/Utilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.Json;

namespace Bloxstrap.Helpers
{
Expand All @@ -15,16 +13,16 @@ public static void OpenWebsite(string website)
Process.Start(new ProcessStartInfo { FileName = website, UseShellExecute = true });
}

public static async Task<JObject> GetJson(string url)
{
using (HttpClient client = new())
{
client.DefaultRequestHeaders.Add("User-Agent", Program.ProjectRepository);
public static async Task<T?> GetJson<T>(string url)
{
using (HttpClient client = new())
{
client.DefaultRequestHeaders.Add("User-Agent", Program.ProjectRepository);

string jsonString = await client.GetStringAsync(url);
return (JObject)JsonConvert.DeserializeObject(jsonString);
}
}
string json = await client.GetStringAsync(url);
return JsonSerializer.Deserialize<T>(json);
}
}

public static string MD5File(string filename)
{
Expand All @@ -47,7 +45,7 @@ public static string MD5File(string filename)

string substr = subject.Substring(subject.LastIndexOf(key) + key.Length);

if (substr.IndexOf(delimiter) == -1)
if (!substr.Contains(delimiter))
return null;

return substr.Split(delimiter)[0];
Expand Down
25 changes: 25 additions & 0 deletions Bloxstrap/Models/GithubRelease.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System.Text.Json.Serialization;

namespace Bloxstrap.Models
{
public class GithubRelease
{
[JsonPropertyName("name")]
public string? Name { get; set; }

[JsonPropertyName("body")]
public string? Body { get; set; }

[JsonPropertyName("created_at")]
public string? CreatedAt { get; set; }

[JsonPropertyName("assets")]
public List<GithubReleaseAsset>? Assets { get; set; }
}

public class GithubReleaseAsset
{
[JsonPropertyName("browser_download_url")]
public string? BrowserDownloadUrl { get; set; }
}
}
13 changes: 13 additions & 0 deletions Bloxstrap/Models/RobloxAsset.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace Bloxstrap.Models
{
public class RobloxAsset
{
public string? Name { get; set; }
public RobloxAssetCreator? Creator { get; set; }
}

public class RobloxAssetCreator
{
public string? Name { get; set; }
}
}
16 changes: 16 additions & 0 deletions Bloxstrap/Models/RobloxThumbnails.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System.Text.Json.Serialization;

namespace Bloxstrap.Models
{
public class RobloxThumbnails
{
[JsonPropertyName("data")]
public List<RobloxThumbnail>? Data { get; set; }
}

public class RobloxThumbnail
{
[JsonPropertyName("imageUrl")]
public string? ImageUrl { get; set; }
}
}
Loading

0 comments on commit 3e42c75

Please sign in to comment.