Skip to content

Commit

Permalink
修复几个Bug
Browse files Browse the repository at this point in the history
  • Loading branch information
YangSpring114 committed Feb 9, 2024
1 parent 9dc7a9e commit 7230ed5
Show file tree
Hide file tree
Showing 14 changed files with 65 additions and 62 deletions.
18 changes: 17 additions & 1 deletion MinecraftLaunch.Test/Program.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,28 @@
using MinecraftLaunch.Components.Launcher;
using MinecraftLaunch;
using MinecraftLaunch.Components.Launcher;
using MinecraftLaunch.Components.Resolver;
using MinecraftLaunch.Classes.Models.Launch;
using MinecraftLaunch.Components.Authenticator;
using MinecraftLaunch.Components.Fetcher;
using MinecraftLaunch.Components.Installer;
using MinecraftLaunch.Extensions;

MirrorDownloadManager.IsUseMirrorDownloadSource = true;

var account = new OfflineAuthenticator("Yang114").Authenticate();
var resolver = new GameResolver("C:\\Users\\w\\Desktop\\总整包\\MC\\mc启动器\\LauncherX\\.minecraft");

var installer = new VanlliaInstaller(resolver, "1.19.4", MirrorDownloadManager.Bmcl);
installer.ProgressChanged += (_, args) => {
Console.WriteLine($"{args.ProgressStatus} - {args.Progress * 100:0.00}%");
};

installer.Completed += (_, _) => {
Console.WriteLine("Completed!");
};

await installer.InstallAsync();

