Reduce tupling even more

This commit is contained in:
Matt Nadareski
2024-11-03 22:51:24 -05:00
parent ee0ccecfb2
commit 98bacf11fc
10 changed files with 83 additions and 52 deletions

View File

@@ -32,6 +32,7 @@
- Reduce call complexity for login result
- Use new ProtectionDictionary type
- Replace user info func with ProcessUserInfoDelegate
- Reduce tupling even more
### 3.2.2 (2024-09-24)

View File

@@ -40,7 +40,7 @@ namespace MPF.CLI
}
// Try processing the common arguments
(bool success, MediaType mediaType, RedumpSystem? knownSystem, var error) = OptionsLoader.ProcessCommonArguments(args);
bool success = OptionsLoader.ProcessCommonArguments(args, out MediaType mediaType, out RedumpSystem? knownSystem, out var error);
if (!success)
{
DisplayHelp(error);

View File

@@ -55,7 +55,7 @@ namespace MPF.Check
}
// Try processing the common arguments
(bool success, MediaType mediaType, RedumpSystem? knownSystem, var error) = OptionsLoader.ProcessCommonArguments(args);
bool success = OptionsLoader.ProcessCommonArguments(args, out MediaType mediaType, out RedumpSystem? knownSystem, out var error);
if (!success)
{
DisplayHelp(error);

View File

@@ -496,7 +496,7 @@ namespace MPF.Frontend
// Write the text output
resultProgress?.Report(ResultEventArgs.Success("Writing submission information file..."));
(bool txtSuccess, string txtResult) = WriteOutputData(outputDirectory, filenameSuffix, formattedValues);
bool txtSuccess = WriteOutputData(outputDirectory, filenameSuffix, formattedValues, out string txtResult);
if (txtSuccess)
resultProgress?.Report(ResultEventArgs.Success(txtResult));
else
@@ -567,11 +567,11 @@ namespace MPF.Frontend
if (_options.CreateIRDAfterDumping && _system == RedumpSystem.SonyPlayStation3 && _type == MediaType.BluRay)
{
resultProgress?.Report(ResultEventArgs.Success("Creating IRD... please wait!"));
(bool deleteSuccess, string deleteResult) = await WriteIRD(OutputPath, submissionInfo?.Extras?.DiscKey, submissionInfo?.Extras?.DiscID, submissionInfo?.Extras?.PIC, submissionInfo?.SizeAndChecksums?.Layerbreak, submissionInfo?.SizeAndChecksums?.CRC32);
bool deleteSuccess = await WriteIRD(OutputPath, submissionInfo?.Extras?.DiscKey, submissionInfo?.Extras?.DiscID, submissionInfo?.Extras?.PIC, submissionInfo?.SizeAndChecksums?.Layerbreak, submissionInfo?.SizeAndChecksums?.CRC32);
if (deleteSuccess)
resultProgress?.Report(ResultEventArgs.Success(deleteResult));
resultProgress?.Report(ResultEventArgs.Success("IRD created!"));
else
resultProgress?.Report(ResultEventArgs.Failure(deleteResult));
resultProgress?.Report(ResultEventArgs.Failure("Failed to create IRD"));
}
resultProgress?.Report(ResultEventArgs.Success("Submission information process complete!"));
@@ -639,11 +639,14 @@ namespace MPF.Frontend
/// <param name="filenameSuffix">Optional suffix to append to the filename</param>
/// <param name="lines">Preformatted list of lines to write out to the file</param>
/// <returns>True on success, false on error</returns>
private static (bool, string) WriteOutputData(string? outputDirectory, string? filenameSuffix, List<string>? lines)
private static bool WriteOutputData(string? outputDirectory, string? filenameSuffix, List<string>? lines, out string status)
{
// Check to see if the inputs are valid
if (lines == null)
return (false, "No formatted data found to write!");
{
status = "No formatted data found to write!";
return false;
}
// Now write out to a generic file
try
@@ -667,10 +670,12 @@ namespace MPF.Frontend
}
catch (Exception ex)
{
return (false, $"Writing could not complete: {ex}");
status = $"Writing could not complete: {ex}";
return false;
}
return (true, "Writing complete!");
status = "Writing complete!";
return true;
}
// MOVE TO REDUMPLIB
@@ -799,7 +804,12 @@ namespace MPF.Frontend
/// <param name="filenameSuffix">Optional suffix to append to the filename</param>
/// <param name="outputFilename">Output filename to use as the base path</param>
/// <returns>True on success, false on error</returns>
private static async Task<(bool, string)> WriteIRD(string isoPath, string? discKeyString, string? discIDString, string? picString, long? layerbreak, string? crc32)
private static async Task<bool> WriteIRD(string isoPath,
string? discKeyString,
string? discIDString,
string? picString,
long? layerbreak,
string? crc32)
{
try
{
@@ -809,7 +819,7 @@ namespace MPF.Frontend
// Parse disc key from submission info (Required)
byte[]? discKey = ProcessingTool.ParseHexKey(discKeyString);
if (discKey == null)
return (false, "Failed to create IRD: No key provided");
return false;
// Parse Disc ID from submission info (Optional)
byte[]? discID = ProcessingTool.ParseDiscID(discIDString);
@@ -838,12 +848,12 @@ namespace MPF.Frontend
// Write IRD to file
ird.Write(irdPath);
return (true, "IRD created!");
return true;
}
catch (Exception)
{
// We don't care what the error is
return (false, "Failed to create IRD");
return false;
}
}

