mirror of
https://github.com/real-zony/ZonyLrcToolsX.git
synced 2026-11-24 03:37:47 +08:00
fix(desktop): 修正解密、配置和任务生命周期问题
修复 KGG/KGM 识别、密钥解码及输出文件保护;改进配置无损保存、登录会话安全和取消处理。统一新增 C# 代码风格,补齐发布许可声明及文档,并增加针对性回归测试。
This commit is contained in:
1 parent
7379571e2d
commit
8912a79168
64 files changed
+2787
-1182
No files matched your search
@@ -0,0 +1,191 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using YamlDotNet.RepresentationModel;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
using ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
namespace ZonyLrcTools.Tests.Infrastructure;
|
||||
|
||||
/// <summary>设置文件无损修改的回归测试。</summary>
|
||||
public sealed class DesktopSettingsPersistenceTests
|
||||
{
|
||||
/// <summary>会话与数据库路径使用生成的 JSON 元数据往返,敏感会话文件限制权限。</summary>
|
||||
[Theory]
|
||||
[InlineData(true)]
|
||||
[InlineData(false)]
|
||||
public async Task RoundTripsStateUsingGeneratedMetadataAsync(bool isSession)
|
||||
{
|
||||
var directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N"));
|
||||
var path = Path.Combine(directory, "state.json");
|
||||
try
|
||||
{
|
||||
var assembly = typeof(NetEaseSession).Assembly;
|
||||
var contextType = assembly.GetType("ZonyLrcTools.Desktop.Infrastructure.Configuration.DesktopStateJsonContext")!;
|
||||
var context = (JsonSerializerContext)contextType.GetProperty("Default")!.GetValue(null)!;
|
||||
var value = isSession
|
||||
? (object)new NetEaseSession { Cookie = "test-cookie", CsrfToken = "test-token" }
|
||||
: new KugouDatabaseSetting { DatabasePath = "/music/My Database.db" };
|
||||
var typeInfo = context.GetTypeInfo(value.GetType())!;
|
||||
var writer = assembly.GetType("ZonyLrcTools.Desktop.Infrastructure.Configuration.DesktopStateFile")!;
|
||||
var method = writer.GetMethod("WriteAsync", BindingFlags.Static | BindingFlags.NonPublic)!
|
||||
.MakeGenericMethod(value.GetType());
|
||||
await (Task)method.Invoke(null, new object[]
|
||||
{
|
||||
path, value, typeInfo, isSession, CancellationToken.None
|
||||
})!;
|
||||
|
||||
var loaded = JsonSerializer.Deserialize(await File.ReadAllTextAsync(path), typeInfo);
|
||||
if (isSession)
|
||||
{
|
||||
var session = loaded.ShouldBeOfType<NetEaseSession>();
|
||||
session.Cookie.ShouldBe("test-cookie");
|
||||
session.CsrfToken.ShouldBe("test-token");
|
||||
}
|
||||
else
|
||||
{
|
||||
loaded.ShouldBeOfType<KugouDatabaseSetting>().DatabasePath.ShouldBe("/music/My Database.db");
|
||||
}
|
||||
if (isSession && !OperatingSystem.IsWindows())
|
||||
{
|
||||
File.GetUnixFileMode(path).ShouldBe(UnixFileMode.UserRead | UnixFileMode.UserWrite);
|
||||
}
|
||||
Directory.GetFiles(directory, "*.tmp").ShouldBeEmpty();
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Directory.Exists(directory))
|
||||
{
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>更改其他设置不能覆盖手工配置的换行符。</summary>
|
||||
[Fact]
|
||||
public void KeepsCustomLineBreakWhenChangingProxy()
|
||||
{
|
||||
var options = new GlobalOptions
|
||||
{
|
||||
Provider = new ProviderOptions
|
||||
{
|
||||
Lyric = new LyricsOptions
|
||||
{
|
||||
Config = new GlobalLyricsConfigOptions { LineBreak = string.Empty, FileEncoding = "ascii" },
|
||||
Plugin = Array.Empty<LyricsProviderOptions>()
|
||||
}
|
||||
}
|
||||
};
|
||||
var viewModel = new SettingsViewModel(new MemorySettingsStore(options));
|
||||
viewModel.IsProxyEnabled = true;
|
||||
options.Provider.Lyric.Config.LineBreak.ShouldBe(string.Empty);
|
||||
viewModel.AvailableEncodings.ShouldContain("ascii");
|
||||
}
|
||||
|
||||
/// <summary>恢复默认值同时恢复下载器顺序。</summary>
|
||||
[Fact]
|
||||
public async Task ResetRestoresProviderOrderAsync()
|
||||
{
|
||||
var options = new GlobalOptions
|
||||
{
|
||||
Provider = new ProviderOptions
|
||||
{
|
||||
Lyric = new LyricsOptions
|
||||
{
|
||||
Config = new GlobalLyricsConfigOptions(),
|
||||
Plugin = new[]
|
||||
{
|
||||
new LyricsProviderOptions { Name = "QQ", Priority = 1 },
|
||||
new LyricsProviderOptions { Name = "NetEase", Priority = -1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
var viewModel = new SettingsViewModel(new MemorySettingsStore(options));
|
||||
await viewModel.ResetToDefaultsCommand.ExecuteAsync(null);
|
||||
viewModel.LyricsProviders[0].Name.ShouldBe("NetEase");
|
||||
viewModel.LyricsProviders[0].Priority.ShouldBe(1);
|
||||
viewModel.LyricsProviders[0].IsEnabled.ShouldBeTrue();
|
||||
viewModel.ProxyPort.ShouldBe(4780);
|
||||
}
|
||||
|
||||
private sealed class MemorySettingsStore(GlobalOptions options) : ISettingsStore
|
||||
{
|
||||
public GlobalOptions Options { get; } = options;
|
||||
public string ConfigFilePath => "unused.yaml";
|
||||
public Task<SettingsSaveResult> SaveAsync(CancellationToken cancellationToken = default) =>
|
||||
Task.FromResult(SettingsSaveResult.Success(ConfigFilePath));
|
||||
}
|
||||
|
||||
/// <summary>合法的 YAML 写法不应导致未知字段和注释丢失。</summary>
|
||||
[Theory]
|
||||
[InlineData("# keep\nnetworkOptions: {isEnable: false, ip: localhost, port: 80}\ncustom: keep\n", "networkOptions.port", "8080")]
|
||||
[InlineData("# keep\nprovider:\n tag:\n blockWord:\n filePath: My Words.json # dictionary\ncustom: keep\n", "provider.tag.blockWord.filePath", "New Words.json")]
|
||||
[InlineData("# keep\nnetworkOptions:\n isEnable: false\n ip: localhost\ncustom: keep\n", "networkOptions.port", "8080")]
|
||||
[InlineData("# keep\nnetworkOptions: {isEnable: false, ip: localhost}\ncustom: keep\n", "networkOptions.port", "8080")]
|
||||
[InlineData("# keep\nnetworkOptions: {}\ncustom: keep\n", "networkOptions.port", "8080")]
|
||||
[InlineData("# keep\nnetworkOptions: {ip: localhost,}\ncustom: keep\n", "networkOptions.port", "8080")]
|
||||
public async Task PatchesValidYamlWithoutDiscardingUnmanagedValuesAsync(string yaml, string key, string value)
|
||||
{
|
||||
var path = Path.GetTempFileName();
|
||||
try
|
||||
{
|
||||
await File.WriteAllTextAsync(path, yaml);
|
||||
using var store = new SettingsStore(Options.Create(new GlobalOptions()));
|
||||
var method = typeof(SettingsStore).GetMethod("TryPatchInPlaceAsync", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
var result = await (Task<string?>)method.Invoke(store, new object[]
|
||||
{
|
||||
path, new Dictionary<string, string> { [key] = value }, CancellationToken.None
|
||||
})!;
|
||||
|
||||
result.ShouldNotBeNull();
|
||||
result.ShouldContain("# keep");
|
||||
var stream = new YamlStream();
|
||||
stream.Load(new StringReader(result!));
|
||||
var mapping = (YamlMappingNode)stream.Documents[0].RootNode;
|
||||
((YamlScalarNode)mapping.Children[new YamlScalarNode("custom")]).Value.ShouldBe("keep");
|
||||
var node = (YamlNode)mapping;
|
||||
foreach (var part in key.Split('.'))
|
||||
{
|
||||
node = ((YamlMappingNode)node).Children[new YamlScalarNode(part)];
|
||||
}
|
||||
((YamlScalarNode)node).Value.ShouldBe(value);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>无效文件必须保留,不能用内存配置覆盖。</summary>
|
||||
[Fact]
|
||||
public async Task RefusesMalformedYamlAsync()
|
||||
{
|
||||
var path = Path.GetTempFileName();
|
||||
try
|
||||
{
|
||||
const string original = "networkOptions: [broken\n# keep";
|
||||
await File.WriteAllTextAsync(path, original);
|
||||
using var store = new SettingsStore(Options.Create(new GlobalOptions()));
|
||||
var method = typeof(SettingsStore).GetMethod("TryPatchInPlaceAsync", BindingFlags.Instance | BindingFlags.NonPublic)!;
|
||||
await Should.ThrowAsync<Exception>(async () => await (Task<string?>)method.Invoke(store, new object[]
|
||||
{
|
||||
path, new Dictionary<string, string> { ["networkOptions.port"] = "8080" }, CancellationToken.None
|
||||
})!);
|
||||
(await File.ReadAllTextAsync(path)).ShouldBe(original);
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common.MusicDecryption;
|
||||
using ZonyLrcTools.Common.MusicDecryption.Kugou;
|
||||
|
||||
namespace ZonyLrcTools.Tests.Infrastructure.MusicDecryption
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用合成加密 SQLite 数据验证密钥读取,不依赖真实酷狗数据库。
|
||||
/// </summary>
|
||||
public sealed class KggDatabaseRegressionTests : IDisposable
|
||||
{
|
||||
private readonly string _directory = Directory.CreateTempSubdirectory("zony-kgg-db-tests-").FullName;
|
||||
|
||||
/// <summary>
|
||||
/// 通过 SQLite 查询完整的合成加密数据库,并保持原文件不变。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void ReadEncryptionKeys_ReadsEncryptedDatabaseWithoutChangingSource()
|
||||
{
|
||||
var path = CreateEncryptedDatabase("keys;test.db");
|
||||
var original = File.ReadAllBytes(path);
|
||||
|
||||
var keys = KugouEkeyDatabase.ReadEncryptionKeys(path, out var failureReason);
|
||||
|
||||
Assert.Null(failureReason);
|
||||
Assert.Equal("synthetic-ekey", keys["audio-hash"]);
|
||||
Assert.Equal(original, File.ReadAllBytes(path));
|
||||
Assert.Single(Directory.GetFiles(_directory));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 区分大小写的文件系统上,切换路径大小写必须重新加载数据库。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void SetDatabasePath_ReloadsDistinctCaseSensitivePath()
|
||||
{
|
||||
var lowerPath = Path.Combine(_directory, "keys.db");
|
||||
var upperPath = Path.Combine(_directory, "KEYS.db");
|
||||
File.WriteAllText(lowerPath, "invalid database");
|
||||
if (File.Exists(upperPath))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
CreateEncryptedDatabase("KEYS.db");
|
||||
var provider = new KugouKeyProvider();
|
||||
provider.SetDatabasePath(lowerPath);
|
||||
Assert.False(provider.Probe().IsAvailable);
|
||||
|
||||
provider.SetDatabasePath(upperPath);
|
||||
|
||||
Assert.True(provider.Probe().IsAvailable);
|
||||
Assert.Equal("synthetic-ekey", provider.FindKey("audio-hash"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除本测试创建的数据。
|
||||
/// </summary>
|
||||
public void Dispose() => Directory.Delete(_directory, true);
|
||||
|
||||
private string CreateEncryptedDatabase(string name)
|
||||
{
|
||||
var path = Path.Combine(_directory, name);
|
||||
var connectionString = new SqliteConnectionStringBuilder { DataSource = path, Pooling = false }.ToString();
|
||||
using (var connection = new SqliteConnection(connectionString))
|
||||
{
|
||||
connection.Open();
|
||||
using var command = connection.CreateCommand();
|
||||
command.CommandText = "PRAGMA page_size=1024; CREATE TABLE ShareFileItems (EncryptionKeyId TEXT, EncryptionKey TEXT);"
|
||||
+ "INSERT INTO ShareFileItems VALUES ('audio-hash', 'synthetic-ekey');";
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
var bytes = File.ReadAllBytes(path);
|
||||
using var aes = Aes.Create();
|
||||
var derivation = new byte[24];
|
||||
for (var page = 1; page <= bytes.Length / 1024; page++)
|
||||
{
|
||||
Convert.FromHexString("1D613145B247BF7F3D189672144FE4BF").CopyTo(derivation, 0);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(derivation.AsSpan(16), (uint)page);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(derivation.AsSpan(20), 0x546C4173);
|
||||
aes.Key = MD5.HashData(derivation);
|
||||
var value = (uint)page + 1;
|
||||
for (var index = 0; index < 16; index += 4)
|
||||
{
|
||||
value = unchecked(0x9EF4 * value - 0x7FFFFF07 * (value / 0xCE26));
|
||||
if ((value & 0x80000000) != 0)
|
||||
{
|
||||
value = unchecked(value + 0x7FFFFF07);
|
||||
}
|
||||
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(derivation.AsSpan(index), value);
|
||||
}
|
||||
|
||||
var iv = MD5.HashData(derivation.AsSpan(0, 16));
|
||||
var offset = (page - 1) * 1024;
|
||||
if (page == 1)
|
||||
{
|
||||
var header = bytes.AsSpan(16, 8).ToArray();
|
||||
var encrypted = aes.EncryptCbc(bytes.AsSpan(16, 1008), iv, PaddingMode.None);
|
||||
encrypted.CopyTo(bytes, 16);
|
||||
encrypted.AsSpan(0, 8).CopyTo(bytes.AsSpan(8));
|
||||
header.CopyTo(bytes, 16);
|
||||
}
|
||||
else
|
||||
{
|
||||
var encrypted = aes.EncryptCbc(bytes.AsSpan(offset, 1024), iv, PaddingMode.None);
|
||||
encrypted.CopyTo(bytes, offset);
|
||||
}
|
||||
}
|
||||
|
||||
File.WriteAllBytes(path, bytes);
|
||||
return path;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
using System;
|
||||
using System.Buffers.Binary;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common.MusicDecryption;
|
||||
using ZonyLrcTools.Common.MusicDecryption.Kugou;
|
||||
|
||||
namespace ZonyLrcTools.Tests.Infrastructure.MusicDecryption
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用独立合成数据验证 KGG 解密边界,不代表真实客户端样本。
|
||||
/// </summary>
|
||||
public sealed class KggRegressionTests : IDisposable
|
||||
{
|
||||
private const string Ekey = "AQIDBAUGBwg0ENpQsPOCXXtClrT99x6WMpfYT1U/+p8=";
|
||||
private readonly string _directory = Directory.CreateTempSubdirectory("zony-kgg-tests-").FullName;
|
||||
|
||||
/// <summary>
|
||||
/// 无填充 Base64 的末组三个字符不能丢掉第二个字节。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Decode_UnpaddedEkey_PreservesEveryKeyByte()
|
||||
{
|
||||
var result = EkeyDecoder.Decode(Ekey.TrimEnd('='), out var invalidCount);
|
||||
|
||||
Assert.Equal(Enumerable.Range(1, 16).Select(value => (byte)value), result);
|
||||
Assert.Equal(0, invalidCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 填充之后还有数据的 Base64 是损坏密钥,不能静默忽略。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Decode_RejectsDataAfterPadding()
|
||||
{
|
||||
Assert.Empty(EkeyDecoder.Decode(Ekey + "AAAA"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// QMC 查表算法使用相同位移量左右移位,不是循环移位。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void MapCipher_UsesReferenceMask()
|
||||
{
|
||||
var cipher = Qmc2Cipher.Create([1, 2, 3, 4, 5, 6, 7, 8]);
|
||||
var data = new byte[8];
|
||||
|
||||
cipher!.Decrypt(data, 0);
|
||||
|
||||
Assert.Equal(new byte[] { 29, 65, 192, 65, 29, 65, 192, 65 }, data);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 合成密文必须还原为预先确定的音频字节。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ConvertAsync_DecryptsSyntheticFile()
|
||||
{
|
||||
var input = CreateKgg();
|
||||
var result = await KggMusicDecryptor.ConvertAsync(input, new KeyProvider());
|
||||
|
||||
Assert.True(result.IsSuccess, result.ErrorMessage);
|
||||
Assert.Equal("fLaCtest-payload"u8.ToArray(), File.ReadAllBytes(result.OutputFilePath!));
|
||||
Assert.Single(Directory.GetFiles(_directory, "*.flac"));
|
||||
Assert.Empty(Directory.GetFiles(_directory, "*.part"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 同名文件不论长度是否相同,都不能覆盖或冒充本次成功结果。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(16)]
|
||||
[InlineData(3)]
|
||||
public async Task ConvertAsync_PreservesExistingOutput(int length)
|
||||
{
|
||||
var input = CreateKgg();
|
||||
var output = Path.ChangeExtension(input, ".flac");
|
||||
var original = Enumerable.Repeat((byte)0x42, length).ToArray();
|
||||
File.WriteAllBytes(output, original);
|
||||
|
||||
var result = await KggMusicDecryptor.ConvertAsync(input, new KeyProvider());
|
||||
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.Equal(original, File.ReadAllBytes(output));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 旧版 KGM 与 KGG 魔数相同,不能将旧格式误送到 KGG 解密器。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(2u)]
|
||||
[InlineData(3u)]
|
||||
public void IsKggFile_DoesNotCaptureLegacyKgm(uint version)
|
||||
{
|
||||
var path = CreateKgg();
|
||||
var data = File.ReadAllBytes(path);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(0x14), version);
|
||||
File.WriteAllBytes(path, data);
|
||||
|
||||
Assert.False(KggMusicDecryptor.IsKggFile(path));
|
||||
Assert.False(new KugouKeyProvider().IsKggFile(path));
|
||||
Assert.Null(new KugouKeyProvider().ReadAudioHash(path));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 不能覆盖另一个任务或程序的临时文件。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ConvertAsync_PreservesUnownedPartialFile()
|
||||
{
|
||||
var input = CreateKgg();
|
||||
var partialPath = Path.ChangeExtension(input, ".flac") + ".part";
|
||||
File.WriteAllText(partialPath, "other conversion");
|
||||
|
||||
var result = await KggMusicDecryptor.ConvertAsync(input, new KeyProvider());
|
||||
|
||||
Assert.True(result.IsSuccess, result.ErrorMessage);
|
||||
Assert.Equal("other conversion", File.ReadAllText(partialPath));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 音频偏移不能指向头部或文件末尾之外。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(0u)]
|
||||
[InlineData(1023u)]
|
||||
[InlineData(uint.MaxValue)]
|
||||
public async Task ConvertAsync_RejectsInvalidAudioOffset(uint offset)
|
||||
{
|
||||
var input = CreateKgg(offset);
|
||||
|
||||
var result = await KggMusicDecryptor.ConvertAsync(input, new KeyProvider());
|
||||
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.Single(Directory.GetFiles(_directory));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 损坏的音频头不能默认为 MP3 并报告成功。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ConvertAsync_RejectsUnknownAudioHeader()
|
||||
{
|
||||
var input = CreateKgg();
|
||||
var bytes = File.ReadAllBytes(input);
|
||||
bytes[1024] ^= 0xFF;
|
||||
File.WriteAllBytes(input, bytes);
|
||||
|
||||
var result = await KggMusicDecryptor.ConvertAsync(input, new KeyProvider());
|
||||
|
||||
Assert.False(result.IsSuccess);
|
||||
Assert.Single(Directory.GetFiles(_directory));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查找密钥期间取消后,不应继续发布输出文件。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ConvertAsync_CancellationDoesNotPublishOutput()
|
||||
{
|
||||
var input = CreateKgg();
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() =>
|
||||
KggMusicDecryptor.ConvertAsync(input, new KeyProvider(cancellation.Cancel), cancellation.Token));
|
||||
|
||||
Assert.Single(Directory.GetFiles(_directory));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除本测试创建的数据。
|
||||
/// </summary>
|
||||
public void Dispose() => Directory.Delete(_directory, true);
|
||||
|
||||
private string CreateKgg(uint offset = 1024)
|
||||
{
|
||||
var encryptedAudio = Convert.FromHexString("59CEA1024B24B3F612F2A138532EA1E6");
|
||||
var data = new byte[1024 + encryptedAudio.Length];
|
||||
Convert.FromHexString("7CD532EB86027F4BA8AFA68E0FFF9914").CopyTo(data, 0);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(0x10), offset);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(0x14), 5);
|
||||
BinaryPrimitives.WriteUInt32LittleEndian(data.AsSpan(0x44), 32);
|
||||
"0123456789abcdef0123456789abcdef"u8.CopyTo(data.AsSpan(0x48));
|
||||
encryptedAudio.CopyTo(data, 1024);
|
||||
var path = Path.Combine(_directory, "song.kgg");
|
||||
File.WriteAllBytes(path, data);
|
||||
return path;
|
||||
}
|
||||
|
||||
private sealed class KeyProvider(Action? onFind = null) : IKugouKeyProvider
|
||||
{
|
||||
public string DatabasePath => "synthetic-key-source";
|
||||
public void SetDatabasePath(string? path) => throw new NotSupportedException();
|
||||
public KugouDatabaseInfo Probe() => new(true, DatabasePath, 1, "合成密钥");
|
||||
public void Invalidate() => throw new NotSupportedException();
|
||||
public bool IsKggFile(string filePath) => throw new NotSupportedException();
|
||||
public string? ReadAudioHash(string filePath) => throw new NotSupportedException();
|
||||
public string? FindKey(string audioHash)
|
||||
{
|
||||
onFind?.Invoke();
|
||||
return audioHash == "0123456789abcdef0123456789abcdef" ? Ekey : null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.IO;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Shouldly;
|
||||
@@ -7,16 +8,31 @@ using ZonyLrcTools.Common.MusicDecryption;
|
||||
|
||||
namespace ZonyLrcTools.Tests.Infrastructure.MusicDecryption
|
||||
{
|
||||
/// <summary>
|
||||
/// 使用真实 NCM 样本验证解密。
|
||||
/// </summary>
|
||||
public class NcmMusicDecryptorTests : TestBase
|
||||
{
|
||||
/// <summary>
|
||||
/// 每次使用独立目录,避免历史输出影响解密结果。
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ConvertMusicAsync_Test()
|
||||
public async Task ConvertMusicAsync_DecryptsNcmAsync()
|
||||
{
|
||||
var decryptor = ServiceProvider.GetRequiredService<IMusicDecryptor>();
|
||||
var ncmFilePath = Path.Combine(Directory.GetCurrentDirectory(), "MusicFiles", "Loren Gray - Queen.ncm");
|
||||
var directory = Directory.CreateTempSubdirectory("zony-ncm-tests-").FullName;
|
||||
try
|
||||
{
|
||||
var decryptor = ServiceProvider.GetRequiredService<IMusicDecryptor>();
|
||||
var ncmFilePath = Path.Combine(directory, "Loren Gray - Queen.ncm");
|
||||
File.Copy(Path.Combine(AppContext.BaseDirectory, "MusicFiles", "Loren Gray - Queen.ncm"), ncmFilePath);
|
||||
|
||||
var result = await decryptor.ConvertMusicAsync(ncmFilePath);
|
||||
result.IsSuccess.ShouldBeTrue();
|
||||
var result = await decryptor.ConvertMusicAsync(ncmFilePath);
|
||||
result.IsSuccess.ShouldBeTrue(result.ErrorMessage);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(directory, recursive: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Xunit;
|
||||
using ZonyLrcTools.Common.Infrastructure.Network;
|
||||
|
||||
namespace ZonyLrcTools.Tests.Infrastructure.Network;
|
||||
|
||||
/// <summary>
|
||||
/// 验证等待服务器响应时可以取消请求。
|
||||
/// </summary>
|
||||
public class WarpHttpCancellationTests
|
||||
{
|
||||
/// <summary>
|
||||
/// 服务端未响应时,取消操作应及时结束请求。
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task CancelsPendingRequestAsync(bool isPost)
|
||||
{
|
||||
using var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
var endpoint = (IPEndPoint)listener.LocalEndpoint;
|
||||
var url = $"http://127.0.0.1:{endpoint.Port}/";
|
||||
using var cancellation = new CancellationTokenSource();
|
||||
var client = new DefaultWarpHttpClient(new LocalClientFactory());
|
||||
var request = SendRequestAsync(client, url, isPost, cancellation.Token);
|
||||
|
||||
using var connection = await listener.AcceptTcpClientAsync().WaitAsync(TimeSpan.FromSeconds(5));
|
||||
cancellation.Cancel();
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => request.WaitAsync(TimeSpan.FromSeconds(5)));
|
||||
}
|
||||
|
||||
private static async Task SendRequestAsync(IWarpHttpClient client, string url, bool isPost,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (isPost)
|
||||
{
|
||||
using var response = await client.PostReturnHttpResponseAsync(url, cancellationToken: cancellationToken);
|
||||
}
|
||||
else
|
||||
{
|
||||
await client.GetAsync(url, cancellationToken: cancellationToken);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class LocalClientFactory : IHttpClientFactory
|
||||
{
|
||||
public HttpClient CreateClient(string name)
|
||||
{
|
||||
return new HttpClient(new SocketsHttpHandler { UseProxy = false });
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user