diff --git a/.gitmodules b/.gitmodules index d9956e7..a1b6c01 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,3 @@ [submodule "Hi3Helper.Plugin.Core"] path = Hi3Helper.Plugin.Core url = https://github.com/CollapseLauncher/Hi3Helper.Plugin.Core -[submodule "SevenZipExtractor"] - path = SevenZipExtractor - url = https://github.com/CollapseLauncher/SevenZipExtractor diff --git a/CompileAOTAndShip.bat b/CompileAOTAndShip.bat index d12928a..abed679 100644 --- a/CompileAOTAndShip.bat +++ b/CompileAOTAndShip.bat @@ -87,6 +87,8 @@ dotnet restore --runtime win-x64 ..\Hi3Helper.Plugin.DNA.sln || goto :Error dotnet clean --configuration %configuration% --runtime win-x64 ..\Hi3Helper.Plugin.DNA.sln || goto :Error dotnet publish --configuration %configuration% --runtime win-x64 /p:PublishProfile=%publishProfile% -o "%outputDirPath%" || goto :Error +xcopy "..\Lib" "%outputDirPath%\Lib" /E /I /Y /Q || goto :Error + :RemovePDBIfNotDebug if "%_isRemoveSymbol%" == "true" ( del "%outputDirPath%\*.pdb" || goto :Error diff --git a/Hi3Helper.Plugin.Core b/Hi3Helper.Plugin.Core index 0b46a37..3833307 160000 --- a/Hi3Helper.Plugin.Core +++ b/Hi3Helper.Plugin.Core @@ -1 +1 @@ -Subproject commit 0b46a3707793a3660490ca68039f075fc50a1419 +Subproject commit 3833307be117daf7699a099b892ddebfa0c1049b diff --git a/Hi3Helper.Plugin.DNA.sln b/Hi3Helper.Plugin.DNA.sln index 16c9b04..3ad1463 100644 --- a/Hi3Helper.Plugin.DNA.sln +++ b/Hi3Helper.Plugin.DNA.sln @@ -1,7 +1,7 @@  Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.13.35931.197 +# Visual Studio Version 18 +VisualStudioVersion = 18.12.12405.243 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Hi3Helper.Plugin.DNA", "Hi3Helper.Plugin.DNA\Hi3Helper.Plugin.DNA.csproj", "{BA302F46-E800-4F4F-B8DA-29939160448D}" EndProject @@ -9,8 +9,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Hi3Helper.Plugin.Core", "Hi EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PluginTest", "Hi3Helper.Plugin.Core\PluginTest\PluginTest.csproj", "{9E58C55F-9D8C-F9CB-F23A-11E336C9D51D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SevenZipExtractor", "SevenZipExtractor\SevenZipExtractor\SevenZipExtractor.csproj", "{672D4FD7-79D4-4DCD-319A-3F59CC670261}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 @@ -43,14 +41,6 @@ Global {9E58C55F-9D8C-F9CB-F23A-11E336C9D51D}.Release|x64.Build.0 = Release|x64 {9E58C55F-9D8C-F9CB-F23A-11E336C9D51D}.ReleaseNoReflection|x64.ActiveCfg = ReleaseNoReflection|x64 {9E58C55F-9D8C-F9CB-F23A-11E336C9D51D}.ReleaseNoReflection|x64.Build.0 = ReleaseNoReflection|x64 - {672D4FD7-79D4-4DCD-319A-3F59CC670261}.Debug|x64.ActiveCfg = Debug|x64 - {672D4FD7-79D4-4DCD-319A-3F59CC670261}.Debug|x64.Build.0 = Debug|x64 - {672D4FD7-79D4-4DCD-319A-3F59CC670261}.DebugNoReflection|x64.ActiveCfg = Debug|x64 - {672D4FD7-79D4-4DCD-319A-3F59CC670261}.DebugNoReflection|x64.Build.0 = Debug|x64 - {672D4FD7-79D4-4DCD-319A-3F59CC670261}.Release|x64.ActiveCfg = Release|x64 - {672D4FD7-79D4-4DCD-319A-3F59CC670261}.Release|x64.Build.0 = Release|x64 - {672D4FD7-79D4-4DCD-319A-3F59CC670261}.ReleaseNoReflection|x64.ActiveCfg = Release|x64 - {672D4FD7-79D4-4DCD-319A-3F59CC670261}.ReleaseNoReflection|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Hi3Helper.Plugin.DNA.slnx b/Hi3Helper.Plugin.DNA.slnx index 19d3c22..69e5d13 100644 --- a/Hi3Helper.Plugin.DNA.slnx +++ b/Hi3Helper.Plugin.DNA.slnx @@ -11,7 +11,4 @@ - - - diff --git a/Hi3Helper.Plugin.DNA/Hi3Helper.Plugin.DNA.csproj b/Hi3Helper.Plugin.DNA/Hi3Helper.Plugin.DNA.csproj index d85f53c..2da04d5 100644 --- a/Hi3Helper.Plugin.DNA/Hi3Helper.Plugin.DNA.csproj +++ b/Hi3Helper.Plugin.DNA/Hi3Helper.Plugin.DNA.csproj @@ -18,14 +18,13 @@ Collapse Launcher Team $(Company). neon-nyan, Cry0, bagusnl, shatyuka, gablm. Copyright 2022-2025 $(Company) - 0.6.2 + 0.7.0 icon.ico Debug;Release;DebugNoReflection;ReleaseNoReflection - diff --git a/Hi3Helper.Plugin.DNA/Management/Api/Classes/Assets/DNAApiResponseHdiffInfo.cs b/Hi3Helper.Plugin.DNA/Management/Api/Classes/Assets/DNAApiResponseHdiffInfo.cs new file mode 100644 index 0000000..0ec31cb --- /dev/null +++ b/Hi3Helper.Plugin.DNA/Management/Api/Classes/Assets/DNAApiResponseHdiffInfo.cs @@ -0,0 +1,26 @@ +// ReSharper disable InconsistentNaming + +using System.Text.Json.Serialization; + +namespace Hi3Helper.Plugin.DNA.Management.Api; + +public class DNAApiResponseHdiffInfo +{ + [JsonPropertyName("hdiff_file")] + public DNAApiResponseHdiffFile? HdiffFile { get; set; } = null!; + + [JsonPropertyName("new_size")] + public long? NewSize { get; set; } = null!; +} + +public class DNAApiResponseHdiffFile +{ + [JsonPropertyName("name")] + public string? Name { get; set; } = null!; + + [JsonPropertyName("md5")] + public string? MD5 { get; set; } = null!; + + [JsonPropertyName("size")] + public long? Size { get; set; } = null!; +} \ No newline at end of file diff --git a/Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponsePatches.cs b/Hi3Helper.Plugin.DNA/Management/Api/Classes/Assets/DNAApiResponsePatches.cs similarity index 100% rename from Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponsePatches.cs rename to Hi3Helper.Plugin.DNA/Management/Api/Classes/Assets/DNAApiResponsePatches.cs diff --git a/Hi3Helper.Plugin.DNA/Management/Api/Classes/Assets/DNAApiResponseVersionManifest.cs b/Hi3Helper.Plugin.DNA/Management/Api/Classes/Assets/DNAApiResponseVersionManifest.cs new file mode 100644 index 0000000..00fa182 --- /dev/null +++ b/Hi3Helper.Plugin.DNA/Management/Api/Classes/Assets/DNAApiResponseVersionManifest.cs @@ -0,0 +1,18 @@ +// ReSharper disable InconsistentNaming + +using System.Text.Json.Serialization; + +namespace Hi3Helper.Plugin.DNA.Management.Api; + +public class DNAApiResponseVersionManifest +{ + [JsonPropertyName("latest_version")] + public string? LatestVersion { get; set; } = null!; + + [JsonPropertyName("latest_version_number")] + public string? LatestVersionNumber { get; set; } = null!; + + [JsonPropertyName("min_supported_version")] + public string? MinSupportedVersion { get; set; } = null!; +} + diff --git a/Hi3Helper.Plugin.DNA/Management/Api/Classes/DNAApiDetails.cs b/Hi3Helper.Plugin.DNA/Management/Api/Classes/DNAApiDetails.cs new file mode 100644 index 0000000..4f103b9 --- /dev/null +++ b/Hi3Helper.Plugin.DNA/Management/Api/Classes/DNAApiDetails.cs @@ -0,0 +1,73 @@ +using Hi3Helper.Plugin.DNA.Utility; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Hi3Helper.Plugin.DNA.Management.Api; + +public class DNAApiDetails +{ + public List BaseUrls { get; init; } = null!; + + public string BaseUrl { + get + { + int index = (int)Math.Floor((DateTime.Now.Day - 1) / 8.0); + if (index >= BaseUrls.Count) return BaseUrls.First(); + + return BaseUrls[index]; + } + } + + public string Region { get; init; } = null!; + public string RegionLong { get; init; } = null!; + public string Tag { get; init; } = null!; + + #region URL Formatting Methods + + #region Asset URLs + public string GetVersionManifestUrl() => $"{BaseUrl}/Packages/{Region}/WindowsNoEditor/{Tag}/VersionManifest.json "; + + protected string GetDiffTag(string? currentVersion, string latestVersion) => + currentVersion == null ? $"full_{latestVersion}" : $"v{currentVersion}_to_v{latestVersion}"; + + public string GetHdiffInfoUrl(string versionNumber, string latestVersion, string? currentVersion = null) + { + var diffTag = GetDiffTag(currentVersion, latestVersion); + + return $"{BaseUrl}/Packages/{Region}/WindowsNoEditor/{Tag}/{versionNumber}/{latestVersion}/{diffTag}/HPatchDiffMd5.json"; + } + + public string GetHdiffFileUrl(string versionNumber, string latestVersion, string fileName, string? currentVersion = null) + { + var diffTag = GetDiffTag(currentVersion, latestVersion); + + return $"{BaseUrl}/Packages/{Region}/WindowsNoEditor/{Tag}/{versionNumber}/{latestVersion}/{diffTag}/{fileName}"; + } + + public string GetHdiffFileName(string versionNumber, string latestVersion, string? currentVersion = null) + { + var diffTag = GetDiffTag(currentVersion, latestVersion); + + return $"{versionNumber}/{latestVersion}/{diffTag}"; + } + #endregion + + #region Media URLs + public static string GetBackgroundUrl(string versionNumber) => $"https://cdnstatic.yingxiong.com/dna_hd_{versionNumber.Replace(".","_")}/imgs/home/pc/bg.webp"; + + public string GetOverlayUrl() + { + string lang = Region == "CN" ? "chs" : DNAUtility.GetOverlayLangFromLauncherLocale(); + return $"https://cdnstatic.yingxiong.com/dna_hd_1_7/imgs/home/pc/slogan-{lang}.webp"; + } + + public string GetNoticesUrl() => $"{BaseUrl}/OperationLauncherNotice/OperationLauncherNoticeProduction{RegionLong}online.json"; + + public string GetCarouselUrl() => $"{BaseUrl}/OperationLauncherHeadImage/OperationLauncherHeadImageProduction{RegionLong}online.json"; + + public string GetSocialsUrl() => $"{BaseUrl}/OperationLauncherSocialMedia/OperationLauncherSocialMediaProduction{RegionLong}online.json"; + #endregion + + #endregion +} diff --git a/Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponseContext.cs b/Hi3Helper.Plugin.DNA/Management/Api/Classes/DNAApiResponseContext.cs similarity index 76% rename from Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponseContext.cs rename to Hi3Helper.Plugin.DNA/Management/Api/Classes/DNAApiResponseContext.cs index bcdf495..a111268 100644 --- a/Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponseContext.cs +++ b/Hi3Helper.Plugin.DNA/Management/Api/Classes/DNAApiResponseContext.cs @@ -6,5 +6,6 @@ namespace Hi3Helper.Plugin.DNA.Management.Api; [JsonSerializable(typeof(DNAApiResponseNotices))] [JsonSerializable(typeof(DNAApiResponseCarousel))] [JsonSerializable(typeof(DNAApiResponsePatches))] -[JsonSerializable(typeof(DNAApiResponseVersion))] +[JsonSerializable(typeof(DNAApiResponseHdiffInfo))] +[JsonSerializable(typeof(DNAApiResponseVersionManifest))] public partial class DNAApiResponseContext : JsonSerializerContext; diff --git a/Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponseCarousel.cs b/Hi3Helper.Plugin.DNA/Management/Api/Classes/Media/DNAApiResponseCarousel.cs similarity index 100% rename from Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponseCarousel.cs rename to Hi3Helper.Plugin.DNA/Management/Api/Classes/Media/DNAApiResponseCarousel.cs diff --git a/Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponseNotices.cs b/Hi3Helper.Plugin.DNA/Management/Api/Classes/Media/DNAApiResponseNotices.cs similarity index 100% rename from Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponseNotices.cs rename to Hi3Helper.Plugin.DNA/Management/Api/Classes/Media/DNAApiResponseNotices.cs diff --git a/Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponseSocials.cs b/Hi3Helper.Plugin.DNA/Management/Api/Classes/Media/DNAApiResponseSocials.cs similarity index 100% rename from Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponseSocials.cs rename to Hi3Helper.Plugin.DNA/Management/Api/Classes/Media/DNAApiResponseSocials.cs diff --git a/Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponseDetails.cs b/Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponseDetails.cs deleted file mode 100644 index b242eb8..0000000 --- a/Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponseDetails.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Hi3Helper.Plugin.DNA.Management.Api; - -public class DNAApiResponseDetails -{ - public List BaseUrls { get; init; } = null!; - - public string BaseUrl { - get - { - int index = (int)Math.Floor((DateTime.Now.Day - 1) / 8.0); - if (index >= BaseUrls.Count) return BaseUrls.First(); - - return BaseUrls[index]; - } - } - - public string Region { get; init; } = null!; - public string RegionLong { get; init; } = null!; - public string Tag { get; init; } = null!; -} diff --git a/Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponseVersion.cs b/Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponseVersion.cs deleted file mode 100644 index c3c7ce2..0000000 --- a/Hi3Helper.Plugin.DNA/Management/Api/DNAApiResponseVersion.cs +++ /dev/null @@ -1,70 +0,0 @@ -// ReSharper disable InconsistentNaming - -using Hi3Helper.Plugin.DNA.Management.FileStructs; -using System.Collections.Generic; -using System.Linq; -using System.Text.Json.Serialization; - -namespace Hi3Helper.Plugin.DNA.Management.Api; - -public class DNAApiResponseVersion -{ - [JsonPropertyName("GameVersionList")] - public Dictionary GameVersionList { get; set; } = []; - - public DNAFilesVersion ToFile() - { - var ret = new DNAFilesVersion(); - foreach ((var version, var container) in GameVersionList) - { - ret.GameVersionList.Add(version, container.ToFile()); - } - return ret; - } - - [JsonIgnore] - public Dictionary? FilesList - => GameVersionList?.FirstOrDefault().Value.FilesList; -} - -public class DNAApiResponseVersionContainer -{ - [JsonPropertyName("GameVersionList")] - public Dictionary FilesList { get; set; } = []; - - public DNAFilesVersionContainer ToFile() - { - var ret = new DNAFilesVersionContainer(); - foreach ((var version, var file) in FilesList) - { - ret.FilesList.Add(version, file.ToFile()); - } - return ret; - } -} - -public class DNAApiResponseVersionFileInfo -{ - [JsonPropertyName("ZipGameVersion")] - public int Version { get; set; } - - [JsonPropertyName("ZipMd5")] - public string? ChecksumMD5 { get; set; } - - [JsonPropertyName("ZipSize")] - public long Size { get; set; } - - [JsonPropertyName("bIsSDK")] - public string? IsSDK { get; set; } - - public DNAFilesVersionFileInfo ToFile() - { - return new DNAFilesVersionFileInfo - { - Version = Version, - ChecksumMD5 = ChecksumMD5, - Size = Size, - IsSDK = IsSDK == bool.TrueString - }; - } -} diff --git a/Hi3Helper.Plugin.DNA/Management/Api/DNAGlobalLauncherApiMedia.cs b/Hi3Helper.Plugin.DNA/Management/Api/DNAGlobalLauncherApiMedia.cs index a380283..616efca 100644 --- a/Hi3Helper.Plugin.DNA/Management/Api/DNAGlobalLauncherApiMedia.cs +++ b/Hi3Helper.Plugin.DNA/Management/Api/DNAGlobalLauncherApiMedia.cs @@ -1,11 +1,15 @@ using Hi3Helper.Plugin.Core; using Hi3Helper.Plugin.Core.Management.Api; using Hi3Helper.Plugin.Core.Utility; +using Hi3Helper.Plugin.DNA.Management.PresetConfig; using Hi3Helper.Plugin.DNA.Utility; +using Microsoft.Extensions.Logging; +using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Net.Http; using System.Runtime.InteropServices.Marshalling; +using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -14,7 +18,7 @@ namespace Hi3Helper.Plugin.DNA.Management.Api; [GeneratedComClass] -internal partial class DNAGlobalLauncherApiMedia(DNAApiResponseDetails apiResponseDetails, string logoUrl, string backgroundUrl) : LauncherApiMediaBase +internal partial class DNAGlobalLauncherApiMedia(DNAPresetConfig presetConfig) : LauncherApiMediaBase { [field: AllowNull, MaybeNull] protected override HttpClient ApiResponseHttpClient @@ -30,10 +34,10 @@ protected HttpClient ApiDownloadHttpClient set; } - protected override string ApiResponseBaseUrl { get; } = apiResponseDetails.BaseUrl; + private DNAApiDetails ApiDetails { get; } = presetConfig.ApiResponseDetails; - protected string LogoUrl { get; } = logoUrl; - protected string BackgroundUrl { get; } = backgroundUrl; + protected string LogoUrl { get; } = presetConfig.ApiResponseDetails.GetOverlayUrl(); + protected string BackgroundUrl { get; private set; } = presetConfig.DefaultBackgroundUrl; public override unsafe void GetBackgroundEntries(out nint handle, out int count, out bool isDisposable, out bool isAllocated) { @@ -46,14 +50,16 @@ public override unsafe void GetBackgroundEntries(out nint handle, out int count, return; } + SharedStatic.InstanceLogger.LogTrace("[DNAGlobalLauncherApiMedia::GetBackgroundEntries] Background Url is {Url}", BackgroundUrl); + using (ThisInstanceLock.EnterScope()) { - PluginDisposableMemory backgroundEntries = PluginDisposableMemory.Alloc(); + PluginDisposableMemory backgroundEntries = PluginDisposableMemory.Alloc(1); try { ref LauncherPathEntry entry = ref backgroundEntries[0]; - entry.Write(BackgroundUrl, []); + entry.Write(BackgroundUrl, []); isAllocated = true; } @@ -68,7 +74,13 @@ public override unsafe void GetBackgroundEntries(out nint handle, out int count, public override void GetLogoOverlayEntries(out nint handle, out int count, out bool isDisposable, out bool isAllocated) { - if (LogoUrl == null) + isDisposable = false; + handle = nint.Zero; + count = 0; + isAllocated = false; + return; + + /*if (LogoUrl == null) { isDisposable = false; handle = nint.Zero; @@ -77,34 +89,59 @@ public override void GetLogoOverlayEntries(out nint handle, out int count, out b return; } + SharedStatic.InstanceLogger.LogTrace("[DNAGlobalLauncherApiMedia::GetLogoOverlayEntries] Logo Overlay Url is {Url}", LogoUrl); + using (ThisInstanceLock.EnterScope()) { - PluginDisposableMemory logoEntries = PluginDisposableMemory.Alloc(); + PluginDisposableMemory backgroundEntries = PluginDisposableMemory.Alloc(1); try { - ref LauncherPathEntry entry = ref logoEntries[0]; + ref LauncherPathEntry entry = ref backgroundEntries[0]; entry.Write(LogoUrl, []); isAllocated = true; } finally { - isDisposable = logoEntries.IsDisposable == 1; - handle = logoEntries.AsSafePointer(); - count = logoEntries.Length; + isDisposable = backgroundEntries.IsDisposable == 1; + handle = backgroundEntries.AsSafePointer(); + count = backgroundEntries.Length; } - } + }*/ } public override void GetBackgroundFlag(out LauncherBackgroundFlag result) - => result = LauncherBackgroundFlag.TypeIsVideo | LauncherBackgroundFlag.IsSourceFile; + => result = LauncherBackgroundFlag.TypeIsImage | LauncherBackgroundFlag.IsSourceFile; public override void GetLogoFlag(out LauncherBackgroundFlag result) - => result = LauncherBackgroundFlag.TypeIsImage | LauncherBackgroundFlag.IsSourceFile; + => result = LauncherBackgroundFlag.None /* LauncherBackgroundFlag.TypeIsImage | LauncherBackgroundFlag.IsSourceFile */; protected override async Task InitAsync(CancellationToken token) { + try + { + var manifestUrl = ApiDetails.GetVersionManifestUrl(); + SharedStatic.InstanceLogger.LogTrace("[DNAGlobalLauncherApiMedia::InitAsync] Manifest Url is {Url}", manifestUrl); + + using HttpResponseMessage manifestResponse = + await ApiResponseHttpClient.GetAsync(manifestUrl, HttpCompletionOption.ResponseHeadersRead, token); + manifestResponse.EnsureSuccessStatusCode(); + + string jsonResponse = await manifestResponse.Content.ReadAsStringAsync(token); + + var apiResponse = JsonSerializer.Deserialize(jsonResponse, DNAApiResponseContext.Default.DNAApiResponseVersionManifest); + + BackgroundUrl = DNAApiDetails.GetBackgroundUrl(apiResponse!.LatestVersionNumber!); + + SharedStatic.InstanceLogger.LogTrace("[DNAGlobalLauncherApiMedia::InitAsync] Background Url is {Url}", BackgroundUrl); + } + catch (Exception ex) + { + SharedStatic.InstanceLogger.LogTrace("[DNAGlobalLauncherApiMedia::InitAsync] Failed to obtain Background Url. Ex: {Message}", ex.Message); + return -1; + } + return 0; } diff --git a/Hi3Helper.Plugin.DNA/Management/Api/DNAGlobalLauncherApiNews.cs b/Hi3Helper.Plugin.DNA/Management/Api/DNAGlobalLauncherApiNews.cs index be44d7d..5b055a6 100644 --- a/Hi3Helper.Plugin.DNA/Management/Api/DNAGlobalLauncherApiNews.cs +++ b/Hi3Helper.Plugin.DNA/Management/Api/DNAGlobalLauncherApiNews.cs @@ -11,9 +11,10 @@ using System.Threading; using System.Threading.Tasks; using Hi3Helper.Plugin.Core.Management; - -// ReSharper disable InconsistentNaming - +using Hi3Helper.Plugin.DNA.Management.PresetConfig; + +// ReSharper disable InconsistentNaming + #if USELIGHTWEIGHTJSONPARSER using System.IO; #else @@ -23,7 +24,7 @@ namespace Hi3Helper.Plugin.DNA.Management.Api; [GeneratedComClass] -internal partial class DNAGlobalLauncherApiNews(DNAApiResponseDetails apiResponseDetails, string? forceLang = null) : LauncherApiNewsBase +internal partial class DNAGlobalLauncherApiNews(DNAPresetConfig presetConfig, string? forceLang = null) : LauncherApiNewsBase { [field: AllowNull, MaybeNull] protected override HttpClient ApiResponseHttpClient @@ -39,8 +40,7 @@ protected HttpClient ApiDownloadHttpClient set; } - protected override string ApiResponseBaseUrl { get; } = apiResponseDetails.BaseUrl; - protected DNAApiResponseDetails ApiResponseDetails { get; } = apiResponseDetails; + protected DNAApiDetails ApiResponseDetails { get; } = presetConfig.ApiResponseDetails; private DNAApiResponseNotices? NoticesApiResponse { get; set; } @@ -50,24 +50,22 @@ protected HttpClient ApiDownloadHttpClient private string LangCode => forceLang ?? DNAUtility.GetApiLangFromLauncherLocale(); + protected override async Task InitAsync(CancellationToken token) { - using HttpResponseMessage notices = await ApiResponseHttpClient - .GetAsync($"{ApiResponseBaseUrl}/OperationLauncherNotice/OperationLauncherNoticeProduction{ApiResponseDetails.RegionLong}online.json", HttpCompletionOption.ResponseHeadersRead, token); + using HttpResponseMessage notices = await ApiResponseHttpClient.GetAsync(ApiResponseDetails.GetNoticesUrl(), HttpCompletionOption.ResponseHeadersRead, token); notices.EnsureSuccessStatusCode(); string noticesJsonResponse = await notices.Content.ReadAsStringAsync(token); NoticesApiResponse = JsonSerializer.Deserialize(noticesJsonResponse, DNAApiResponseContext.Default.DNAApiResponseNotices); - using HttpResponseMessage carousel = await ApiResponseHttpClient - .GetAsync($"{ApiResponseBaseUrl}/OperationLauncherHeadImage/OperationLauncherHeadImageProduction{ApiResponseDetails.RegionLong}online.json", HttpCompletionOption.ResponseHeadersRead, token); + using HttpResponseMessage carousel = await ApiResponseHttpClient.GetAsync(ApiResponseDetails.GetCarouselUrl(), HttpCompletionOption.ResponseHeadersRead, token); carousel.EnsureSuccessStatusCode(); string carouselJsonResponse = await carousel.Content.ReadAsStringAsync(token); CarouselApiResponse = JsonSerializer.Deserialize(carouselJsonResponse, DNAApiResponseContext.Default.DNAApiResponseCarousel); - using HttpResponseMessage socials = await ApiResponseHttpClient - .GetAsync($"{ApiResponseBaseUrl}/OperationLauncherSocialMedia/OperationLauncherSocialMediaProduction{ApiResponseDetails.RegionLong}online.json", HttpCompletionOption.ResponseHeadersRead, token); + using HttpResponseMessage socials = await ApiResponseHttpClient.GetAsync(ApiResponseDetails.GetSocialsUrl(), HttpCompletionOption.ResponseHeadersRead, token); socials.EnsureSuccessStatusCode(); string socialsJsonResponse = await socials.Content.ReadAsStringAsync(token); diff --git a/Hi3Helper.Plugin.DNA/Management/DNAGameInstaller.Install.cs b/Hi3Helper.Plugin.DNA/Management/DNAGameInstaller.Install.cs index d1957a0..be97349 100644 --- a/Hi3Helper.Plugin.DNA/Management/DNAGameInstaller.Install.cs +++ b/Hi3Helper.Plugin.DNA/Management/DNAGameInstaller.Install.cs @@ -1,16 +1,12 @@ using Hi3Helper.Plugin.Core; using Hi3Helper.Plugin.Core.Management; using Hi3Helper.Plugin.Core.Utility; -using Hi3Helper.Plugin.DNA.Management.Api; using Hi3Helper.Plugin.DNA.Management.FileStructs; using Hi3Helper.Plugin.DNA.Utility; using Microsoft.Extensions.Logging; -using SevenZipExtractor; -using SevenZipExtractor.Event; using System; -using System.Collections.Generic; +using System.Diagnostics; using System.IO; -using System.Linq; using System.Net.Http; using System.Text.Json; using System.Threading; @@ -20,18 +16,18 @@ namespace Hi3Helper.Plugin.DNA.Management; internal partial class DNAGameInstaller : GameInstallerBase { - protected bool _canSkipDeleteZip => File.Exists(Path.Combine(_gamePath!, "@NoDeleteZip")); + protected bool _canSkipDelete => File.Exists(Path.Combine(_gamePath!, "@NoDelete")); protected bool _canSkipVerif => File.Exists(Path.Combine(_gamePath!, "@NoVerification")); - protected bool _canSkipExtract => File.Exists(Path.Combine(_gamePath!, "@NoExtraction")); + protected bool _canSkipPatch => File.Exists(Path.Combine(_gamePath!, "@NoPatch")); protected override async Task StartInstallAsyncInner(InstallProgressDelegate? progressDelegate, InstallProgressStateDelegate? progressStateDelegate, CancellationToken token) { SharedStatic.InstanceLogger.LogInformation("[DNAGameInstaller::StartInstallAsyncInner] Starting installation routine."); - if (_apiVersion is null) + if (HdiffInfo?.HdiffFile is null) { - SharedStatic.InstanceLogger.LogError("[DNAGameInstaller::StartInstallAsyncInner] _apiVersion is null, aborting."); - throw new InvalidOperationException("BaseVersion from API is not initialized."); + SharedStatic.InstanceLogger.LogError("[DNAGameInstaller::StartInstallAsyncInner] File information is null, aborting."); + throw new InvalidOperationException("No information about download package."); } await InitAsync(token).ConfigureAwait(false); @@ -39,135 +35,103 @@ protected override async Task StartInstallAsyncInner(InstallProgressDelegate? pr if (_gamePath is null) { SharedStatic.InstanceLogger.LogError("[DNAGameInstaller::StartInstallAsyncInner] _gamePath is null, aborting."); - throw new InvalidOperationException("Game Path is not initialized."); + throw new InvalidOperationException("Game location was not set before installation."); } - (var missingFiles, var filesToDelete) = VersionUtils.FindMissingFiles(_apiVersion.FilesList, _installVersion?.FilesList, _tempVersion?.FilesList); - - var tempPath = Path.Combine(_gamePath!, "TempPath", "TempGameFiles"); + var tempPath = Path.Combine(_gamePath!, _tempPath); Directory.CreateDirectory(tempPath); - var tempJsonPath = Path.Combine(_gamePath!, "TempPath", _baseVersion); - await WriteVersionJson(tempJsonPath); + var fileSize = HdiffInfo.HdiffFile.Size!.Value; + var hdiffName = HdiffInfo.HdiffFile.Name!; - // 0. Set Initial State - InstallProgress installProgress = new() - { - StateCount = 0, - TotalStateToComplete = missingFiles.Count, - DownloadedCount = GetDownloadedCountAsync(GameInstallerKind.Install, token), - TotalCountToDownload = missingFiles.Count, - DownloadedBytes = await GetGameDownloadedSizeAsyncInner(GameInstallerKind.Install, token), - TotalBytesToDownload = await GetGameSizeAsyncInner(GameInstallerKind.Install, token) - }; + var hdiffUrl = _gameManager!.ApiDetails.GetHdiffFileUrl( + _gameManager!.VersionManifest!.LatestVersionNumber!, + _gameManager!.VersionManifest!.LatestVersion!, + hdiffName, + _gameVersion); + + + var hdiffPath = Path.Combine(tempPath, hdiffName); + + + // Head request for file (optional but launcher does it) + var headRequest = new HttpRequestMessage(HttpMethod.Head, hdiffUrl); + var headResponse = await _downloadHttpClient.SendAsync(headRequest, HttpCompletionOption.ResponseHeadersRead, token); + headResponse.EnsureSuccessStatusCode(); - progressDelegate?.Invoke(in installProgress); - progressStateDelegate?.Invoke(InstallProgressState.Download); + + InstallProgress installProgress = new(); int retries = 0; while (true) { - // 1. File Download - await Parallel.ForEachAsync(missingFiles, new ParallelOptions + // 0. Set Initial State + installProgress = new() { - MaxDegreeOfParallelism = Environment.ProcessorCount, - CancellationToken = token - }, DownloadImpl); + StateCount = 0, + TotalStateToComplete = 1, + DownloadedCount = GetDownloadedCountAsync(GameInstallerKind.Install, token), + TotalCountToDownload = 1, + DownloadedBytes = await GetGameDownloadedSizeAsyncInner(GameInstallerKind.Install, token), + TotalBytesToDownload = await GetGameSizeAsyncInner(GameInstallerKind.Install, token) + }; + progressDelegate?.Invoke(in installProgress); + progressStateDelegate?.Invoke(InstallProgressState.Download); + + // 1. File Download + await DownloadFile(); // 2. File Verification - installProgress.StateCount = 0; - installProgress.DownloadedCount = 0; - installProgress.DownloadedBytes = 0; - progressDelegate?.Invoke(in installProgress); - progressStateDelegate?.Invoke(InstallProgressState.Verify); + await VerifyFile(); - await Parallel.ForEachAsync(missingFiles, new ParallelOptions - { - MaxDegreeOfParallelism = Environment.ProcessorCount, - CancellationToken = token - }, VerifyImpl); + if (installProgress.DownloadedCount == 1) + break; retries++; - if (retries >= 5) - { throw new Exception("Exceeded amount of allowed retries."); - } - - if (filesToDelete.Count == 0) - break; - - progressDelegate?.Invoke(in installProgress); - progressStateDelegate?.Invoke(InstallProgressState.Download); - // TODO: Fix display when file is corrupt } - // 3. File Extraction - installProgress.StateCount = 0; - installProgress.DownloadedCount = 0; - installProgress.DownloadedBytes = 0; - progressDelegate?.Invoke(in installProgress); - progressStateDelegate?.Invoke(InstallProgressState.Install); - - await Parallel.ForEachAsync(missingFiles, new ParallelOptions - { - MaxDegreeOfParallelism = Environment.ProcessorCount / 2 + 1, - CancellationToken = token - }, ExtractImpl); + // 4. Game File Patching + await PatchFiles(); - // 4. File Cleanup - foreach ((var fileName, _) in missingFiles) + // 5. File Cleanup + if (!_canSkipDelete) { - if (_canSkipDeleteZip) break; - - var filePath = Path.Combine(tempPath, fileName); - FileInfo fileInfo = new(filePath); + var fileInfo = new FileInfo(hdiffPath); if (fileInfo.Exists) { fileInfo.Delete(); } - } - // 5. Finalize installation - Write BaseVersion.json - var mainJsonPath = Path.Combine(_gamePath!, _baseVersion); - await WriteVersionJson(mainJsonPath, true); + Directory.Delete(tempPath, true); + } - Directory.Delete(tempPath, true); + // 6. Finalize installation - Write GameVersion.json + var mainJsonPath = Path.Combine(_gamePath!, "DNA Game", _gameVersionName); + await WriteGameVersionJson(mainJsonPath); - _gameManager?.SetCurrentGameVersion(_apiVersion.ToFile()); + _gameManager!.GetApiGameVersion(out GameVersion apiVersion); + _gameManager!.SetCurrentGameVersion(apiVersion); return; #region Subroutine - File Download - async ValueTask DownloadImpl(KeyValuePair file, CancellationToken innerToken) + async Task DownloadFile() { - (string fileName, DNAApiResponseVersionFileInfo fileDetails) = file; - - var filePath = Path.Combine(tempPath, fileName); - FileInfo fileInfo = new(filePath); + FileInfo fileInfo = new(hdiffPath); fileInfo.Directory?.Create(); if (fileInfo.Exists) { fileInfo.IsReadOnly = false; - if (filesToDelete.Contains(fileName)) - { - fileInfo.Delete(); - } } await using FileStream fileStream = fileInfo.Open(FileMode.Append, FileAccess.Write, FileShare.Write); - string assetDownloadUrl = _baseVersionUrl + fileName; - #if DEBUG - SharedStatic.InstanceLogger.LogTrace("Trying to download the asset from URL: {AssetUrl}", assetDownloadUrl); + SharedStatic.InstanceLogger.LogTrace("Trying to download {outputName}", hdiffName); #endif - // Head request for file (optional but launcher does it) - var headRequest = new HttpRequestMessage(HttpMethod.Head, assetDownloadUrl); - var headResponse = await _downloadHttpClient.SendAsync(headRequest, HttpCompletionOption.ResponseHeadersRead, token); - headResponse.EnsureSuccessStatusCode(); - long existingLength = 0; if (fileStream.CanSeek) { @@ -175,35 +139,38 @@ async ValueTask DownloadImpl(KeyValuePair fileStream.Seek(existingLength, SeekOrigin.Begin); } - if (existingLength >= fileDetails.Size) + if (existingLength == fileSize) { -#if DEBUG - SharedStatic.InstanceLogger.LogTrace("Already downloaded asset from URL: {AssetUrl}", assetDownloadUrl); -#endif - Interlocked.Increment(ref installProgress.StateCount); - Interlocked.Increment(ref installProgress.DownloadedCount); - progressDelegate?.Invoke(in installProgress); - progressStateDelegate?.Invoke(InstallProgressState.Download); + SharedStatic.InstanceLogger.LogInformation("Already downloaded all {bytes} bytes of {outputName}", existingLength, hdiffName); return; } +#if DEBUG + if (existingLength >= 0) + { + SharedStatic.InstanceLogger.LogTrace("Already downloaded {bytes} bytes of {outputName}", existingLength, hdiffName); + } +#endif + // Use Retry-able Copy-To Stream task to start the download await using RetryableCopyToStreamTask downloadTask = RetryableCopyToStreamTask .CreateTask((pos, thisCtx) => { // Start from existing file size (or retry position) long startPos = existingLength + pos; + long endPos = fileSize - 1; + return _downloadHttpClient.CreateHttpBridgedStream( - assetDownloadUrl, + hdiffUrl, startPos, - null, + endPos, thisCtx); }, fileStream, new RetryableCopyToStreamTaskOptions { IsDisposeTargetStream = true, - MaxBufferSize = 8 << 10, + MaxBufferSize = 128 << 10, RetryDelaySeconds = 1d }); @@ -212,7 +179,7 @@ await downloadTask.StartTaskAsync(read => { Interlocked.Add(ref installProgress.DownloadedBytes, read); progressDelegate?.Invoke(in installProgress); - }, innerToken); + }, token); Interlocked.Increment(ref installProgress.StateCount); Interlocked.Increment(ref installProgress.DownloadedCount); @@ -220,145 +187,108 @@ await downloadTask.StartTaskAsync(read => progressStateDelegate?.Invoke(InstallProgressState.Download); #if DEBUG - SharedStatic.InstanceLogger.LogTrace("Downloaded asset from URL: {AssetUrl}", assetDownloadUrl); + SharedStatic.InstanceLogger.LogTrace("Downloaded {Segment}", hdiffName); #endif } -#endregion + #endregion #region Subroutine - File Verification - async ValueTask VerifyImpl(KeyValuePair file, CancellationToken innerToken) + + async Task VerifyFile() { if (_canSkipVerif) return; - (string fileName, DNAApiResponseVersionFileInfo fileDetails) = file; - - var filePath = Path.Combine(tempPath, fileName); - FileInfo fileInfo = new(filePath); - fileInfo.Directory?.Create(); - - if (fileInfo.Exists) - { - fileInfo.IsReadOnly = false; - } - - await using FileStream fileStream = fileInfo.Open(new FileStreamOptions - { - Mode = FileMode.Open, - Access = FileAccess.Read, - Share = FileShare.Read, - Options = FileOptions.SequentialScan - }); - - var expectedSize = fileDetails.Size; - var expectedMd5 = fileDetails.ChecksumMD5?.Trim()?.ToLowerInvariant(); + installProgress.StateCount = 0; + installProgress.TotalStateToComplete = 1; + installProgress.DownloadedCount = 0; + installProgress.DownloadedBytes = 0; + progressDelegate?.Invoke(in installProgress); + progressStateDelegate?.Invoke(InstallProgressState.Verify); - var downloadedSize = new FileInfo(filePath).Length; - if (downloadedSize != expectedSize) + using var input = File.OpenRead(hdiffPath); + var fileMd5 = await HashUtils.ComputeMd5HexAsync(input, (o) => { - filesToDelete.Add(fileName); - SharedStatic.InstanceLogger.LogError("[DNAGameInstaller::StartInstallAsyncInner] File size for {fileName} does not match ({downloadedSize} vs {expectedSize}).", - fileName, downloadedSize, expectedSize); - return; - } + Interlocked.Add(ref installProgress.DownloadedBytes, o); + progressDelegate?.Invoke(in installProgress); + }, token); - if (expectedMd5 != null) + if (fileMd5 != null && fileMd5 != HdiffInfo.HdiffFile.MD5) { - var callback = (long e) => - { - Interlocked.Add(ref installProgress.DownloadedBytes, e); - progressDelegate?.Invoke(in installProgress); - progressStateDelegate?.Invoke(InstallProgressState.Verify); - }; - - var fs = File.OpenRead(filePath); - var checksumMd5 = (await HashUtils.ComputeMd5HexAsync(fs, callback, token))?.Trim()?.ToLowerInvariant(); - await fs.DisposeAsync(); - - if (checksumMd5 != expectedMd5) - { - filesToDelete.Add(fileName); - SharedStatic.InstanceLogger.LogError("[DNAGameInstaller::StartInstallAsyncInner] MD5 for {fileName} does not match. ({checksumMd5} vs {expectedMd5})", - fileName, checksumMd5, expectedMd5); - return; - } + throw new Exception("File hash doesn't match VersionManifest"); } -#if DEBUG - SharedStatic.InstanceLogger.LogTrace("[DNAGameInstaller::StartInstallAsyncInner] {file} has been downloaded and checksum matches or is null.", fileName); -#endif - filesToDelete.Remove(fileName); + Interlocked.Increment(ref installProgress.DownloadedCount); Interlocked.Increment(ref installProgress.StateCount); progressDelegate?.Invoke(in installProgress); - progressStateDelegate?.Invoke(InstallProgressState.Verify); + progressStateDelegate?.Invoke(InstallProgressState.Verify); } #endregion - #region Subroutine - File Extraction - async ValueTask ExtractImpl(KeyValuePair file, CancellationToken innerToken) + #region Subroutine - Patch Files + async Task PatchFiles() { - if (_canSkipExtract) return; + if (_canSkipPatch) return; - (string fileName, DNAApiResponseVersionFileInfo fileDetails) = file; + var finalSize = HdiffInfo.NewSize!.Value; - var filePath = Path.Combine(tempPath, fileName); - FileInfo fileInfo = new(filePath); + installProgress.StateCount = 0; + installProgress.TotalStateToComplete = 1; + installProgress.DownloadedCount = 0; + installProgress.DownloadedBytes = 0; + installProgress.TotalBytesToDownload = finalSize; + progressDelegate?.Invoke(in installProgress); + progressStateDelegate?.Invoke(InstallProgressState.Install); + + var pluginPath = DNAUtility.FindPluginPath()!; + var hpatchzPath = Path.Combine(pluginPath, "Lib", "hpatchz.exe"); - await using FileStream fileStream = fileInfo.Open(new FileStreamOptions + var psi = new ProcessStartInfo + { + FileName = hpatchzPath, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + RedirectStandardError = true + }; + + var currentPath = Path.Combine(_gamePath, "DNA Game"); + var patchedPath = Path.Combine(_gamePath, "patched"); + if (Directory.Exists(patchedPath)) { - Mode = FileMode.Open, - Access = FileAccess.Read, - Share = FileShare.Read, - Options = FileOptions.SequentialScan - }); + Directory.Delete(patchedPath, true); + } -#if DEBUG - SharedStatic.InstanceLogger.LogTrace("Trying to extract the ZIP archive: {ZipName}", filePath); -#endif + var gamePath = _gameVersion == null ? "" : currentPath; - ArchiveFile? archiveFile = null; + psi.ArgumentList.Add("-f"); // Force Patch + psi.ArgumentList.Add(gamePath); // Old Path + psi.ArgumentList.Add(hdiffPath); // Hdiff Path + psi.ArgumentList.Add(patchedPath); // New Path - bool fixSize = true; - void ZipProgressAdapter(object? sender, ExtractProgressProp e) + await DNAUtility.RunHPatchZAsync(psi, finalSize, patchedPath, (o) => { - if (fixSize) - { - Interlocked.Add(ref installProgress.TotalBytesToDownload, (long)e.TotalSize - fileDetails.Size); - fixSize = false; - } - - Interlocked.Add(ref installProgress.DownloadedBytes, (long)e.Read); + Interlocked.Add(ref installProgress.DownloadedBytes, o); progressDelegate?.Invoke(in installProgress); - progressStateDelegate?.Invoke(InstallProgressState.Install); - } + }, token); - try + if (Directory.Exists(currentPath)) { - archiveFile = ArchiveFile.Create(fileStream, true); - - // Start extraction - archiveFile.ExtractProgress += ZipProgressAdapter; - await archiveFile.ExtractAsync(e => Path.Combine(_gamePath, e!.FileName!), true, 1 << 20, token); - } - finally - { - if (archiveFile != null) - { - archiveFile.ExtractProgress -= ZipProgressAdapter; - archiveFile.Dispose(); - } + Directory.Delete(currentPath, true); } + Directory.Move(patchedPath, currentPath); - Interlocked.Increment(ref installProgress.DownloadedCount); - Interlocked.Increment(ref installProgress.StateCount); + installProgress.StateCount = 1; progressDelegate?.Invoke(in installProgress); progressStateDelegate?.Invoke(InstallProgressState.Install); + + return; } #endregion } - private async Task WriteVersionJson(string jsonPath, bool isFile = false) + private async Task WriteGameVersionJson(string jsonPath) { - if (_apiVersion == null) + if (HdiffInfo?.HdiffFile == null) return; FileInfo fileInfo = new FileInfo(jsonPath); @@ -366,20 +296,17 @@ private async Task WriteVersionJson(string jsonPath, bool isFile = false) using var output = fileInfo.Open(FileMode.Create, FileAccess.Write, FileShare.None); - if (isFile) - { - var installVersion = _apiVersion.ToFile(); - await JsonSerializer.SerializeAsync(output, installVersion, DNAFilesContext.Default.DNAFilesVersion); - } - else + var gameVersion = new DNAFilesGameVersion() { - await JsonSerializer.SerializeAsync(output, _apiVersion, DNAApiResponseContext.Default.DNAApiResponseVersion); - } + Version = int.Parse(_gameManager!.VersionManifest!.LatestVersion!) + }; + + await JsonSerializer.SerializeAsync(output, gameVersion, DNAFilesContext.Default.DNAFilesGameVersion); } protected override Task StartUpdateAsyncInner(InstallProgressDelegate? progressDelegate, InstallProgressStateDelegate? progressStateDelegate, CancellationToken token) { - // Updates are the exact same as installs, but BaseVersions already exists! °□° + // Updates are the exact same as installs, but _gameManager.GameVersion is not null return StartInstallAsyncInner(progressDelegate, progressStateDelegate, token); } diff --git a/Hi3Helper.Plugin.DNA/Management/DNAGameInstaller.cs b/Hi3Helper.Plugin.DNA/Management/DNAGameInstaller.cs index ff66380..c1bc963 100644 --- a/Hi3Helper.Plugin.DNA/Management/DNAGameInstaller.cs +++ b/Hi3Helper.Plugin.DNA/Management/DNAGameInstaller.cs @@ -1,12 +1,10 @@ using Hi3Helper.Plugin.Core; using Hi3Helper.Plugin.Core.Management; using Hi3Helper.Plugin.DNA.Management.Api; -using Hi3Helper.Plugin.DNA.Management.FileStructs; using Hi3Helper.Plugin.DNA.Utility; using Microsoft.Extensions.Logging; using System; using System.IO; -using System.Linq; using System.Net.Http; using System.Runtime.InteropServices.Marshalling; using System.Text.Json; @@ -21,75 +19,49 @@ internal partial class DNAGameInstaller : GameInstallerBase private readonly HttpClient _downloadHttpClient = DNAUtility.CreateApiHttpClient(); private DNAGameManager? _gameManager; - private string? _baseVersionUrl = null; - private const string _baseVersion = "BaseVersion.json"; - private string? _gamePath = null; - - private DNAApiResponseVersion? _apiVersion; - private DNAFilesVersion? _installVersion; - private DNAApiResponseVersion? _tempVersion; + private string? _gameVersion = null; + + private const string _tempPath = "TempPath"; + + private DNAApiResponseHdiffInfo? HdiffInfo = null; + + private const string _gameVersionName = "GameVersion.json"; - public DNAGameInstaller(IGameManager? gameManager, DNAApiResponseDetails apiResponseDetails) : base(gameManager) + public DNAGameInstaller(IGameManager? gameManager) : base(gameManager) { _gameManager = gameManager as DNAGameManager; - _baseVersionUrl = $"{apiResponseDetails.BaseUrl}/Packages/{apiResponseDetails.Region}/WindowsNoEditor/{apiResponseDetails.Tag}/{_gameManager?.ApiResponseVersion}/"; } protected override async Task InitAsync(CancellationToken token) { GameManager.GetGamePath(out _gamePath); - // Attempt to download API BaseVersion - try + _gameVersion = _gameManager!.GameVersion?.Version.ToString(); + if (_gameVersion != null) { - using HttpResponseMessage versionResponse = - await _downloadHttpClient.GetAsync(_baseVersionUrl + _baseVersion, HttpCompletionOption.ResponseHeadersRead, token); - versionResponse.EnsureSuccessStatusCode(); + long gameVer = long.Parse(_gameVersion); + long minVer = long.Parse(_gameManager!.VersionManifest!.MinSupportedVersion!); - string jsonResponse = await versionResponse.Content.ReadAsStringAsync(token); - _apiVersion = JsonSerializer.Deserialize(jsonResponse, DNAApiResponseContext.Default.DNAApiResponseVersion); - SharedStatic.InstanceLogger.LogDebug("[DNAGameInstaller::InitAsync] Downloaded BaseVersion.json"); - } - catch (Exception ex) - { - SharedStatic.InstanceLogger.LogWarning("[DNAGameInstaller::InitAsync] Failed to get API BaseVersion.json: {Err}", ex.Message); - _apiVersion = null; - } - - // Attempt to parse Install BaseVersion - try - { - var jsonPath = Path.Combine(_gamePath!, _baseVersion); - if (Path.Exists(jsonPath)) + if (gameVer < minVer) { - using var jsonResponse = File.OpenRead(jsonPath); - _installVersion = JsonSerializer.Deserialize(jsonResponse, DNAFilesContext.Default.DNAFilesVersion); - SharedStatic.InstanceLogger.LogDebug("[DNAGameInstaller::InitAsync] Deserialized Install BaseVersion.json"); + _gameVersion = null; +#if DEBUG + SharedStatic.InstanceLogger.LogWarning("[DNAGameInstaller::InitAsync] Game version is too old to be updated, downloading full package."); +#endif } } - catch (Exception ex) - { - SharedStatic.InstanceLogger.LogWarning("[DNAGameInstaller::InitAsync] Failed to deserialize Install BaseVersion: {Err}", ex.Message); - _installVersion = null; - } - // Attempt to parse Temp BaseVersion - try - { - var jsonPath = Path.Combine(_gamePath!, "TempPath", _baseVersion); - if (Path.Exists(jsonPath)) - { - using var jsonResponse = File.OpenRead(jsonPath); - _tempVersion = JsonSerializer.Deserialize(jsonResponse, DNAApiResponseContext.Default.DNAApiResponseVersion); - SharedStatic.InstanceLogger.LogDebug("[DNAGameInstaller::InitAsync] Deserialized Temp BaseVersion.json"); - } - } - catch (Exception ex) - { - SharedStatic.InstanceLogger.LogWarning("[DNAGameInstaller::InitAsync] Failed to deserialize Temp BaseVersion: {Err}", ex.Message); - _tempVersion = null; - } + // Get information about file to download + var hdiffInfoUrl = _gameManager!.ApiDetails.GetHdiffInfoUrl( + _gameManager.VersionManifest!.LatestVersionNumber!, + _gameManager.VersionManifest!.LatestVersion!, + _gameVersion); + using HttpResponseMessage hdiffInfoResponse = await _downloadHttpClient.GetAsync(hdiffInfoUrl, HttpCompletionOption.ResponseHeadersRead, token); + hdiffInfoResponse.EnsureSuccessStatusCode(); + + string jsonResponse = await hdiffInfoResponse.Content.ReadAsStringAsync(token); + HdiffInfo = JsonSerializer.Deserialize(jsonResponse, DNAApiResponseContext.Default.DNAApiResponseHdiffInfo); return 0; } @@ -101,7 +73,7 @@ public override void Dispose() protected override async Task GetGameDownloadedSizeAsyncInner(GameInstallerKind gameInstallerKind, CancellationToken token) { - if (_apiVersion == null) + if (HdiffInfo == null) return 0L; await InitAsync(token).ConfigureAwait(false); @@ -120,30 +92,24 @@ private long CalculateDownloadedBytesAsync(CancellationToken token) if (string.IsNullOrEmpty(_gamePath)) return 0L; - if (_apiVersion == null) + if (HdiffInfo?.HdiffFile == null) return 0L; - (var missingFiles, var filesToDelete) = VersionUtils.FindMissingFiles(_apiVersion.FilesList, _installVersion?.FilesList, _tempVersion?.FilesList); - - var filteredFiles = missingFiles.Where(x => !filesToDelete.Contains(x.Key)); - - // Check main files - var tempPath = Path.Combine(_gamePath, "TempPath", "TempGameFiles"); + var tempPath = Path.Combine(_gamePath, _tempPath); var downloadedSize = 0L; - foreach (var files in filteredFiles) - { - var filePath = Path.Combine(tempPath, files.Key); - try - { - var fi = new FileInfo(filePath); - downloadedSize += fi.Length; - SharedStatic.InstanceLogger.LogTrace("[DNAGameInstaller::CalculateDownloadedBytesAsync] Counted existing file {File} len={Len}", filePath, fi.Length); - } - catch (Exception ex) - { - SharedStatic.InstanceLogger.LogWarning("[DNAGameInstaller::CalculateDownloadedBytesAsync] Error reading file info {File}: {Err}", filePath, ex.Message); - } + var filePath = Path.Combine(tempPath, HdiffInfo.HdiffFile.Name!); + try + { + var fi = new FileInfo(filePath); + downloadedSize += fi.Length; +#if DEBUG + SharedStatic.InstanceLogger.LogTrace("[DNAGameInstaller::CalculateDownloadedBytesAsync] Counted existing file {File} len={Len}", filePath, fi.Length); +#endif + } + catch (Exception ex) + { + SharedStatic.InstanceLogger.LogWarning("[DNAGameInstaller::CalculateDownloadedBytesAsync] Error reading file info {File}: {Err}", filePath, ex.Message); } return downloadedSize; @@ -154,30 +120,18 @@ protected override async Task GetGameSizeAsyncInner(GameInstallerKind game if (gameInstallerKind is GameInstallerKind.None or GameInstallerKind.Preload) return 0; - if (_apiVersion == null || _apiVersion.GameVersionList.Count == 0) + if (HdiffInfo?.HdiffFile == null) { - SharedStatic.InstanceLogger.LogDebug("[DNAGameInstaller::GetGameSizeAsyncInner] Version list empty or null"); + SharedStatic.InstanceLogger.LogWarning("[DNAGameInstaller::GetGameSizeAsyncInner] No information about the download exist"); return 0L; } - (var missingFiles, _) = VersionUtils.FindMissingFiles(_apiVersion.FilesList, _installVersion?.FilesList, _tempVersion?.FilesList); - - try - { - long total = 0; - foreach ((_, var file) in missingFiles) - { - total = unchecked(total + file.Size); - } +#if DEBUG + SharedStatic.InstanceLogger.LogWarning("[DNAGameInstaller::GetGameSizeAsyncInner] Download size: {DS} / Final size: {FS}", + HdiffInfo.HdiffFile.Size, HdiffInfo.NewSize); +#endif - SharedStatic.InstanceLogger.LogDebug("[DNAGameInstaller::GetGameSizeAsyncInner] Computed total size: {Total}", total); - return total; - } - catch (Exception ex) - { - SharedStatic.InstanceLogger.LogWarning("[WuwaGameInstaller::GetGameSizeAsyncInner] Error computing total size: {Err}", ex.Message); - return 0L; - } + return HdiffInfo.HdiffFile.Size ?? 0L; } private int GetDownloadedCountAsync(GameInstallerKind install, CancellationToken token) @@ -185,28 +139,26 @@ private int GetDownloadedCountAsync(GameInstallerKind install, CancellationToken if (install is GameInstallerKind.None or GameInstallerKind.Preload) return 0; - if (_apiVersion is null) + if (HdiffInfo?.HdiffFile == null) { - SharedStatic.InstanceLogger.LogError("[DNAGameInstaller::StartInstallAsyncInner] _apiVersion is null, aborting."); - throw new InvalidOperationException("BaseVersion from API is not initialized."); + SharedStatic.InstanceLogger.LogError("[DNAGameInstaller::StartInstallAsyncInner] HdiffFile is null, aborting."); + throw new InvalidOperationException("No information about download package."); } - (var missingFiles, _) = VersionUtils.FindMissingFiles(_apiVersion.FilesList, _installVersion?.FilesList, _tempVersion?.FilesList); + var file = HdiffInfo.HdiffFile; - var tempPath = Path.Combine(_gamePath!, "TempPath", "TempGameFiles"); + var tempPath = Path.Combine(_gamePath!, _tempPath); if (!Directory.Exists(tempPath)) return 0; var totalDownloaded = 0; - foreach ((var fileName, var fileDetails) in missingFiles) + + var filePath = Path.Combine(tempPath, HdiffInfo.HdiffFile.Name!); + if (File.Exists(filePath)) { - var filePath = Path.Combine(tempPath, fileName); - if (File.Exists(filePath)) - { - var existingSize = new FileInfo(filePath).Length; - if (existingSize == fileDetails.Size) - totalDownloaded++; - } + var fileSize = new FileInfo(filePath).Length; + if (fileSize == file.Size) + totalDownloaded++; } return totalDownloaded; diff --git a/Hi3Helper.Plugin.DNA/Management/DNAGameManager.cs b/Hi3Helper.Plugin.DNA/Management/DNAGameManager.cs index 5b94969..18fcbeb 100644 --- a/Hi3Helper.Plugin.DNA/Management/DNAGameManager.cs +++ b/Hi3Helper.Plugin.DNA/Management/DNAGameManager.cs @@ -10,7 +10,6 @@ using System; using System.Diagnostics.CodeAnalysis; using System.IO; -using System.Linq; using System.Net.Http; using System.Runtime.InteropServices.Marshalling; using System.Text.Json; @@ -29,12 +28,10 @@ internal partial class DNAGameManager : GameManagerBase { internal DNAGameManager( string gameExecutableNameByPreset, - DNAApiResponseDetails details, DNAPresetConfig preset) { CurrentGameExecutableByPreset = gameExecutableNameByPreset; - ApiResponseBaseUrl = details.BaseUrl; - ApiResponseDetails = details; + ApiDetails = preset.ApiResponseDetails; Preset = preset; } @@ -52,31 +49,32 @@ protected HttpClient ApiDownloadHttpClient set; } - protected override string ApiResponseBaseUrl { get; } - protected DNAApiResponseDetails ApiResponseDetails { get; } + private DNAPresetConfig Preset { get; } - public string ApiResponseVersion { get; private set; } = "1"; + public DNAApiDetails ApiDetails { get; } private string CurrentGameExecutableByPreset { get; } - - private DNAPresetConfig Preset { get; } - - internal string? GameResourceBaseUrl { get; set; } - internal string? GameResourceBasisPath { get; set; } - internal bool IsInitialized { get; set; } + + internal bool IsInitialized { get; set; } + + protected override GameVersion ApiGameVersion { get; set; } + protected override GameVersion CurrentGameVersion { get; set; } protected override bool HasPreload => false; - protected override bool HasUpdate => IsInstalled && InstalledVersion != null && ApiVersion != null - && VersionUtils.CheckUpdate(ApiVersion.FilesList, InstalledVersion.FilesList); + protected override bool HasUpdate => IsInstalled && ApiGameVersion != CurrentGameVersion; + + public DNAApiResponseVersionManifest? VersionManifest { get; private set; } = null; + public DNAFilesGameVersion? GameVersion { get; private set; } = null; + public DNAFilesDownloadVersion? DownloadVersion { get; private set; } = null; protected override bool IsInstalled { get { string executablePath1 = - Path.Combine(CurrentGameInstallPath ?? string.Empty, CurrentGameExecutableByPreset); - string executablePath2 = Path.Combine(CurrentGameInstallPath ?? string.Empty, "EM/Binaries/Win64/EM-Win64-Shipping.exe"); - string executablePath3 = Path.Combine(CurrentGameInstallPath ?? string.Empty, "EM.exe"); + Path.Combine(CurrentGameInstallPath ?? string.Empty, "DNA Game", CurrentGameExecutableByPreset); + string executablePath2 = Path.Combine(CurrentGameInstallPath ?? string.Empty, "DNA Game\\EM\\Binaries\\Win64\\EM-Win64-Shipping.exe"); + string executablePath3 = Path.Combine(CurrentGameInstallPath ?? string.Empty, "DNA Game\\EM.exe"); return File.Exists(executablePath1) && File.Exists(executablePath2) && File.Exists(executablePath3); } } @@ -110,32 +108,25 @@ protected override Task InitAsync(CancellationToken token) return InitAsyncInner(true, token); } - private DNAApiResponseVersion? ApiVersion; - private DNAFilesVersion? InstalledVersion; - internal async Task InitAsyncInner(bool forceInit = false, CancellationToken token = default) { if (!forceInit && IsInitialized) return 0; - var apiUrl = $"{ApiResponseDetails.BaseUrl}/Packages/{ApiResponseDetails.Region}/WindowsNoEditor/{ApiResponseDetails.Tag}/PackageBaseVersion.txt"; - - using HttpResponseMessage packageVersionResponse = - await ApiResponseHttpClient.GetAsync(apiUrl, HttpCompletionOption.ResponseHeadersRead, token); - packageVersionResponse.EnsureSuccessStatusCode(); + using HttpResponseMessage manifestResponse = + await ApiResponseHttpClient.GetAsync(ApiDetails.GetVersionManifestUrl(), HttpCompletionOption.ResponseHeadersRead, token); + manifestResponse.EnsureSuccessStatusCode(); - ApiResponseVersion = await packageVersionResponse.Content.ReadAsStringAsync(token); - ApiGameVersion = new GameVersion($"{ApiResponseVersion}.0.0"); + string jsonResponse = await manifestResponse.Content.ReadAsStringAsync(token); + VersionManifest = JsonSerializer.Deserialize(jsonResponse, DNAApiResponseContext.Default.DNAApiResponseVersionManifest); - var apiVersionUrl = $"{ApiResponseDetails.BaseUrl}/Packages/{ApiResponseDetails.Region}/WindowsNoEditor/{ApiResponseDetails.Tag}/{ApiResponseVersion}/BaseVersion.json"; - - using HttpResponseMessage versionResponse = - await ApiResponseHttpClient.GetAsync(apiVersionUrl, HttpCompletionOption.ResponseHeadersRead, token); - versionResponse.EnsureSuccessStatusCode(); - - string jsonResponse = await versionResponse.Content.ReadAsStringAsync(token); - ApiVersion = JsonSerializer.Deserialize(jsonResponse, DNAApiResponseContext.Default.DNAApiResponseVersion); - ApiGameVersion = new GameVersion(ApiVersion?.GameVersionList.First().Key); + ApiGameVersion = new GameVersion($"{VersionManifest?.LatestVersion}.0.0"); +#if DEBUG + SharedStatic.InstanceLogger.LogTrace("[DNAGameManager::InitAsyncInner] Current Game Version is {Version} ({FormattedVersion})", + VersionManifest?.LatestVersion, VersionManifest?.LatestVersionNumber); + SharedStatic.InstanceLogger.LogTrace("[DNAGameManager::InitAsyncInner] Game can be updated from any version over {MinVersion}", + VersionManifest?.MinSupportedVersion); +#endif IsInitialized = true; @@ -178,7 +169,7 @@ protected override Task DownloadAssetAsyncInner(HttpClient? client, string fileU #if DEBUG SharedStatic.InstanceLogger.LogTrace("[DNAGameManager::FindExistingInstallPathAsyncInner] Found game executable at {Path}", expectedExe); #endif - return Path.GetDirectoryName(expectedExe); + return launcherDir; } return null; @@ -189,36 +180,34 @@ public override void LoadConfig() { if (string.IsNullOrEmpty(CurrentGameInstallPath)) { - SharedStatic.InstanceLogger.LogWarning( - "[DNAGameManager::LoadConfig] Game directory isn't set! Game config won't be loaded."); + SharedStatic.InstanceLogger.LogWarning("[DNAGameManager::LoadConfig] Game directory isn't set! Game config won't be loaded."); return; } - string filePath = Path.Combine(CurrentGameInstallPath, "BaseVersion.json"); + var gameFolder = Path.Combine(CurrentGameInstallPath, "DNA Game"); + var filePath = Path.Combine(gameFolder, "GameVersion.json"); FileInfo fileInfo = new(filePath); if (!fileInfo.Exists) { - SharedStatic.InstanceLogger.LogWarning( - "[DNAGameManager::LoadConfig] File BaseVersion.json doesn't exist on dir: {Dir}", - CurrentGameInstallPath); + SharedStatic.InstanceLogger.LogWarning("[DNAGameManager::LoadConfig] File GameVersion.json doesn't exist on dir: {Dir}", + gameFolder); return; } try { using FileStream fileStream = fileInfo.OpenRead(); - InstalledVersion = JsonSerializer.Deserialize(fileStream, DNAFilesContext.Default.DNAFilesVersion); - CurrentGameVersion = new GameVersion(InstalledVersion?.GameVersionList.First().Key); + GameVersion = JsonSerializer.Deserialize(fileStream, DNAFilesContext.Default.DNAFilesGameVersion); - SharedStatic.InstanceLogger.LogTrace( - "[DNAGameManager::LoadConfig] Loaded BaseVersion.json from directory: {Dir}", - CurrentGameInstallPath); + CurrentGameVersion = new GameVersion($"{GameVersion?.Version}.0.0"); + + SharedStatic.InstanceLogger.LogTrace("[DNAGameManager::LoadConfig] Loaded GameVersion.json ({Version}) from directory: {Dir}", + GameVersion?.Version, gameFolder); } catch (Exception ex) { - SharedStatic.InstanceLogger.LogError( - "[DNAGameManager::LoadConfig] Cannot load BaseVersion.json! Reason: {Exception}", ex); + SharedStatic.InstanceLogger.LogError("[DNAGameManager::LoadConfig] Cannot load GameVersion.json! Reason: {Exception}", ex); } } @@ -226,9 +215,4 @@ public override void SaveConfig() { // NOP } - - internal void SetCurrentGameVersion(DNAFilesVersion? version) - { - InstalledVersion = version; - } } \ No newline at end of file diff --git a/Hi3Helper.Plugin.DNA/Management/FileStructs/DNAFilesContext.cs b/Hi3Helper.Plugin.DNA/Management/FileStructs/DNAFilesContext.cs index da32fa3..8d3f548 100644 --- a/Hi3Helper.Plugin.DNA/Management/FileStructs/DNAFilesContext.cs +++ b/Hi3Helper.Plugin.DNA/Management/FileStructs/DNAFilesContext.cs @@ -2,5 +2,6 @@ namespace Hi3Helper.Plugin.DNA.Management.FileStructs; -[JsonSerializable(typeof(DNAFilesVersion))] +[JsonSerializable(typeof(DNAFilesGameVersion))] +[JsonSerializable(typeof(DNAFilesDownloadVersion))] public partial class DNAFilesContext : JsonSerializerContext; diff --git a/Hi3Helper.Plugin.DNA/Management/FileStructs/DNAFilesDownloadVersion.cs b/Hi3Helper.Plugin.DNA/Management/FileStructs/DNAFilesDownloadVersion.cs new file mode 100644 index 0000000..ea7c595 --- /dev/null +++ b/Hi3Helper.Plugin.DNA/Management/FileStructs/DNAFilesDownloadVersion.cs @@ -0,0 +1,21 @@ +// ReSharper disable InconsistentNaming + +using System.Text.Json.Serialization; + +namespace Hi3Helper.Plugin.DNA.Management.FileStructs; + +// /TempPath/TempGameFiles/GameVersion.json +public class DNAFilesDownloadVersion +{ + [JsonPropertyName("version")] + public string? Version { get; set; } = null!; + + [JsonPropertyName("hdiff_file")] + public string? HdiffFile { get; set; } = null!; + + [JsonPropertyName("md5")] + public string? MD5 { get; set; } = null!; + + [JsonPropertyName("is_full_patch")] + public bool? IsFullPatch { get; set; } = null!; +} diff --git a/Hi3Helper.Plugin.DNA/Management/FileStructs/DNAFilesGameVersion.cs b/Hi3Helper.Plugin.DNA/Management/FileStructs/DNAFilesGameVersion.cs new file mode 100644 index 0000000..07f6705 --- /dev/null +++ b/Hi3Helper.Plugin.DNA/Management/FileStructs/DNAFilesGameVersion.cs @@ -0,0 +1,12 @@ +// ReSharper disable InconsistentNaming + +using System.Text.Json.Serialization; + +namespace Hi3Helper.Plugin.DNA.Management.FileStructs; + +// /GameVersion.json +public class DNAFilesGameVersion +{ + [JsonPropertyName("version")] + public int? Version { get; set; } = null!; +} diff --git a/Hi3Helper.Plugin.DNA/Management/FileStructs/DNAFilesVersion.cs b/Hi3Helper.Plugin.DNA/Management/FileStructs/DNAFilesVersion.cs deleted file mode 100644 index 1381e07..0000000 --- a/Hi3Helper.Plugin.DNA/Management/FileStructs/DNAFilesVersion.cs +++ /dev/null @@ -1,39 +0,0 @@ -// ReSharper disable InconsistentNaming - -using System.Collections.Generic; -using System.Linq; -using System.Text.Json.Serialization; - -namespace Hi3Helper.Plugin.DNA.Management.FileStructs; - -public class DNAFilesVersion -{ - [JsonPropertyName("gameVersionList")] - public Dictionary GameVersionList { get; set; } = []; - - [JsonIgnore] - public Dictionary? FilesList - => GameVersionList?.FirstOrDefault().Value.FilesList; -} - -public class DNAFilesVersionContainer -{ - [JsonPropertyName("gameVersionList")] - public Dictionary FilesList { get; set; } = []; -} - -public class DNAFilesVersionFileInfo -{ - [JsonPropertyName("zipGameVersion")] - public int Version { get; set; } - - [JsonPropertyName("zipMd5")] - public string? ChecksumMD5 { get; set; } - - [JsonPropertyName("zipSize")] - public long Size { get; set; } - - [JsonPropertyName("bIsSDK")] - public bool IsSDK { get; set; } -} - diff --git a/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNABilibiliPresetConfig.cs b/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNABilibiliPresetConfig.cs index 818fcd5..47e79ba 100644 --- a/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNABilibiliPresetConfig.cs +++ b/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNABilibiliPresetConfig.cs @@ -11,11 +11,10 @@ namespace Hi3Helper.Plugin.DNA.Management.PresetConfig; [GeneratedComClass] public partial class DNABiliBilliPresetConfig : DNAChinaPresetConfig { - private readonly DNAApiResponseDetails ApiResponseDetails = new() + public override DNAApiDetails ApiResponseDetails { get; } = new() { BaseUrls = [ "http://pan01-cdn-dna-ali.shyxhy.com", - "http://pan01-cdn-dna-aws.shyxhy.com", "http://pan01-1-eo.shyxhy.com", "http://pan01-1-hs.shyxhy.com" ], @@ -41,13 +40,13 @@ public partial class DNABiliBilliPresetConfig : DNAChinaPresetConfig public override IGameManager? GameManager { - get => field ??= new DNAGameManager(ExecutableName, ApiResponseDetails, this); + get => field ??= new DNAGameManager(ExecutableName, this); set; } public override IGameInstaller? GameInstaller { - get => field ??= new DNAGameInstaller(GameManager, ApiResponseDetails); + get => field ??= new DNAGameInstaller(GameManager); set; } } diff --git a/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNAChinaPresetConfig.cs b/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNAChinaPresetConfig.cs index 43e77c3..230d39f 100644 --- a/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNAChinaPresetConfig.cs +++ b/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNAChinaPresetConfig.cs @@ -16,11 +16,10 @@ namespace Hi3Helper.Plugin.DNA.Management.PresetConfig; [GeneratedComClass] public partial class DNAChinaPresetConfig : DNAPresetConfig { - private readonly DNAApiResponseDetails ApiResponseDetails = new() + public override DNAApiDetails ApiResponseDetails { get; } = new() { BaseUrls = [ "http://pan01-cdn-dna-ali.shyxhy.com", - "http://pan01-cdn-dna-aws.shyxhy.com", "http://pan01-1-eo.shyxhy.com", "http://pan01-1-hs.shyxhy.com" ], @@ -38,10 +37,10 @@ public partial class DNAChinaPresetConfig : DNAPresetConfig public override string GameName => "Duet Night Abyss"; [field: AllowNull, MaybeNull] - public override string GameExecutableName => field ??= Path.Combine("EM", "Binaries", "Win64", EngineExecutableName); + public override string GameExecutableName => field ??= Path.Combine("DNA Game", "EM", "Binaries", "Win64", EngineExecutableName); [field: AllowNull, MaybeNull] - public override string StartExecutableName => field ??= ExecutableName; + public override string StartExecutableName => field ??= Path.Combine("DNA Game", ExecutableName); public override string GameAppDataPath { get @@ -97,25 +96,25 @@ public override string GameAppDataPath { public override ILauncherApiMedia? LauncherApiMedia { - get => field ??= new DNAGlobalLauncherApiMedia(ApiResponseDetails, ZoneLogoUrl, BackgroundUrl); + get => field ??= new DNAGlobalLauncherApiMedia(this); set; } public override ILauncherApiNews? LauncherApiNews { - get => field ??= new DNAGlobalLauncherApiNews(ApiResponseDetails, "CN"); + get => field ??= new DNAGlobalLauncherApiNews(this, "CN"); set; } public override IGameManager? GameManager { - get => field ??= new DNAGameManager(ExecutableName, ApiResponseDetails, this); + get => field ??= new DNAGameManager(ExecutableName, this); set; } public override IGameInstaller? GameInstaller { - get => field ??= new DNAGameInstaller(GameManager, ApiResponseDetails); + get => field ??= new DNAGameInstaller(GameManager); set; } diff --git a/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNAEpicPresetConfig.cs b/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNAEpicPresetConfig.cs index 09e1f58..5c80f76 100644 --- a/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNAEpicPresetConfig.cs +++ b/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNAEpicPresetConfig.cs @@ -11,7 +11,7 @@ namespace Hi3Helper.Plugin.DNA.Management.PresetConfig; [GeneratedComClass] public partial class DNAEpicPresetConfig : DNAGlobalPresetConfig { - private readonly DNAApiResponseDetails ApiResponseDetails = new() + public override DNAApiDetails ApiResponseDetails { get; } = new() { BaseUrls = [ "http://pan01-cdn-aws-jp.dna-panstudio.com", @@ -38,13 +38,13 @@ public partial class DNAEpicPresetConfig : DNAGlobalPresetConfig public override IGameManager? GameManager { - get => field ??= new DNAGameManager(ExecutableName, ApiResponseDetails, this); + get => field ??= new DNAGameManager(ExecutableName, this); set; } public override IGameInstaller? GameInstaller { - get => field ??= new DNAGameInstaller(GameManager, ApiResponseDetails); + get => field ??= new DNAGameInstaller(GameManager); set; } } diff --git a/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNAGlobalPresetConfig.cs b/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNAGlobalPresetConfig.cs index 00cf053..aa1eb37 100644 --- a/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNAGlobalPresetConfig.cs +++ b/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNAGlobalPresetConfig.cs @@ -16,7 +16,7 @@ namespace Hi3Helper.Plugin.DNA.Management.PresetConfig; [GeneratedComClass] public partial class DNAGlobalPresetConfig : DNAPresetConfig { - private readonly DNAApiResponseDetails ApiResponseDetails = new() + public override DNAApiDetails ApiResponseDetails { get; } = new() { BaseUrls = [ "http://pan01-cdn-aws-jp.dna-panstudio.com", @@ -38,10 +38,10 @@ public partial class DNAGlobalPresetConfig : DNAPresetConfig public override string GameName => "Duet Night Abyss"; [field: AllowNull, MaybeNull] - public override string GameExecutableName => field ??= Path.Combine("EM", "Binaries", "Win64", EngineExecutableName); + public override string GameExecutableName => field ??= Path.Combine("DNA Game", "EM", "Binaries", "Win64", EngineExecutableName); [field: AllowNull, MaybeNull] - public override string StartExecutableName => field ??= ExecutableName; + public override string StartExecutableName => field ??= Path.Combine("DNA Game", ExecutableName); public override string GameAppDataPath { get @@ -50,7 +50,7 @@ public override string GameAppDataPath { GameManager?.GetGamePath(out path); if (path == null) return string.Empty; - return Path.Combine(path, "EM", "Saved"); + return Path.Combine(path, "DNA Game", "EM", "Saved"); } } @@ -98,30 +98,31 @@ public override string GameAppDataPath { public override ILauncherApiMedia? LauncherApiMedia { - get => field ??= new DNAGlobalLauncherApiMedia(ApiResponseDetails, ZoneLogoUrl, BackgroundUrl); + get => field ??= new DNAGlobalLauncherApiMedia(this); set; } public override ILauncherApiNews? LauncherApiNews { - get => field ??= new DNAGlobalLauncherApiNews(ApiResponseDetails); + get => field ??= new DNAGlobalLauncherApiNews(this); set; } public override IGameManager? GameManager { - get => field ??= new DNAGameManager(ExecutableName, ApiResponseDetails, this); + get => field ??= new DNAGameManager(ExecutableName, this); set; } public override IGameInstaller? GameInstaller { - get => field ??= new DNAGameInstaller(GameManager, ApiResponseDetails); + get => field ??= new DNAGameInstaller(GameManager); set; } protected override Task InitAsync(CancellationToken token) { + return Task.FromResult(0); } } diff --git a/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNAPresetConfig.cs b/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNAPresetConfig.cs index 8f68c2a..d998cba 100644 --- a/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNAPresetConfig.cs +++ b/Hi3Helper.Plugin.DNA/Management/PresetConfig/DNAPresetConfig.cs @@ -1,5 +1,8 @@ using Hi3Helper.Plugin.Core.Management.PresetConfig; +using Hi3Helper.Plugin.DNA.Management.Api; using System.Runtime.InteropServices.Marshalling; +using System.Threading; +using System.Threading.Tasks; // ReSharper disable IdentifierTypo // ReSharper disable InconsistentNaming @@ -9,7 +12,9 @@ namespace Hi3Helper.Plugin.DNA.Management.PresetConfig; [GeneratedComClass] public abstract partial class DNAPresetConfig : PluginPresetConfigBase { + public abstract DNAApiDetails ApiResponseDetails { get; } + public abstract string? StartExecutableName { get; } - protected const string BackgroundUrl = "https://video.yingxiong.com/fhd/696d50aea66d49d9af0cf2fda53d9186.mp4"; + public string DefaultBackgroundUrl { get; } = "https://cdnstatic.yingxiong.com/dna_hd_1_3/imgs/home/pc/bg.webp"; } diff --git a/Hi3Helper.Plugin.DNA/Properties/PublishProfiles/DebugNoReflectionPublish.pubxml b/Hi3Helper.Plugin.DNA/Properties/PublishProfiles/DebugNoReflectionPublish.pubxml index 5649ba9..48092e3 100644 --- a/Hi3Helper.Plugin.DNA/Properties/PublishProfiles/DebugNoReflectionPublish.pubxml +++ b/Hi3Helper.Plugin.DNA/Properties/PublishProfiles/DebugNoReflectionPublish.pubxml @@ -2,7 +2,7 @@ - Release + Debug x64 publish/Debug FileSystem diff --git a/Hi3Helper.Plugin.DNA/Utility/DNAUtility.cs b/Hi3Helper.Plugin.DNA/Utility/DNAUtility.cs index bf6bd79..d0e4a3f 100644 --- a/Hi3Helper.Plugin.DNA/Utility/DNAUtility.cs +++ b/Hi3Helper.Plugin.DNA/Utility/DNAUtility.cs @@ -1,9 +1,17 @@ using Hi3Helper.Plugin.Core; +using Hi3Helper.Plugin.Core.Management; using Hi3Helper.Plugin.Core.Utility; +using Microsoft.Extensions.Logging; using System; +using System.Diagnostics; +using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; // ReSharper disable InconsistentNaming // ReSharper disable StringLiteralTypo @@ -29,7 +37,7 @@ internal static HttpClient CreateApiHttpClient(bool useCompression = true) internal static PluginHttpClientBuilder CreateApiHttpClientBuilder(bool useCompression = true) { PluginHttpClientBuilder builder = new PluginHttpClientBuilder() - .SetUserAgent($"EMLauncher/++UE4+Release-4.27-CL-0 Windows/10.0.26100.1.768.64bit"); + .SetUserAgent($"EMLauncher/++UE4+Release-4.27-CL-0 Windows/10.0.26200.1.256.64bit"); if (!useCompression) { @@ -82,4 +90,119 @@ internal static PluginHttpClientBuilder CreateVideoHttpClientBuilder(bool useCom "fr-fr" => "FR", _ => "EN", }; + + internal static string GetOverlayLangFromLauncherLocale() => SharedStatic.PluginLocaleCode switch + { + "zh-cn" => "chs", + "zh-tw" => "cht", + "ja-jp" => "jp", + "ko-kr" => "kr", + _ => "en", + }; + + #region Plugin Folder + public static readonly string AppDataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "AppData", "LocalLow", "CollapseLauncher"); + public static readonly string AppConfigFile = Path.Combine(AppDataFolder, "config.ini"); + + internal static string? FindPluginPath() + { + if (!Path.Exists(AppConfigFile)) + return null; + + var gameFolder = GetIniValue(AppConfigFile, "GameFolder"); + return Path.Combine(gameFolder!, "_plugins", "Hi3Helper.Plugin.DNAbyss"); + } + + private static string? GetIniValue(string path, string key) + { + using var reader = new StreamReader(path); + string? line; + + while ((line = reader.ReadLine()) != null) + { + ReadOnlySpan s = line.AsSpan().Trim(); + + // Skip blanks, comments, and [section] headers + if (s.IsEmpty || s[0] is ';' or '#' or '[') + continue; + + int eq = s.IndexOf('='); + if (eq <= 0) continue; + + if (s[..eq].Trim().Equals(key, StringComparison.OrdinalIgnoreCase)) + return s[(eq + 1)..].Trim().ToString(); + } + + return null; + } + #endregion + + #region HPatchZ + public static async Task RunHPatchZAsync(ProcessStartInfo psi, long totalSize, string outputDir, + Action progressCallback, CancellationToken token) + { + psi.UseShellExecute = false; + psi.CreateNoWindow = true; + psi.RedirectStandardOutput = true; + psi.RedirectStandardError = true; + + using Process proc = new() { StartInfo = psi }; + proc.Start(); + + await using CancellationTokenRegistration reg = token.Register(() => + { + try { if (!proc.HasExited) proc.Kill(entireProcessTree: true); } + catch { /* already exited */ } + }); + + Task stdoutTask = proc.StandardOutput.ReadToEndAsync(token); + Task stderrTask = proc.StandardError.ReadToEndAsync(token); + Task exitTask = proc.WaitForExitAsync(token); + + long lastBytes = GetDirectorySize(outputDir); + + while (!exitTask.IsCompleted) + { + await Task.WhenAny(exitTask, Task.Delay(1000, token)); + + long current = GetDirectorySize(outputDir); + long o = current - lastBytes; + if (o > 0) + { + lastBytes = current; + progressCallback(o); + } + } + + await exitTask; + + if (proc.ExitCode != 0) + throw new Exception(await stderrTask); + + long end = GetDirectorySize(outputDir); + if (end - lastBytes > 0) + { + progressCallback(end - lastBytes); + } + } + + private static long GetDirectorySize(string path) + { + long total = 0; + try + { + DirectoryInfo di = new(path); + if (!di.Exists) return 0; + + foreach (FileInfo fi in di.EnumerateFiles("*", SearchOption.AllDirectories)) + { + try { total += fi.Length; } + catch (IOException) { /* file vanished or locked, skip */ } + } + } + catch (IOException) { } + catch (UnauthorizedAccessException) { } + return total; + } + #endregion } diff --git a/Hi3Helper.Plugin.DNA/Utility/VersionUtils.cs b/Hi3Helper.Plugin.DNA/Utility/VersionUtils.cs deleted file mode 100644 index e366ff4..0000000 --- a/Hi3Helper.Plugin.DNA/Utility/VersionUtils.cs +++ /dev/null @@ -1,46 +0,0 @@ -using Hi3Helper.Plugin.DNA.Management.Api; -using Hi3Helper.Plugin.DNA.Management.FileStructs; -using System.Collections.Generic; - -namespace Hi3Helper.Plugin.DNA.Utility; - -using ApiFilesDict = Dictionary; -using FilesDict = Dictionary; - -internal class VersionUtils -{ - internal static bool CheckUpdate(ApiFilesDict? apiVersion, FilesDict? installedVersion) - => FindMissingFiles(apiVersion, installedVersion, null).Item1.Count != 0; - - internal static (ApiFilesDict, HashSet) FindMissingFiles(ApiFilesDict? apiVersion, FilesDict? installedVersion, ApiFilesDict? tempVersion) - { - var diffVersion = new ApiFilesDict(); - var expiredFiles = new HashSet(); - - if (apiVersion == null) - return (diffVersion, expiredFiles); - - foreach ((var fileName, var apiDetails) in apiVersion) - { - var tempDetails = tempVersion?.GetValueOrDefault(fileName); - var installedDetails = installedVersion?.GetValueOrDefault(fileName); - - bool isInstallChange = installedDetails != null && apiDetails.Version > installedDetails.Version; - bool isNew = installedDetails == null; - - // If file version is not installed or has an update - if (isInstallChange || isNew) - { - diffVersion.TryAdd(fileName, apiDetails); - } - - // If version changed, queue file for deletion - if (tempDetails != null && apiDetails.Version > tempDetails.Version) - { - expiredFiles.Add(fileName); - } - } - - return (diffVersion, expiredFiles); - } -} diff --git a/Lib/LICENSE.txt b/Lib/LICENSE.txt new file mode 100644 index 0000000..07fed6c --- /dev/null +++ b/Lib/LICENSE.txt @@ -0,0 +1,48 @@ +MIT License + +HDiffPatch +Copyright (c) 2012-2025 housisong + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +---------------------------------------------------------------------------------- + +libdivsufsort +Copyright (c) 2003-2008 Yuta Mori All Rights Reserved. + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/Lib/hpatchz.exe b/Lib/hpatchz.exe new file mode 100644 index 0000000..66bf2d5 Binary files /dev/null and b/Lib/hpatchz.exe differ diff --git a/SevenZipExtractor b/SevenZipExtractor deleted file mode 160000 index 049ccc4..0000000 --- a/SevenZipExtractor +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 049ccc4eea1aec0a2a856411c1657842bf4cfa8f diff --git a/qodana.yaml b/qodana.yaml deleted file mode 100644 index c97dc23..0000000 --- a/qodana.yaml +++ /dev/null @@ -1,41 +0,0 @@ -version: "1.0" -ide: QDNET -#linter: jetbrains/qodana-cdnet -bootstrap: git submodule sync --recursive && git -c protocol.version=2 submodule update --init --force --recursive && .\CompileAOTAndShip.bat 4 -dotnet: - solution: Hi3Helper.Plugin.DNA.sln -include: - - name: CheckDependencyLicenses - - name: VulnerableLibrariesGlobal - - name: RiderSecurityErrorsInspection -exclude: - - name: All - paths: - - Hi3Helper.Plugin.Core - - name: CheckNamespace - - name: UnusedParameter.Local - - name: UnusedMember.Local - - name: RedundantArgumentDefaultValue - - name: RedundantDefaultMemberInitializer - - name: Xaml.BindingWithContextNotResolved - - name: Xaml.ConstructorWarning - - name: Xaml.InvalidResourceType - - name: Xaml.StaticResourceNotResolved - - name: RedundantExtendsListEntry - - name: PartialTypeWithSinglePart - - name: InvalidXmlDocComment -licenseRules: - - keys: - - "MIT" - allowed: - # WinAppSDK - - "MS-DXSDK-D3DX-9.29.952.3" - # .NET - - "MS-ASP-NET-WEB-OPTIMIZATION" - - "MS-NET-LIBRARY-2019-06" - # Windows SDK - - "PROPRIETARY-LICENSE" - # Protobuf, duh - - "PROTOBUF" - # System.CommandLine NuGet for some reason - - "None"