View File

@@ -561,32 +561,37 @@ namespace MPF.Frontend.Tools
/// String representing the message to display the the user.
/// String representing the new release URL.
/// </returns>
public static (bool different, string message, string? url) CheckForNewVersion()
public static void CheckForNewVersion(out bool different, out string message, out string? url)
{
try
{
// Get current assembly version
var assemblyVersion = Assembly.GetEntryAssembly()?.GetName()?.Version;
if (assemblyVersion == null)
return (false, "Assembly version could not be determined", null);
{
different = false;
message = "Assembly version could not be determined";
url = null;
return;
}
string version = $"{assemblyVersion.Major}.{assemblyVersion.Minor}.{assemblyVersion.Build}";
// Get the latest tag from GitHub
var (tag, url) = GetRemoteVersionAndUrl();
bool different = version != tag && tag != null;
_ = GetRemoteVersionAndUrl(out string? tag, out url);
different = version != tag && tag != null;
string message = $"Local version: {version}"
message = $"Local version: {version}"
+ $"{Environment.NewLine}Remote version: {tag}"
+ (different
? $"{Environment.NewLine}The update URL has been added copied to your clipboard"
: $"{Environment.NewLine}You have the newest version!");
return (different, message, url);
}
catch (Exception ex)
{
return (false, ex.ToString(), null);
different = false;
message = ex.ToString();
url = null;
}
}
@@ -613,11 +618,12 @@ namespace MPF.Frontend.Tools
/// <summary>
/// Get the latest version of MPF from GitHub and the release URL
/// </summary>
private static (string? tag, string? url) GetRemoteVersionAndUrl()
private static bool GetRemoteVersionAndUrl(out string? tag, out string? url)
{
tag = null; url = null;
#if NET20 || NET35 || NET40
// Not supported in .NET Frameworks 2.0, 3.5, or 4.0
return (null, null);
return false;
#else
using var hc = new System.Net.Http.HttpClient();
#if NET452
@@ -625,22 +631,22 @@ namespace MPF.Frontend.Tools
#endif
// TODO: Figure out a better way than having this hardcoded...
string url = "https://api.github.com/repos/SabreTools/MPF/releases/latest";
var message = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
string releaseUrl = "https://api.github.com/repos/SabreTools/MPF/releases/latest";
var message = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, releaseUrl);
message.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:64.0) Gecko/20100101 Firefox/64.0");
var latestReleaseJsonString = hc.SendAsync(message)?.ConfigureAwait(false).GetAwaiter().GetResult()
.Content?.ReadAsStringAsync().ConfigureAwait(false).GetAwaiter().GetResult();
if (latestReleaseJsonString == null)
return (null, null);
return false;
var latestReleaseJson = Newtonsoft.Json.Linq.JObject.Parse(latestReleaseJsonString);
if (latestReleaseJson == null)
return (null, null);
return false;
var latestTag = latestReleaseJson["tag_name"]?.ToString();
var releaseUrl = latestReleaseJson["html_url"]?.ToString();
tag = latestReleaseJson["tag_name"]?.ToString();
url = latestReleaseJson["html_url"]?.ToString();
return (latestTag, releaseUrl);
return true;
#endif
}

View File

