Skip to content

Commit

Permalink
Merge pull request #70 from LittleBigRefresh/core
Browse files Browse the repository at this point in the history
Move non-UI components to new `Refresher.Core` project, move to NotEnoughLogs
  • Loading branch information
jvyden authored Sep 19, 2024
2 parents cc89f92 + 4c86b33 commit 2b265be
Show file tree
Hide file tree
Showing 34 changed files with 241 additions and 137 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
using FluentFTP;
using Refresher.Exceptions;
using Refresher.Core.Exceptions;

namespace Refresher.Accessors;
namespace Refresher.Core.Accessors;

public class ConsolePatchAccessor : PatchAccessor, IDisposable
{
Expand All @@ -27,7 +27,7 @@ public ConsolePatchAccessor(string remoteIp)

private byte[]? GetIdps()
{
Program.Log("Getting IDPS...", "IDPS");
State.Logger.LogInfo(IDPS, "Getting IDPS from the console...");
UriBuilder idpsPs3 = new("http", this._remoteIp, 80, "idps.ps3");
UriBuilder idpsHex = new("http", this._remoteIp, 80, "dev_hdd0/idps.hex");
UriBuilder idpsHexUsb = new("http", this._remoteIp, 80, "dev_usb000/idps.hex");
Expand All @@ -48,7 +48,7 @@ public ConsolePatchAccessor(string remoteIp)
{
HttpResponseMessage response;

Program.Log($" {stepName} ({uri.AbsolutePath})", "IDPS");
State.Logger.LogDebug(IDPS, $" {stepName} ({uri.AbsolutePath})");
try
{
response = client.GetAsync(uri).Result;
Expand All @@ -62,17 +62,17 @@ public ConsolePatchAccessor(string remoteIp)
{
if (!HandleIdpsRequestError(e))
{
Program.Log($"Couldn't fetch the IDPS from the PS3 because of an unknown error: {e}", "IDPS", BreadcrumbLevel.Error);
State.Logger.LogError(IDPS, $"Couldn't fetch the IDPS from the PS3 because of an unknown error: {e}");
SentrySdk.CaptureException(e);
}
return null;
}
Program.Log($" {(int)response.StatusCode} {response.StatusCode} (success: {response.IsSuccessStatusCode})", "IDPS");
State.Logger.LogDebug(IDPS, $" {(int)response.StatusCode} {response.StatusCode} (success: {response.IsSuccessStatusCode})");

if (!response.IsSuccessStatusCode)
{
Program.Log("Couldn't fetch the IDPS from the PS3 because of a bad status code.", "IDPS", BreadcrumbLevel.Error);
Program.Log(response.Content.ReadAsStringAsync().Result, "IDPS", BreadcrumbLevel.Debug);
State.Logger.LogError(IDPS, "Couldn't fetch the IDPS from the PS3 because of a bad status code.");
State.Logger.LogDebug(IDPS, response.Content.ReadAsStringAsync().Result);
return null;
}

Expand All @@ -83,7 +83,7 @@ private static bool HandleIdpsRequestError(Exception inner)
{
if (inner is HttpRequestException httpException)
{
Program.Log($"Couldn't fetch the IDPS from the PS3 because we couldn't make the request: {httpException.Message}", "IDPS", BreadcrumbLevel.Error);
State.Logger.LogError(IDPS, $"Couldn't fetch the IDPS from the PS3 because we couldn't make the request: {httpException.Message}");
return true;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Refresher.Accessors;
namespace Refresher.Core.Accessors;

public class EmulatorPatchAccessor : PatchAccessor
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using Eto.Forms;

namespace Refresher.Accessors;
namespace Refresher.Core.Accessors;

public static class GameCacheAccessor
{
Expand All @@ -19,8 +17,9 @@ static GameCacheAccessor()
}
catch (IOException e)

Check warning on line 18 in Refresher.Core/Accessors/GameCacheAccessor.cs

View workflow job for this annotation

GitHub Actions / Build, Test, and Upload Builds (macos-latest)

The variable 'e' is declared but never used

Check warning on line 18 in Refresher.Core/Accessors/GameCacheAccessor.cs

View workflow job for this annotation

GitHub Actions / Build, Test, and Upload Builds (ubuntu-latest)

The variable 'e' is declared but never used

Check warning on line 18 in Refresher.Core/Accessors/GameCacheAccessor.cs

View workflow job for this annotation

GitHub Actions / Build, Test, and Upload Builds (windows-latest)

The variable 'e' is declared but never used
{
MessageBox.Show($"Couldn't create the directory for the games cache: {e.Message}\n" +
$"This error is rare and I don't know how to cleanly handle this scenario so Refresher is just gonna exit.");
// FIXME: no native MessageBox in Refresher.Core
// MessageBox.Show($"Couldn't create the directory for the games cache: {e.Message}\n" +
// $"This error is rare and I don't know how to cleanly handle this scenario so Refresher is just gonna exit.");
Environment.Exit(1); // shrug
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Refresher.Accessors;
namespace Refresher.Core.Accessors;

public abstract class PatchAccessor
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using System.Runtime.CompilerServices;

namespace Refresher.Exceptions;
namespace Refresher.Core.Exceptions;

public class FTPConnectionFailureException() : Exception("Could not connect to the FTP server.");
1 change: 1 addition & 0 deletions Refresher.Core/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global using static Refresher.Core.LogType;
18 changes: 18 additions & 0 deletions Refresher.Core/LogType.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
namespace Refresher.Core;

public enum LogType : byte
{
Patcher,
PPU,
Verify,
CLI,
PatchAccessor,
PatchForm,
IntegratedPatchForm,
InfoRetrieval,
Crypto,
IDPS,
OSIntegration,
AutoDiscover,
PSP,
}
31 changes: 31 additions & 0 deletions Refresher.Core/Logging/SentryBreadcrumbSink.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using NotEnoughLogs;
using NotEnoughLogs.Sinks;

namespace Refresher.Core.Logging;

public class SentryBreadcrumbSink : ILoggerSink
{
private static BreadcrumbLevel GetLevel(LogLevel level)
{
return level switch
{
LogLevel.Critical => BreadcrumbLevel.Critical,
LogLevel.Error => BreadcrumbLevel.Error,
LogLevel.Warning => BreadcrumbLevel.Warning,
LogLevel.Info => BreadcrumbLevel.Info,
LogLevel.Debug => BreadcrumbLevel.Debug,
LogLevel.Trace => BreadcrumbLevel.Debug,
_ => throw new ArgumentOutOfRangeException(nameof(level), level, null),
};
}

public void Log(LogLevel level, ReadOnlySpan<char> category, ReadOnlySpan<char> content)
{
SentrySdk.AddBreadcrumb(content.ToString(), category.ToString(), level: GetLevel(level));
}

public void Log(LogLevel level, ReadOnlySpan<char> category, ReadOnlySpan<char> format, params object[] args)
{
SentrySdk.AddBreadcrumb(string.Format(format.ToString(), args), category.ToString(), level: GetLevel(level));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@
using System.Text.RegularExpressions;
using ELFSharp.ELF;
using ELFSharp.ELF.Segments;
using Refresher.Verification;
using Refresher.Core.Verification;

namespace Refresher.Patching;
namespace Refresher.Core.Patching;

public partial class EbootPatcher : IPatcher
{
Expand Down Expand Up @@ -141,7 +141,7 @@ private static List<PatchTargetInfo> FindPatchableElements(Stream file)
FindLbpkDomains(reader, lbpkPositions, foundItems);

long end = Stopwatch.GetTimestamp();
Program.Log($"Detecting patchables took {(double)(end - start) / (double)Stopwatch.Frequency} seconds!");
State.Logger.LogDebug(Patcher, $"Detecting patchables took {(end - start) / (double)Stopwatch.Frequency} seconds!");
return foundItems;
}

Expand Down Expand Up @@ -245,7 +245,7 @@ private static void FilterValidUrls(BinaryReader reader, List<long> foundPossibl

if (UrlMatch().Matches(str).Count != 0)
{
Program.Log($"Found URL at offset {foundPosition}: '{str}'");
State.Logger.LogTrace(Patcher, $"Found URL at offset {foundPosition}: '{str}'");
foundItems.Add(new PatchTargetInfo
{
Length = len,
Expand Down Expand Up @@ -344,7 +344,7 @@ public static string GeneratePpuHash(Stream stream)

string ppuHash = BitConverter.ToString(hash.Hash!).Replace("-", "").ToLower();

Program.Log($"PPU hash: PPU-{ppuHash}", "PPU", BreadcrumbLevel.Debug);
State.Logger.LogDebug(PPU, $"PPU hash: PPU-{ppuHash}");
return ppuHash;
}

Expand All @@ -359,7 +359,7 @@ public List<Message> Verify(string url, bool patchDigest)

this.Stream.Position = 0;

Program.Log($"URL: {url}", "Verify");
State.Logger.LogInfo(LogType.Verify, $"Verifying EBOOT against URL: {url}");
// Check url
if (url.EndsWith('/'))
messages.Add(new Message(MessageLevel.Error,
Expand All @@ -373,7 +373,7 @@ public List<Message> Verify(string url, bool patchDigest)
{
Class output = ELFReader.CheckELFType(this.Stream);

Program.Log($"ELF class: {output}", "Verify");
State.Logger.LogDebug(LogType.Verify, $"ELF class: {output}");
if (output == Class.NotELF)
{
messages.Add(new Message(MessageLevel.Error, "EBOOT is not a valid ELF file."));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using Refresher.Verification;
using Refresher.Core.Verification;

namespace Refresher.Patching;
namespace Refresher.Core.Patching;

public interface IPatcher
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Refresher.Patching.PSP;
namespace Refresher.Core.Patching.PSP;

public class PSPPluginListEntry
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Refresher.Patching.PSP;
namespace Refresher.Core.Patching.PSP;

public static class PSPPluginListParser
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using System.Reflection;
using Refresher.Patching.PSP;
using Refresher.Verification;
using Refresher.Core.Patching.PSP;
using Refresher.Core.Verification;

namespace Refresher.Patching;
namespace Refresher.Core.Patching;

public class PSPPatcher : IPatcher
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Refresher.Patching;
namespace Refresher.Core.Patching;

public struct PatchTargetInfo
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Refresher.Patching;
namespace Refresher.Core.Patching;

public enum PatchTargetType
{
Expand Down
17 changes: 17 additions & 0 deletions Refresher.Core/Refresher.Core.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentFTP" Version="49.0.2" />
<PackageReference Include="NotEnoughLogs" Version="2.0.3" />
<PackageReference Include="SCEToolSharp" Version="1.2.2" />
<PackageReference Include="ELFSharp" Version="2.17.3" />
<PackageReference Include="Sentry" Version="4.4.0" />
</ItemGroup>

</Project>
23 changes: 23 additions & 0 deletions Refresher.Core/State.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using NotEnoughLogs;
using NotEnoughLogs.Behaviour;
using NotEnoughLogs.Sinks;
using Refresher.Core.Logging;

namespace Refresher.Core;

public static class State
{
public static readonly Logger Logger = InitializeLogger([new ConsoleSink(), new SentryBreadcrumbSink()]);

private static Logger InitializeLogger(IEnumerable<ILoggerSink> sinks)
{
// if(Logger != null)
// Logger.Dispose();

return new Logger(sinks, new LoggerConfiguration
{
Behaviour = new DirectLoggingBehaviour(),
MaxLevel = LogLevel.Trace,
});
}
}
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
using Newtonsoft.Json;
using System.Text.Json.Serialization;

namespace Refresher.Verification.Autodiscover;
namespace Refresher.Core.Verification.Autodiscover;

#nullable disable

public class AutodiscoverResponse
{
private const int SupportedVersion = 2;

[JsonProperty("version")]
[JsonPropertyName("version")]
public int Version { get; set; }

[JsonProperty("serverBrand")]
[JsonPropertyName("serverBrand")]
public string ServerBrand { get; set; }

[JsonProperty("url")]
[JsonPropertyName("url")]
public string Url { get; set; }

[JsonProperty("usesCustomDigestKey")]
[JsonPropertyName("usesCustomDigestKey")]
public bool? UsesCustomDigestKey { get; set; } = false; // We mark as nullable, as this was added in version 2
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Refresher.Verification;
namespace Refresher.Core.Verification;

public readonly struct Message
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
namespace Refresher.Verification;
namespace Refresher.Core.Verification;

public enum MessageLevel
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System.Text;

namespace Refresher.Verification;
namespace Refresher.Core.Verification;

// TODO: Move to separate repository with its own nuget package
// Maybe combine with NPTicket?
Expand Down
6 changes: 6 additions & 0 deletions Refresher.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Refresher", "Refresher\Refresher.csproj", "{0A67E8A2-0E7C-4BB7-90E5-8D8EA59631D4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Refresher.Core", "Refresher.Core\Refresher.Core.csproj", "{49CE141A-8BD7-4CD5-BE86-257BDA5C5796}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -18,5 +20,9 @@ Global
{0A67E8A2-0E7C-4BB7-90E5-8D8EA59631D4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0A67E8A2-0E7C-4BB7-90E5-8D8EA59631D4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0A67E8A2-0E7C-4BB7-90E5-8D8EA59631D4}.Release|Any CPU.Build.0 = Release|Any CPU
{49CE141A-8BD7-4CD5-BE86-257BDA5C5796}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{49CE141A-8BD7-4CD5-BE86-257BDA5C5796}.Debug|Any CPU.Build.0 = Debug|Any CPU
{49CE141A-8BD7-4CD5-BE86-257BDA5C5796}.Release|Any CPU.ActiveCfg = Release|Any CPU
{49CE141A-8BD7-4CD5-BE86-257BDA5C5796}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
Loading

0 comments on commit 2b265be

Please sign in to comment.