Skip to content

Commit

Permalink
Merge pull request #139 from Corona-Studio/master
Browse files Browse the repository at this point in the history
master to tests
  • Loading branch information
yueyinqiu committed Apr 3, 2024
2 parents f72b442 + b0eceef commit 26aee22
Show file tree
Hide file tree
Showing 12 changed files with 166 additions and 96 deletions.
34 changes: 16 additions & 18 deletions ProjBobcat/ProjBobcat/Class/Helper/DeepJavaSearcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ public static class DeepJavaSearcher
{
public static async IAsyncEnumerable<string> DeepSearch(string drive, string fileName)
{
var result = new HashSet<string>();
ProcessStartInfo psi;
if (OperatingSystem.IsWindows())
psi = new ProcessStartInfo(Constants.WhereCommand)
Expand Down Expand Up @@ -40,34 +39,33 @@ public static async IAsyncEnumerable<string> DeepSearch(string drive, string fil
};

var process = Process.Start(psi);
var isFailed = false;

if (process == null)
yield break;

process.ErrorDataReceived += (_, args) =>
while (!process.HasExited)
{
if (string.IsNullOrEmpty(args.Data)) return;
// ReSharper disable once MethodHasAsyncOverload
var line = process.StandardOutput.ReadLine();

isFailed = true;
};
if (!IsValid(line)) continue;

process.OutputDataReceived += (_, args) =>
{
if (string.IsNullOrEmpty(args.Data)) return;
if (File.Exists(args.Data))
result.Add(args.Data);
};

process.BeginErrorReadLine();
process.BeginOutputReadLine();
yield return line!;
}

await process.WaitForExitAsync();

if (isFailed || process.ExitCode != 0)
yield break;
var lastLine = await process.StandardOutput.ReadLineAsync();

foreach (var path in result) yield return path;
if (IsValid(lastLine))
yield return lastLine!;

yield break;

static bool IsValid(string? line)
{
return !string.IsNullOrEmpty(line) && File.Exists(line);
}
}