@@ -79,23 +79,36 @@ namespace MPF.Frontend.Tools
/// Process common arguments for all functionality
/// </summary>
/// <returns>True if all arguments pass, false otherwise</returns>
public static (bool, MediaType, RedumpSystem?, string?) ProcessCommonArguments(string[] args)
public static bool ProcessCommonArguments(string[] args, out MediaType mediaType, out RedumpSystem? system, out string? message)
{
// All other use requires at least 3 arguments
if (args.Length < 3)
return (false, MediaType.NONE, null, "Invalid number of arguments");
{
mediaType = MediaType.NONE;
system = null;
message = "Invalid number of arguments";
return false;
}
// Check the MediaType
var mediaType = ToMediaType(args[0].Trim('"'));
mediaType = ToMediaType(args[0].Trim('"'));
if (mediaType == MediaType.NONE)
return (false, MediaType.NONE, null, $"{args[0]} is not a recognized media type");
{
system = null;
message = $"{args[0]} is not a recognized media type";
return false;
}
// Check the RedumpSystem
var knownSystem = Extensions.ToRedumpSystem(args[1].Trim('"'));
if (knownSystem == null)
return (false, MediaType.NONE, null, $"{args[1]} is not a recognized system");
system = Extensions.ToRedumpSystem(args[1].Trim('"'));
if (system == null)
{
message = $"{args[1]} is not a recognized system";
return false;
}
return (true, mediaType, knownSystem, null);
message = null;
return true;
}
/// <summary>

View File

@@ -17,17 +17,17 @@ namespace MPF.Frontend.Tools
/// <param name="options">Options object that determines what to scan</param>
/// <param name="progress">Optional progress callback</param>
/// <returns>Detected copy protection(s) if possible, null on error</returns>
public static async Task<(string?, ProtectionDictionary?)> GetCopyProtection(Drive? drive,
public static async Task<ProtectionDictionary?> GetCopyProtection(Drive? drive,
Frontend.Options options,
IProgress<ProtectionProgress>? progress = null)
{
if (options.ScanForProtection && drive?.Name != null)
{
(var protection, _) = await RunProtectionScanOnPath(drive.Name, options, progress);
return (FormatProtections(protection), protection);
return protection;
}
return ("(CHECK WITH PROTECTIONID)", null);
return null;
}
/// <summary>
@@ -37,7 +37,7 @@ namespace MPF.Frontend.Tools
/// <param name="options">Options object that determines what to scan</param>
/// <param name="progress">Optional progress callback</param>
/// <returns>Set of all detected copy protections with an optional error string</returns>
public static async Task<(ProtectionDictionary?, string?)> RunProtectionScanOnPath(string path,
public static async Task<(ProtectionDictionary, string?)> RunProtectionScanOnPath(string path,
Frontend.Options options,
IProgress<ProtectionProgress>? progress = null)
{
@@ -63,7 +63,7 @@ namespace MPF.Frontend.Tools
// If nothing was returned, return
if (found == null || found.Count == 0)
return (null, null);
return ([], null);
// Filter out any empty protections
found.ClearEmptyKeys();
@@ -73,7 +73,7 @@ namespace MPF.Frontend.Tools
}
catch (Exception ex)
{
return (null, ex.ToString());
return ([], ex.ToString());
}
}
@@ -85,7 +85,9 @@ namespace MPF.Frontend.Tools
public static string? FormatProtections(ProtectionDictionary? protections)
{
// If the filtered list is empty in some way, return
if (protections == null || !protections.Any())
if (protections == null)
return "(CHECK WITH PROTECTIONID)";
else if (protections.Count == 0)
return "None found [OMIT FROM SUBMISSION]";
// Get an ordered list of distinct found protections

View File

@@ -118,7 +118,8 @@ namespace MPF.Frontend.Tools
if (system.SupportsCopyProtectionScans())
{
resultProgress?.Report(ResultEventArgs.Success("Running copy protection scan... this might take a while!"));
var (protectionString, protections) = await ProtectionTool.GetCopyProtection(drive, options, protectionProgress);
var protections = await ProtectionTool.GetCopyProtection(drive, options, protectionProgress);
var protectionString = ProtectionTool.FormatProtections(protections);
info.CopyProtection!.Protection += protectionString;
info.CopyProtection.FullProtections = ReformatProtectionDictionary(protections);

View File

@@ -773,15 +773,13 @@ namespace MPF.Frontend.ViewModels
/// <summary>
/// Check for available updates
/// </summary>
public (bool, string, string?) CheckForUpdates()
public void CheckForUpdates(out bool different, out string message, out string? url)
{
(bool different, string message, var url) = FrontendTool.CheckForNewVersion();
FrontendTool.CheckForNewVersion(out different, out message, out url);
SecretLogLn(message);
if (url == null)
message = "An exception occurred while checking for versions, please try again later. See the log window for more details.";
return (different, message, url);
}
/// <summary>

View File

@@ -237,7 +237,7 @@ namespace MPF.UI.Windows
/// <param name="showIfSame">True to show the box even if it's the same, false to only show if it's different</param>
public void CheckForUpdates(bool showIfSame)
{
(bool different, string message, var url) = MainViewModel.CheckForUpdates();
MainViewModel.CheckForUpdates(out bool different, out string message, out var url);
// If we have a new version, put it in the clipboard
if (different && !string.IsNullOrEmpty(url))