var config = new LaunchConfig {
Account = account,
IsEnableIndependencyCore = true,
Expand Down
2 changes: 0 additions & 2 deletions MinecraftLaunch/Classes/Interfaces/IInstaller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ namespace MinecraftLaunch.Classes.Interfaces;
public interface IInstaller {
ValueTask<bool> InstallAsync();

void ReportProgress(double progress, string progressStatus, TaskStatus status);

event EventHandler<EventArgs> Completed;

event EventHandler<ProgressChangedEventArgs> ProgressChanged;
Expand Down
4 changes: 1 addition & 3 deletions MinecraftLaunch/Classes/Models/Download/DownloadRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ public sealed record DownloadRequest {

public required string Url { get; init; }

public required string Name { get; init; }

public required string Path { get; init; }
public required FileInfo FileInfo { get; set; }

public bool IsPartialContentSupported { get; set; }
}
15 changes: 7 additions & 8 deletions MinecraftLaunch/Components/Downloader/BatchDownloader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,8 +132,8 @@ public async ValueTask<bool> DownloadAsync() {

// Clean incomplete files
foreach (var item in _downloadItems) {
if (!item.IsCompleted && File.Exists(Path.Combine(item.Path, item.Name))) {
File.Delete(Path.Combine(item.Path, item.Name));
if (!item.IsCompleted && item.FileInfo.Exists) {
item.FileInfo.Delete();
}
}

Expand Down Expand Up @@ -174,13 +174,12 @@ private async ValueTask<bool> DownloadItemAsync(DownloadRequest item, int retryT
}

// Make sure directory exists
if (Directory.Exists(item.Path)) {
Directory.CreateDirectory(item.Path);
if (!item.FileInfo.Directory.Exists) {
item.FileInfo.Directory.Create();
}

var filePath = Path.Combine(item.Path, item.Name);
if (!File.Exists(filePath)) {
using (File.Create(filePath)) { }
if (!item.FileInfo.Exists) {
using var r = item.FileInfo.Create();
}

byte[] buffer = _bufferPool.Rent(BUFFER_SIZE);
Expand Down Expand Up @@ -220,7 +219,7 @@ private async ValueTask<bool> DownloadItemAsync(DownloadRequest item, int retryT
response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, _userCts.Token);

await using var httpStream = await response.Content.ReadAsStreamAsync();
await using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Write, FileShare.Write);
await using var fileStream = new FileStream(item.FileInfo.FullName, FileMode.Open, FileAccess.Write, FileShare.Write);
fileStream.Position = chunkStart;

int bytesRead;
Expand Down
19 changes: 6 additions & 13 deletions MinecraftLaunch/Components/Fetcher/ModrinthFetcher.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
using MinecraftLaunch.Classes.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using Flurl.Http;
using System.Text;
using System.Threading.Tasks;
using Flurl.Http;
using MinecraftLaunch.Classes.Models.Download;
using MinecraftLaunch.Extensions;
using System.Text.Json;
using System.Text.Json.Nodes;
using MinecraftLaunch.Classes.Enums;
using MinecraftLaunch.Utilities;
using MinecraftLaunch.Extensions;
using MinecraftLaunch.Classes.Enums;
using MinecraftLaunch.Classes.Interfaces;
using MinecraftLaunch.Classes.Models.Download;

namespace MinecraftLaunch.Components.Fetcher;
public sealed class ModrinthFetcher : IFetcher<IEnumerable<ModrinthResourceEntry>> {
Expand All @@ -29,8 +24,7 @@ public async ValueTask<IEnumerable<ModrinthResourceEntry>> FetchAsync() {
public async ValueTask<IEnumerable<ModrinthResourceEntry>> SearchResourcesAsync(
string searchFilter,
string version = default,
ModrinthResourceType? resourceType = ModrinthResourceType.Mod)
{
ModrinthResourceType? resourceType = ModrinthResourceType.Mod) {
var stringBuilder = new StringBuilder(_api);
stringBuilder.Append($"search?query={searchFilter}");

Expand All @@ -54,7 +48,6 @@ public async ValueTask<IEnumerable<ModrinthResourceEntry>> SearchResourcesAsync(
}

var jNode = (await stringBuilder.ToString().GetStringAsync()).AsNode();

return jNode?.Select("hits")?.GetEnumerable()
.Deserialize<IEnumerable<ModrinthResourceEntry>>(JsonConverterUtil.DefaultJsonOptions);
}
Expand Down
4 changes: 2 additions & 2 deletions MinecraftLaunch/Components/Installer/ForgeInstaller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public override async ValueTask<bool> InstallAsync() {
string packagePath = Path.Combine(Path.GetTempPath(),
Path.GetFileName(packageUrl));

var request = packageUrl.ToDownloadRequest(packagePath);
var request = packageUrl.ToDownloadRequest(packagePath.ToFileInfo());
await request.DownloadAsync(x => {
ReportProgress(x.ToPercentage().ToPercentage(0.0d, 0.15d),
"Downloading Forge installation package",
Expand All @@ -43,7 +43,7 @@ await request.DownloadAsync(x => {
* Parse package
*/
ReportProgress(0.15d, "Start parse package", TaskStatus.Created);
var packageArchive = ZipFile.OpenRead(request.Path);
var packageArchive = ZipFile.OpenRead(request.FileInfo.FullName);
var installProfile = packageArchive.GetEntry("install_profile.json")
.ReadAsString()
.AsNode();
Expand Down
6 changes: 5 additions & 1 deletion MinecraftLaunch/Components/Installer/InstallerBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@ public abstract class InstallerBase : IInstaller {

public abstract ValueTask<bool> InstallAsync();

public virtual void ReportProgress(double progress, string progressStatus, TaskStatus status) {
public void ReportCompleted() {
Completed?.Invoke(this, EventArgs.Empty);
}

internal virtual void ReportProgress(double progress, string progressStatus, TaskStatus status) {
ProgressChanged?.Invoke(this, new(status, progress, progressStatus));
}
}
14 changes: 7 additions & 7 deletions MinecraftLaunch/Components/Installer/VanlliaInstaller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ namespace MinecraftLaunch.Components.Installer;
/// </summary>
public sealed class VanlliaInstaller(IGameResolver gameFoloder, string gameId, MirrorDownloadSource source = default) : InstallerBase {
private readonly string _gameId = gameId;
private ResourceChecker _resourceChecker;
private readonly MirrorDownloadSource _source = source;
private readonly IGameResolver _gameResolver = gameFoloder;

Expand All @@ -39,7 +38,7 @@ public override async ValueTask<bool> InstallAsync() {
var versionJsonFile = Path.Combine(_gameResolver.Root.FullName, "versions", _gameId,
$"{_gameId}.json").ToFileInfo();

if (!versionJsonFile.Directory.Exists) {
if (versionJsonFile.Directory is { Exists: false }) {
versionJsonFile.Directory.Create();
}

Expand All @@ -50,10 +49,10 @@ await File.WriteAllTextAsync(versionJsonFile.FullName,
* Download dependent resources
*/
ReportProgress(0.45d, "Start downloading dependent resources", TaskStatus.WaitingToRun);
_resourceChecker = new(_gameResolver.GetGameEntity(_gameId));
await _resourceChecker.CheckAsync();
ResourceChecker resourceChecker = new(_gameResolver.GetGameEntity(_gameId));
await resourceChecker.CheckAsync();

await _resourceChecker.MissingResources.DownloadResourceEntrysAsync(_source,
await resourceChecker.MissingResources.DownloadResourceEntrysAsync(_source,
x => {
ReportProgress(x.ToPercentage().ToPercentage(0.45d, 0.95d),
$"Downloading dependent resources:{x.CompletedCount}/{x.TotalCount}",
Expand All @@ -62,15 +61,16 @@ await _resourceChecker.MissingResources.DownloadResourceEntrysAsync(_source,


ReportProgress(1.0d, "Installation is complete", TaskStatus.Canceled);
ReportCompleted();
return true;
}

public static async ValueTask<IEnumerable<VersionManifestEntry>> EnumerableGameCoreAsync(MirrorDownloadSource source = default) {
string url = string.Empty;
string url;
if (MirrorDownloadManager.IsUseMirrorDownloadSource && source is not null) {
url = source.VersionManifestUrl;
} else {
url = "http://launchermeta.mojang.com/mc/game/version_manifest.json";
url = "https://launchermeta.mojang.com/mc/game/version_manifest.json";
}

var node = (await url.GetStringAsync())
Expand Down
28 changes: 14 additions & 14 deletions MinecraftLaunch/Components/Resolver/ModResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,21 +132,21 @@ private void OfForgeModEntry(ZipArchive zipArchive, ref ModEntry entry) {
private void OfQulitModEntry(ZipArchive zipArchive, ref ModEntry entry) {
var zipEntry = zipArchive.GetEntry("quilt.mod.json");
using var stream = zipEntry.Open();
using (var reader = new StreamReader(stream)) {
try {
var jsonNode = reader.ReadToEnd().AsNode();
jsonNode = jsonNode["quilt_loader"]["metadata"];
using var reader = new StreamReader(stream);

try {
var jsonNode = reader.ReadToEnd().AsNode();
jsonNode = jsonNode.Select("quilt_loader").Select("metadata");

entry.DisplayName = jsonNode?.GetString("name");
entry.Version = jsonNode?.GetString("version");
entry.Description = jsonNode?.GetString("description");
entry.Authors = jsonNode["authors"]
.GetEnumerable<string>()
.ToImmutableArray();
}
catch (Exception) {
entry.IsError = true;
}
entry.DisplayName = jsonNode?.GetString("name");
entry.Version = jsonNode?.GetString("version");
entry.Description = jsonNode?.GetString("description");
entry.Authors = jsonNode["authors"]
.GetEnumerable<string>()
.ToImmutableArray();
}
catch (Exception) {
entry.IsError = true;
}
}
}
6 changes: 1 addition & 5 deletions MinecraftLaunch/Components/Resolver/TomlResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,7 @@ public TomlResolver(string content) : this() {
public string this[string key] => GetString(key);

public string GetString(string key) {
if (_data.TryGetValue(key, out var value)) {
return value;
}

return null;
return _data.GetValueOrDefault(key);
}

private void Parse(string content) {
Expand Down
3 changes: 1 addition & 2 deletions MinecraftLaunch/Extensions/DownloadEntryExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,10 @@ public static class DownloadEntryExtension {
public static DownloadRequest ToDownloadRequest(this IDownloadEntry entry) {
return new DownloadRequest {
Url = entry.Url,
Path = entry.Path,
Size = entry.Size,
IsCompleted = false,
DownloadedBytes = 0,
Name = Path.GetFileName(entry.Path),
FileInfo = entry.Path.ToFileInfo()
};
}

Expand Down
1 change: 1 addition & 0 deletions MinecraftLaunch/Extensions/DownloadExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ public static ValueTask<bool> DownloadResourceEntryAsync(this
.OfMirrorSource(source)
.ToDownloadRequest(), 1));

Console.WriteLine(downloadEntry.Path);
return DefaultDownloader.DownloadAsync();
}

Expand Down
5 changes: 2 additions & 3 deletions MinecraftLaunch/Extensions/StringExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,12 @@ public static string Replace(this string text, Dictionary<string, string> keyVal
return replacedText;
}

public static DownloadRequest ToDownloadRequest(this string url, string path) {
public static DownloadRequest ToDownloadRequest(this string url, FileInfo path) {
return new DownloadRequest {
Url = url,
Path = path,
FileInfo = path,
IsCompleted = false,
DownloadedBytes = 0,
Name = Path.GetFileName(path),
};
}
}
2 changes: 1 addition & 1 deletion MinecraftLaunch/MinecraftLaunch.csproj
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Version>3.0.0</Version>
<Version>3.0.1</Version>
</PropertyGroup>

<PropertyGroup>
Expand Down

0 comments on commit 7230ed5

Please sign in to comment.