public static async IAsyncEnumerable<string> DeepSearch()
Expand Down
57 changes: 24 additions & 33 deletions ProjBobcat/ProjBobcat/Class/Helper/DownloadHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,19 +72,18 @@ public static async Task DownloadData(DownloadFile downloadFile, DownloadSetting

var tSpeed = 0d;
var cSpeed = 0;

using var rentMemory = Pool.Rent(DefaultBufferSize);
var lastWrotePos = 0L;

while (true)
{
sw.Restart();
var bytesRead = await stream.ReadAsync(rentMemory.Memory, cts.Token);
await stream.CopyToAsync(outputStream, cts.Token);
var bytesRead = outputStream.Position - lastWrotePos;
lastWrotePos = outputStream.Position;
sw.Stop();

if (bytesRead == 0) break;

await outputStream.WriteAsync(rentMemory.Memory[..bytesRead], cts.Token);

downloadedBytesCount += bytesRead;

var elapsedTime = sw.Elapsed.TotalSeconds == 0 ? 1 : sw.Elapsed.TotalSeconds;
Expand Down Expand Up @@ -154,33 +153,26 @@ public static string AutoFormatSpeedString(double speedInBytePerSecond)
public static (double Speed, SizeUnit Unit) AutoFormatSpeed(double transferSpeed)
{
const double baseNum = 1024;
const double mbNum = baseNum * baseNum;
const double gbNum = baseNum * mbNum;
const double tbNum = baseNum * gbNum;

// Auto choose the unit
var unit = SizeUnit.B;

if (transferSpeed > baseNum)
var unit = transferSpeed switch
{
unit = SizeUnit.Kb;
if (transferSpeed > Math.Pow(baseNum, 2))
{
unit = SizeUnit.Mb;
if (transferSpeed > Math.Pow(baseNum, 3))
{
unit = SizeUnit.Gb;
if (transferSpeed > Math.Pow(baseNum, 4))
{
unit = SizeUnit.Tb;
}
}
}
}
>= tbNum => SizeUnit.Tb,
>= gbNum => SizeUnit.Gb,
>= mbNum => SizeUnit.Mb,
>= baseNum => SizeUnit.Kb,
_ => SizeUnit.B
};

var convertedSpeed = unit switch
{
SizeUnit.Kb => transferSpeed / baseNum,
SizeUnit.Mb => transferSpeed / Math.Pow(baseNum, 2),
SizeUnit.Gb => transferSpeed / Math.Pow(baseNum, 3),
SizeUnit.Tb => transferSpeed / Math.Pow(baseNum, 4),
SizeUnit.Mb => transferSpeed / mbNum,
SizeUnit.Gb => transferSpeed / gbNum,
SizeUnit.Tb => transferSpeed / tbNum,
_ => transferSpeed
};

Expand Down Expand Up @@ -237,8 +229,6 @@ public static Task AdvancedDownloadFile(DownloadFile df, DownloadSettings downlo

#region 分片下载

static readonly MemoryPool<byte> Pool = MemoryPool<byte>.Shared;

/// <summary>
/// 分片下载方法(异步)
/// </summary>
Expand Down Expand Up @@ -379,21 +369,23 @@ public static Task AdvancedDownloadFile(DownloadFile df, DownloadSettings downlo
await using var stream = await res.Content.ReadAsStreamAsync(cts.Token);
await using var fileToWriteTo = File.Create(t.Item2.TempFileName);
using var rentMemory = Pool.Rent(DefaultBufferSize);
var sw = new Stopwatch();
var lastWrotePos = 0L;
while (true)
{
sw.Restart();
var bytesRead = await stream.ReadAsync(rentMemory.Memory, cts.Token);
await stream.CopyToAsync(fileToWriteTo, cts.Token);
var bytesRead = fileToWriteTo.Position - lastWrotePos;
lastWrotePos = fileToWriteTo.Position;
sw.Stop();
if (bytesRead == 0)
break;
await fileToWriteTo.WriteAsync(rentMemory.Memory[..bytesRead], cts.Token);
Interlocked.Add(ref downloadedBytesCount, bytesRead);
var elapsedTime = Math.Ceiling(sw.Elapsed.TotalSeconds);
Expand Down Expand Up @@ -495,7 +487,6 @@ await using (var outputStream = File.Create(filePath))

downloadFile.RetryCount++;
exceptions.Add(ex);
// downloadFile.OnCompleted(false, ex, 0);
}
}

Expand Down
15 changes: 14 additions & 1 deletion ProjBobcat/ProjBobcat/Class/Helper/GamePathHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,20 @@ public static string GetGamePath(string id)
/// <returns></returns>
public static string GetGameJsonPath(string rootPath, string id)
{
return Path.Combine(rootPath, "versions", id, $"{id}.json");
var versions = Path.Combine(rootPath, "versions", id);

foreach (var file in Directory.EnumerateFiles(versions, "*.json"))
{
var name = Path.GetFileNameWithoutExtension(file);

if (name.Contains(id, StringComparison.OrdinalIgnoreCase))
return file;

if (id.Contains(name, StringComparison.OrdinalIgnoreCase))
return file;
}

return Path.Combine(versions, $"{id}.json");
}

/// <summary>
Expand Down
6 changes: 4 additions & 2 deletions ProjBobcat/ProjBobcat/Class/Helper/HttpHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace ProjBobcat.Class.Helper;
Expand Down Expand Up @@ -71,7 +72,8 @@ public static partial class HttpHelper
/// <returns>获取到的字符串</returns>
public static async Task<HttpResponseMessage> Get(
string address,
ValueTuple<string, string> auth = default)
ValueTuple<string, string> auth = default,
CancellationToken ct = default)
{
using var req = new HttpRequestMessage(HttpMethod.Get, new Uri(address));

Expand All @@ -83,7 +85,7 @@ public static partial class HttpHelper
!string.IsNullOrEmpty(auth.Item2))
req.Headers.Authorization = new AuthenticationHeaderValue(auth.Item1, auth.Item2);

var res = await Client.SendAsync(req);
var res = await Client.SendAsync(req, ct);
return res;
}

Expand Down
11 changes: 6 additions & 5 deletions ProjBobcat/ProjBobcat/Class/Helper/ModrinthAPIHelper.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading;
using System.Threading.Tasks;
using ProjBobcat.Class.Model.Modrinth;

Expand All @@ -9,9 +10,9 @@ public static class ModrinthAPIHelper
{
const string BaseUrl = "https://api.modrinth.com/v2";

static async Task<HttpResponseMessage> Get(string reqUrl)
static async Task<HttpResponseMessage> Get(string reqUrl, CancellationToken ct = default)
{
var req = await HttpHelper.Get(reqUrl);
var req = await HttpHelper.Get(reqUrl, ct: ct);
req.EnsureSuccessStatusCode();

return req;
Expand Down Expand Up @@ -40,12 +41,12 @@ static async Task<HttpResponseMessage> Get(string reqUrl)
return resModel;
}

public static async Task<ModrinthProjectInfo?> GetProject(string projectId)
public static async Task<ModrinthProjectInfo?> GetProject(string projectId, CancellationToken ct)
{
var reqUrl = $"{BaseUrl}/project/{projectId}";

using var res = await Get(reqUrl);
var resModel = await res.Content.ReadFromJsonAsync(ModrinthProjectInfoContext.Default.ModrinthProjectInfo);
using var res = await Get(reqUrl, ct);
var resModel = await res.Content.ReadFromJsonAsync(ModrinthProjectInfoContext.Default.ModrinthProjectInfo, ct);

return resModel;
}
Expand Down
18 changes: 8 additions & 10 deletions ProjBobcat/ProjBobcat/Class/Helper/SystemInfoHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,32 +71,30 @@ public static bool IsRunningUnderTranslation()
[SupportedOSPlatform(nameof(OSPlatform.Linux))]
public static async IAsyncEnumerable<string> FindJava(bool fullSearch = false)
{
var result = new HashSet<string>();
var searched = new HashSet<string>();

if (fullSearch)
await foreach (var path in DeepJavaSearcher.DeepSearch())
result.Add(path);
if (searched.Add(path)) yield return path;

if (OperatingSystem.IsWindows())
foreach (var path in Platforms.Windows.SystemInfoHelper.FindJavaWindows())
result.Add(path);
if (searched.Add(path)) yield return path;

if (OperatingSystem.IsMacOS())
foreach (var path in Platforms.MacOS.SystemInfoHelper.FindJavaMacOS())
result.Add(path);
if (searched.Add(path)) yield return path;

if (OperatingSystem.IsLinux())
foreach(var path in Platforms.Linux.SystemInfoHelper.FindJavaLinux())
result.Add(path);
if (searched.Add(path)) yield return path;

foreach (var path in result)
yield return path;
foreach (var path in FindJavaInOfficialGamePath())
yield return path;
if (searched.Add(path)) yield return path;

var evJava = FindJavaUsingEnvironmentVariable();

if (!string.IsNullOrEmpty(evJava))
if (!string.IsNullOrEmpty(evJava) && searched.Add(evJava))
yield return Path.Combine(evJava, Constants.JavaExecutablePath);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public class VersionInfo

[JsonPropertyName("assets")] public string? Assets { get; set; }

[JsonPropertyName("logging")] public JsonElement Logging { get; set; }
[JsonPropertyName("logging")] public JsonElement? Logging { get; set; }

[JsonPropertyName("libraries")] public ForgeLibraries[] Libraries { get; set; } = [];
}
Expand Down Expand Up @@ -107,4 +107,4 @@ partial class LegacyForgeInstallVersionInfoContext : JsonSerializerContext
[JsonSerializable(typeof(LegacyForgeInstallProfile))]
partial class LegacyForgeInstallProfileContext : JsonSerializerContext
{
}
}
2 changes: 2 additions & 0 deletions ProjBobcat/ProjBobcat/Class/Model/VersionInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ public class VersionInfo

public required string DirName { get; init; }

public required string GameBaseVersion { get; init; }

public JavaVersionModel? JavaVersion { get; set; }

public required string MainClass { get; set; }
Expand Down
5 changes: 5 additions & 0 deletions ProjBobcat/ProjBobcat/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ public static class Constants
? Windows.JavaExecutableExtension
: UnixKind.JavaExecutableExtension;

public static string JavaConsoleExecutableExtension => OperatingSystem.IsWindows()
? Windows.JavaConsoleExecutable
: UnixKind.JavaExecutable;

public static string JavaExecutablePath => RuntimeInformation.RuntimeIdentifier switch
{
_ when RuntimeInformation.IsOSPlatform(OSPlatform.Windows) => Windows.JavaExecutablePath,
Expand All @@ -34,6 +38,7 @@ static class Windows
{
public const string WhereCommand = "where";
public const string JavaExecutable = "javaw.exe";
public const string JavaConsoleExecutable = "java.exe";
public const string JavaExecutablePath = $"bin\\{JavaExecutable}";
public const string JavaExecutableExtension = "exe";
public const string OsSymbol = "windows";
Expand Down
Loading

0 comments on commit 26aee22

Please sign in to comment.