using System.Diagnostics; using System.Collections.Concurrent; using System.Globalization; using System.IO; using System.Net; using System.Net.Http; using System.Text; using System.Text.Json; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Threading; using XFEToolBox.Tools.BilibiliDanmaku; namespace BilibiliDanmaku.Validation; internal static partial class Program { private static string root = ""; private static int passed, failed; private static readonly List results = []; private static readonly string Bvid = "BV1xx411c7mD"; private static readonly List dispatcherErrors = []; private static readonly string Workspace = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "XFEToolBox", "CrossVersion", "EditorWorkspaces", "BilibiliDanmaku"); [STAThread] private static int Main(string[] args) { root = Path.GetFullPath(args.FirstOrDefault(x => !x.StartsWith("--")) ?? Path.Combine("artifacts", "bilibili-danmaku", DateTime.Now.ToString("yyyyMMdd-HHmmss"))); Directory.CreateDirectory(root); var app = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown }; app.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("/XFEToolBox.WpfCore;component/Resources/Style/ToolThemeResources.xaml", UriKind.Relative) }); app.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("/XFEToolBox;component/Resources/Style/MainStyle.xaml", UriKind.Relative) }); app.DispatcherUnhandledException += (_, e) => { dispatcherErrors.Add(e.Exception); e.Handled = true; }; var bindings = new StringWriter(); PresentationTraceSources.DataBindingSource.Listeners.Add(new TextWriterTraceListener(bindings)); PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error; app.Dispatcher.InvokeAsync(async () => { try { await Services(); await Pages(); if (args.Contains("--live")) await Live(); if (args.Contains("--package")) await Package(); await Test("No WPF binding or dispatcher errors", () => { Check(dispatcherErrors.Count == 0, string.Join("\n", dispatcherErrors)); Check(bindings.ToString().Length == 0, bindings.ToString()); }); } catch (Exception e) { failed++; Console.WriteLine(e); } finally { File.WriteAllText(Path.Combine(root, "results.json"), JsonSerializer.Serialize(new { passed, failed, results }, new JsonSerializerOptions { WriteIndented = true })); Console.WriteLine($"RESULT {passed} passed / {failed} failed: {root}"); app.Shutdown(); } }); app.Run(); return failed == 0 ? 0 : 1; } private static void Check(bool condition, string message) { if (!condition) throw new InvalidOperationException(message); } private static void Equal(T expected, T actual) => Check(EqualityComparer.Default.Equals(expected, actual), $"Expected {expected}, got {actual}"); private static void Throws(Action action) where T : Exception { try { action(); } catch (T) { return; } throw new InvalidOperationException("Expected " + typeof(T).Name); } private static async Task ThrowsAsync(Func action) where T : Exception { try { await action(); } catch (T) { return; } throw new InvalidOperationException("Expected " + typeof(T).Name); } private static async Task RejectAsync(Func action) { try { await action(); } catch (Exception e) when (e is InvalidDataException or HttpRequestException or FormatException) { return; } throw new InvalidOperationException("Expected rejection"); } private static Task Test(string name, Action action) => Test(name, () => { action(); return Task.CompletedTask; }); private static async Task Test(string name, Func action) { var timer = Stopwatch.StartNew(); try { await action(); passed++; results.Add(new { name, pass = true, milliseconds = timer.ElapsedMilliseconds }); Console.WriteLine("PASS " + name); } catch (Exception e) { failed++; results.Add(new { name, pass = false, error = e.ToString() }); Console.WriteLine("FAIL " + name + ": " + e); } } private static DanmakuItem Item(string id = "1", long ms = 1000, string text = "测试弹幕 中文 🎬", string hash = "") => new(id, ms, text, 1, 0xffffff, 1735689600, hash); private static byte[] Packet(params DanmakuItem[] items) { var data = new List(); foreach (var item in items) { var row = new List(); Number(row, 1, ulong.TryParse(item.Id, out var id) ? id : 0); Number(row, 2, (ulong)item.PositionMs); Number(row, 3, (ulong)item.Mode); Number(row, 5, item.Color); Field(row, 6, Encoding.UTF8.GetBytes(item.MidHash)); Field(row, 7, Encoding.UTF8.GetBytes(item.Content)); Number(row, 8, (ulong)item.SentAt); Field(row, 12, Encoding.UTF8.GetBytes(item.Id)); Number(row, 99, 42); Field(data, 1, row.ToArray()); } return data.ToArray(); } private static void Varint(List b, ulong value) { while (value >= 128) { b.Add((byte)(value | 128)); value >>= 7; } b.Add((byte)value); } private static void Number(List b, int field, ulong value) { Varint(b, (ulong)(field << 3)); Varint(b, value); } private static void Field(List b, int field, byte[] value) { Varint(b, (ulong)(field << 3 | 2)); Varint(b, (ulong)value.Length); b.AddRange(value); } private static HttpResponseMessage Response(byte[] data, HttpStatusCode status = HttpStatusCode.OK) => new(status) { Content = new ByteArrayContent(data) }; private static HttpResponseMessage Metadata() => Response(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { code = 0, data = new { bvid = Bvid, title = "测试视频 · 中文", owner = new { mid = 123, name = "不是弹幕发送者" }, pages = new[] { new { cid = 62131, page = 1, part = "第一 P", duration = 420 }, new { cid = 62132, page = 2, part = "第二 P", duration = 200 } } } }))); private static HttpResponseMessage ProfileMetadata(object? mid = null, string face = "https://i0.hdslb.com/bfs/face/fixture.png") => Response(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { code = 0, data = new { card = new { mid = mid ?? "123", name = "公开昵称 🎬", face, sign = "公开简介\n第二行", level_info = new { current_level = 6 }, fans = 321L }, follower = 12345L } }))); private sealed class Handler(Func> respond) : HttpMessageHandler { public List Requests { get; } = []; protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Requests.Add(request.RequestUri!); Check(request.Headers.Authorization is null && !request.Headers.Contains("Cookie"), "Unexpected credentials"); return respond(request, cancellationToken); } } private sealed class InlineProgress(Action onProgress) : IProgress { public void Report(LoadProgress value) => onProgress(value); } private sealed class InlineBatchProgress(Action onProgress) : IProgress { public void Report(MidHashBatchProgress value) => onProgress(value); } private sealed class InlineCandidateProgress(Action onProgress) : IProgress { public void Report(CandidateProfileProgress value) => onProgress(value); } // Independent reference: reflected CRC-32/ISO-HDLC, one bit at a time; no production tables or reversal helpers. private static string ReferenceMidHash(long uid) => ReferenceMidHashText(uid.ToString(CultureInfo.InvariantCulture)); private static string ReferenceMidHashText(string text) { uint crc = uint.MaxValue; foreach (byte value in Encoding.ASCII.GetBytes(text)) { crc ^= value; for (int bit = 0; bit < 8; bit++) crc = (crc >> 1) ^ ((crc & 1) == 0 ? 0u : 0xedb88320u); } return (~crc).ToString("x8", CultureInfo.InvariantCulture); } private static void CandidateSet(string hash, params long[] expected) { var actual = MidHashResolver.Resolve(hash); Check(actual.SequenceEqual(expected.Order()), $"Unexpected complete candidate set for {hash}: {string.Join(", ", actual)}"); Equal(actual.Count, actual.Distinct().Count()); uint target = uint.Parse(hash.Trim(), NumberStyles.HexNumber, CultureInfo.InvariantCulture); foreach (long uid in actual) { Check(uid >= 1 && uid <= MidHashResolver.MaximumUid, "Candidate exceeds UID search boundaries"); Equal(target, uint.Parse(ReferenceMidHash(uid), NumberStyles.HexNumber, CultureInfo.InvariantCulture)); } } private static async Task Services() { await Test("BV / full URL / selected P / short URL validation", () => { Equal(Bvid, BilibiliClient.ParseInput(Bvid).Bvid); Equal(Bvid, BilibiliClient.ParseInput("\"https://www.bilibili.com/video/" + Bvid + "/?p=2&vd_source=ignored\"").Bvid); Equal(2, BilibiliClient.ParseInput("https://m.bilibili.com/video/" + Bvid + "?p=2").Page); Check(BilibiliClient.ParseInput("b23.tv/AbCd").ShortLink is not null, "Short link"); }); await Test("Untrusted hosts, protocols, credentials and malformed IDs rejected", () => { foreach (string bad in new[] { "", "BVbroken", "https://evil.example/video/" + Bvid, "https://www.bilibili.com.evil.example/video/" + Bvid, "file:///C:/a", "https://user:secret@www.bilibili.com/video/" + Bvid, "https://www.bilibili.com:444/video/" + Bvid, "https://www.bilibili.com/video/" + Bvid + "?p=-1", "https://b23.tv/../a/b" }) Throws(() => BilibiliClient.ParseInput(bad)); }); await Test("Playback-time parsing including milliseconds and invalid boundaries", () => { Equal(90500, DanmakuFilter.ParseTime("1:30.500")); Equal(3600123, DanmakuFilter.ParseTime("01:00:00.123")); Equal(90000, DanmakuFilter.ParseTime("90")); Equal(null, DanmakuFilter.ParseTime("")); foreach (string t in new[] { "-1", "NaN", "1:60", "1.5:20", "1:2:3:4", "1e9", "99999999999999999999999999", "abc" }) Throws(() => DanmakuFilter.ParseTime(t)); }); await Test("Protobuf exact IDs, Unicode, unknown fields and raw midHash without identity inference", () => { var original = Item("9223372036854775807", 60555, hash: "00AbCdEF"); var rows = DanmakuParser.ParseSegment(Packet(original)); Equal(original, rows.Single()); Equal("未公开", rows[0].SenderText); Equal("00AbCdEF", rows[0].MidHash); Check(rows[0].Detail.Contains("00AbCdEF"), "Hash is missing from detail"); Equal("00:01:00.555", rows[0].PositionText); Equal("未提供", (Item() with { SentAt = long.MaxValue }).SentText); }); await Test("midHash validity, raw malformed values and bounded parser field", () => { foreach (string good in new[] { "0", "a", "0000000a", "0972D361", "ffffffff", " 83DCEFB7 " }) Check(MidHashResolver.IsValidHash(good), "Valid hash rejected: " + good); foreach (string? bad in new string?[] { null, "", " ", "0x123456", "123456789", "-1", "+1", "g", "12 34", "12", "1\n2" }) { Check(!MidHashResolver.IsValidHash(bad), "Invalid hash accepted: " + bad); Throws(() => MidHashResolver.Resolve(bad!)); } string malformed = new('x', 64); Equal(malformed, DanmakuParser.ParseSegment(Packet(Item(hash: malformed))).Single().MidHash); Throws(() => DanmakuParser.ParseSegment(Packet(Item(hash: malformed + "x")))); }); await Test("CRC32 reference vectors, complete MITM collisions and UID boundaries", () => { Equal(9_999_999_999L, MidHashResolver.MaximumUid); Equal("83dcefb7", ReferenceMidHash(1)); Equal("884863d2", ReferenceMidHash(123)); Equal("0972d361", ReferenceMidHash(123456)); Equal("2adbffce", ReferenceMidHash(MidHashResolver.MaximumUid)); // Full sets independently precomputed with Python zlib and exhaustive decimal meet-in-the-middle. CandidateSet("83dcefb7", 1, 1_146_140_827, 2_422_059_385, 8_630_450_571); CandidateSet("884863d2", 123); CandidateSet(" 972D361 ", 123456, 2_088_160_976, 3_061_779_183, 8_223_934_876, 8_395_766_326, 9_273_370_777); CandidateSet("2adbffce", 4_959_604_151, 5_295_997_110, 9_999_999_999); CandidateSet("0", 863_045_057, 2_292_307_566, 2_915_035_893, 3_374_711_137); CandidateSet("0000000a"); CandidateSet(ReferenceMidHash(0), 1_146_140_826, 2_422_059_384, 8_630_450_570); CandidateSet(ReferenceMidHash(10_000_000_000), 4_035_279_871, 4_121_693_660); }); await Test("midHash resolution honors cancellation without returning a partial candidate set", async () => { using var canceled = new CancellationTokenSource(); canceled.Cancel(); Throws(() => MidHashResolver.Resolve("83dcefb7", canceled.Token)); using var cancel = new CancellationTokenSource(); using var entered = new ManualResetEventSlim(); Task pending = Task.Factory.StartNew(() => { entered.Set(); MidHashResolver.Resolve("deadbeef", cancel.Token); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); Check(entered.Wait(TimeSpan.FromSeconds(2)), "Resolver worker did not start"); cancel.Cancel(); try { await pending.WaitAsync(TimeSpan.FromSeconds(2)); throw new InvalidOperationException("Canceled resolution returned success"); } catch (OperationCanceledException) { } }); await Test("Batch midHash normalization, invalid skipping, deduplication and complete candidates", async () => { Equal("0972d361", MidHashResolver.NormalizeHash(" 972D361 ")); Equal("00000000", MidHashResolver.NormalizeHash("0")); Equal("83dcefb7", MidHashResolver.NormalizeHash("83DCEFB7")); foreach (string invalid in new[] { "", "bad-hash", "123456789", "0x123" }) Throws(() => MidHashResolver.NormalizeHash(invalid)); Check(MidHashBatchResolver.WorkerCount is >= 1 and <= 8, "Worker count exceeds the bounded CPU parallelism"); var progress = new ConcurrentQueue(); var result = await MidHashBatchResolver.ResolveAsync(["83DCEFB7", " 83dcefb7 ", "972d361", "0972D361", "0000000a", "A", "invalid", "", null!], new InlineBatchProgress(progress.Enqueue), default); Equal(3, result.Total); Equal(3, result.Matches.Count); Check(!result.Canceled, "Completed batch was marked canceled"); Check(result.Matches.Keys.Order().SequenceEqual(new[] { "0000000a", "0972d361", "83dcefb7" }), "Batch keys were not normalized and deduplicated"); Check(result.Matches["83dcefb7"].SequenceEqual(new long[] { 1, 1_146_140_827, 2_422_059_385, 8_630_450_571 }), "Batch lost a collision or returned unsorted candidates"); Check(result.Matches["0972d361"].SequenceEqual(new long[] { 123456, 2_088_160_976, 3_061_779_183, 8_223_934_876, 8_395_766_326, 9_273_370_777 }), "Batch candidate set differs from the independent complete vector"); Equal(0, result.Matches["0000000a"].Count); Check(progress.Any(p => p.Completed == result.Total && p.Total == result.Total), "Batch never reported completion"); Check(progress.All(p => p.Total == result.Total && p.Completed >= 0 && p.Completed <= result.Total), "Batch progress exceeded its normalized total"); var empty = await MidHashBatchResolver.ResolveAsync(["invalid", "", null!], null, default); Equal(0, empty.Total); Equal(0, empty.Matches.Count); Check(!empty.Canceled, "Empty valid input was treated as a failure"); await ThrowsAsync(() => MidHashBatchResolver.ResolveAsync(Enumerable.Range(0, 100001).Select(i => i.ToString("x8", CultureInfo.InvariantCulture)))); }); await Test("Batch cancellation retains only complete verified hash results", async () => { string[] hashes = Enumerable.Range(1000, 128).Select(i => ReferenceMidHash(i)).ToArray(); using var canceled = new CancellationTokenSource(); canceled.Cancel(); var empty = await MidHashBatchResolver.ResolveAsync(hashes, null, canceled.Token); Check(empty.Canceled && empty.Matches.Count == 0, "Pre-canceled batch performed work or reported success"); using var cancel = new CancellationTokenSource(); var result = await MidHashBatchResolver.ResolveAsync(hashes, new InlineBatchProgress(p => { if (p.Completed >= 1) cancel.Cancel(); }), cancel.Token); Check(result.Canceled && result.Matches.Count >= 1 && result.Matches.Count <= result.Total, "Cancellation lost completed hashes or exceeded the normalized total"); Equal(hashes.Distinct().Count(), result.Total); foreach (var (hash, candidates) in result.Matches) { Equal(MidHashResolver.NormalizeHash(hash), hash); Check(candidates.SequenceEqual(MidHashResolver.Resolve(hash)), "A canceled batch retained a partial hash result"); foreach (long uid in candidates) Equal(hash, ReferenceMidHash(uid)); } }); await Test("Truncated / overflow / illegal protobuf rejected", () => { foreach (byte[] bad in new byte[][] { [0], [10, 127], [10, 2, 16, 128], [10, 2, 8, 255], [15], [255,255,255,255,255,255,255,255,255,2], [8,1] }) Throws(() => DanmakuParser.ParseSegment(bad)); Equal(0, DanmakuParser.ParseSegment([]).Count); }); await Test("XML adjacent records, entities, millisecond time and no identity inference", () => { using var input = new MemoryStream(Encoding.UTF8.GetBytes("中文 & <test>next")); var rows = DanmakuParser.ParseXml(input); Equal(2, rows.Count); Equal(1125L, rows[0].PositionMs); Equal("中文 & ", rows[0].Content); Equal("顶部", rows[1].ModeText); Equal("未公开", rows[1].SenderText); Equal("not-a-uid", rows[0].MidHash); Equal("123", rows[1].MidHash); Check(!MidHashResolver.IsValidHash(rows[0].MidHash), "Malformed raw hash should be preserved but cannot resolve"); }); await Test("XML preserves raw hash whitespace/case and bounds field length", () => { using var input = new MemoryStream(Encoding.UTF8.GetBytes("hash")); Equal(" 00AbCdEF ", DanmakuParser.ParseXml(input).Single().MidHash); using var tooLong = new MemoryStream(Encoding.UTF8.GetBytes("x")); Throws(() => DanmakuParser.ParseXml(tooLong)); }); await Test("XML external entities and malformed data blocked", () => { foreach (string bad in new[] { "]>&x;", "", "x", "x" }) { bool rejected = false; try { using var stream = new MemoryStream(Encoding.UTF8.GetBytes(bad)); DanmakuParser.ParseXml(stream); } catch (Exception e) when (e is System.Xml.XmlException or InvalidDataException) { rejected = true; } Check(rejected, "Malformed XML accepted"); } }); await Test("Combined literal keyword / inclusive video-time / local send-date filters", () => { var date = DateTimeOffset.FromUnixTimeSeconds(1735689600).LocalDateTime.Date; var rows = new[] { Item("1", 999, "HELLO"), Item("2", 1000, "hello中文"), Item("3", 2000, "HeLLo"), Item("4", 2001, "hello"), Item("5", 1500, ".*not regex") }; Equal(2, new DanmakuFilter("hello", 1000, 2000, date, date).Apply(rows).Count); Equal(1, new DanmakuFilter(".*", null, null, null, null).Apply(rows).Count); Equal(0, new DanmakuFilter("", null, null, date.AddDays(1), null).Apply(rows).Count); Throws(() => new DanmakuFilter("", 2000, 1000, null, null).Validate()); Throws(() => new DanmakuFilter("", null, null, date, date.AddDays(-1)).Validate()); }); await Test("CSV escaping and spreadsheet-formula guard; JSON null sender and exact ID", () => { string csv = DanmakuExport.Csv([Item(text: "=HYPERLINK(\"bad\")", hash: "83dcefb7"), Item(text: "a,b\n\"c\"")]); Check(csv.Contains("'="), "Formula not escaped"); Check(csv.Contains("\"a,b\n\"\"c\"\"\""), "CSV escape"); Check(csv.Contains("midHash") && csv.Contains("83dcefb7"), "CSV raw hash field missing"); string json = DanmakuExport.Json([Item("9223372036854775807", hash: "83dcefb7")], "test", "partial"); using var document = JsonDocument.Parse(json); Equal(JsonValueKind.Null, document.RootElement.GetProperty("items")[0].GetProperty("sender").ValueKind); Equal("83dcefb7", document.RootElement.GetProperty("items")[0].GetProperty("midHash").GetString()); Check(json.Contains("9223372036854775807") && !json.Contains("1146140827"), "Export inferred identity from a CRC collision"); }); await Test("Metadata + P selection + uploader is never used as sender", async () => { using var client = new BilibiliClient(new Handler((_, _) => Task.FromResult(Metadata()))); var video = await client.GetVideoAsync("https://www.bilibili.com/video/" + Bvid + "?p=2", default); Equal(2, video.Parts.Count); Equal(2, video.RequestedPage); }); await Test("Short-link redirect to verified video only", async () => { var handler = new Handler((r, _) => { if (r.RequestUri!.Host == "b23.tv") { var response = new HttpResponseMessage(HttpStatusCode.Found); response.Headers.Location = new Uri("https://www.bilibili.com/video/" + Bvid + "?p=2"); return Task.FromResult(response); } return Task.FromResult(Metadata()); }); using var client = new BilibiliClient(handler); Equal(2, (await client.GetVideoAsync("https://b23.tv/test", default)).RequestedPage); Equal(2, handler.Requests.Count); }); await Test("External short-link redirect blocked before network request", async () => { var handler = new Handler((_, _) => { var r = new HttpResponseMessage(HttpStatusCode.Found); r.Headers.Location = new Uri("https://evil.example/"); return Task.FromResult(r); }); using var client = new BilibiliClient(handler); await RejectAsync(() => client.GetVideoAsync("https://b23.tv/test", default)); Equal(1, handler.Requests.Count); }); await Test("Unavailable video / invalid page / login required handled", async () => { using (var client = new BilibiliClient(new Handler((_, _) => Task.FromResult(Response(Encoding.UTF8.GetBytes("{\"code\":-404}")))))) await RejectAsync(() => client.GetVideoAsync(Bvid, default)); using (var client = new BilibiliClient(new Handler((_, _) => Task.FromResult(Metadata())))) await RejectAsync(() => client.GetVideoAsync("https://www.bilibili.com/video/" + Bvid + "?p=99", default)); }); await Test("Segment merge deduplicates IDs, keeps same-text comments, clips exact range", async () => { var handler = new Handler((r, _) => Task.FromResult(Response(r.RequestUri!.Query.Contains("segment_index=1") ? Packet(Item("1", 1000), Item("2", 360000)) : Packet(Item("2", 360000), Item("3", 360000), Item("4", 400000))))); using var client = new BilibiliClient(handler); var result = await client.GetDanmakuAsync(new(62131, 1, "test", 420), 1000, 360000, null, default); Equal(3, result.Items.Count); Equal(2, result.Completed); Check(result.Complete, "Complete result expected"); }); await Test("HTTP 412 after a segment yields partial results, no bypass or retry storm", async () => { var handler = new Handler((r, _) => Task.FromResult(r.RequestUri!.Query.Contains("segment_index=1") ? Response(Packet(Item())) : Response([], HttpStatusCode.PreconditionFailed))); using var client = new BilibiliClient(handler); var r = await client.GetDanmakuAsync(new(62131, 1, "test", 420), null, null, null, default); Equal(1, r.Items.Count); Check(!r.Complete && r.Warning!.Contains("412"), "Partial/error status missing"); Equal(2, handler.Requests.Count); }); await Test("Cancellation keeps completed segments and stops further requests", async () => { using var cancel = new CancellationTokenSource(); var handler = new Handler((_, _) => Task.FromResult(Response(Packet(Item())))); using var client = new BilibiliClient(handler); var r = await client.GetDanmakuAsync(new(62131, 1, "test", 1000), null, null, new InlineProgress(p => { if (p.Completed == 1) cancel.Cancel(); }), cancel.Token); Check(r.Canceled && !r.Complete, "Cancellation not propagated"); Equal(1, r.Items.Count); Equal(1, handler.Requests.Count); }); await Test("Network failure / JSON restriction / body limit never reported as empty success", async () => { foreach (int kind in new[] { 0, 1, 2 }) { var handler = new Handler((_, _) => { if (kind == 0) throw new HttpRequestException("test offline"); var response = Response(kind == 1 ? Encoding.UTF8.GetBytes("{\"code\":-352}") : []); if (kind == 2) response.Content.Headers.ContentLength = DanmakuParser.MaximumBytes + 1; return Task.FromResult(response); }); using var client = new BilibiliClient(handler); var r = await client.GetDanmakuAsync(new(62131, 1, "test", 100), null, null, null, default); Check(!r.Complete && r.Warning is not null, "False empty success"); Equal(0, r.Completed); } }); await Test("Large video bounded requests; narrow range skips unrelated segments", async () => { var handler = new Handler((_, _) => Task.FromResult(Response([]))); using var client = new BilibiliClient(handler); await RejectAsync(async () => await client.GetDanmakuAsync(new(62131, 1, "test", 80000), null, null, null, default)); Equal(0, handler.Requests.Count); var r = await client.GetDanmakuAsync(new(62131, 1, "test", 80000), 720000, 720100, null, default); Check(r.Complete, "Empty segment should succeed"); Equal(1, handler.Requests.Count); Check(handler.Requests[0].Query.Contains("segment_index=3"), "Wrong segment"); }); await Test("100k records filter without UI-thread work", async () => { var data = Enumerable.Range(1, 100000).Select(i => Item(i.ToString(), i * 100L, i % 10 == 0 ? "needle" : "other")).ToArray(); var timer = Stopwatch.StartNew(); var result = await Task.Run(() => new DanmakuFilter("NEEDLE", null, null, null, null).Apply(data)); Equal(10000, result.Count); Check(timer.Elapsed < TimeSpan.FromSeconds(5), "Filter unexpectedly slow"); }); await Test("Accumulated large-text responses stop at memory budget with partial status", async () => { int segment = 0; string longText = new('x', 65536); var handler = new Handler((_, _) => { int offset = segment++ * 200; var rows = Enumerable.Range(offset + 1, 200).Select(i => Item(i.ToString(), i * 1000, longText)).ToArray(); return Task.FromResult(Response(Packet(rows))); }); using var client = new BilibiliClient(handler); var result = await client.GetDanmakuAsync(new(62131, 1, "test", 1800), null, null, null, default); Check(!result.Complete && result.Warning!.Contains("64 MiB"), "Missing retained-memory limit"); Check(result.Items.Sum(x => (long)(x.Content.Length + x.Id.Length) * 2) <= BilibiliClient.MaximumRetainedTextBytes, "Retained text exceeds budget"); Equal(3, handler.Requests.Count); }); await Test("Public profile card requests, typed fields and canonical homepage without credentials", async () => { foreach (object mid in new object[] { "123", 123L }) { var handler = new Handler((request, _) => { Equal(HttpMethod.Get, request.Method); Equal("https", request.RequestUri!.Scheme); Equal("api.bilibili.com", request.RequestUri.Host); Equal("/x/web-interface/card", request.RequestUri.AbsolutePath); Equal("?mid=123", request.RequestUri.Query); return Task.FromResult(ProfileMetadata(mid)); }); using var client = new BilibiliProfileClient(handler); var profile = await client.GetProfileAsync(123, default); Equal(123L, profile.Uid); Equal("公开昵称 🎬", profile.Name); Equal("公开简介\n第二行", profile.Signature); Equal(6, profile.Level); Equal(12345, profile.Followers); Equal("https://space.bilibili.com/123", profile.ProfileUrl); Equal("https://i0.hdslb.com/bfs/face/fixture.png", profile.AvatarUrl); Equal(1, handler.Requests.Count); } const long boundaryUid = 9_999_999_999; var boundaryHandler = new Handler((request, _) => { Equal("?mid=9999999999", request.RequestUri!.Query); return Task.FromResult(ProfileMetadata(boundaryUid)); }); using var boundaryClient = new BilibiliProfileClient(boundaryHandler); var boundary = await boundaryClient.GetProfileAsync(boundaryUid, default); Equal(boundaryUid, boundary.Uid); Equal("https://space.bilibili.com/9999999999", boundary.ProfileUrl); }); await Test("Profile optional fields, fans fallback and avatar URL restrictions", async () => { foreach (string face in new[] { "", "https://evil.example/avatar.png", "https://i0.hdslb.com.evil.example/a", "https://user:secret@i0.hdslb.com/a", "file:///C:/a", "https://i0.hdslb.com:444/a" }) { using var client = new BilibiliProfileClient(new Handler((_, _) => Task.FromResult(ProfileMetadata(face: face)))); Equal("", (await client.GetProfileAsync(123, default)).AvatarUrl); } using (var client = new BilibiliProfileClient(new Handler((_, _) => Task.FromResult(ProfileMetadata(face: "http://i1.hdslb.com/bfs/face/a.png"))))) Equal("https://i1.hdslb.com/bfs/face/a.png", (await client.GetProfileAsync(123, default)).AvatarUrl); using (var client = new BilibiliProfileClient(new Handler((_, _) => Task.FromResult(Response(Encoding.UTF8.GetBytes("{\"code\":0,\"data\":{\"card\":{\"mid\":\"123\",\"name\":\"minimal\",\"fans\":7}}}")))))) { var profile = await client.GetProfileAsync(123, default); Equal("", profile.AvatarUrl); Equal("", profile.Signature); Equal(null, profile.Level); Equal(7, profile.Followers); } }); await Test("Profile invalid UID, mismatched identity, malformed fields and restricted responses fail clearly", async () => { var handler = new Handler((_, _) => Task.FromResult(ProfileMetadata())); using (var client = new BilibiliProfileClient(handler)) { foreach (long invalid in new[] { 0L, -1L, MidHashResolver.MaximumUid + 1 }) await ThrowsAsync(() => client.GetProfileAsync(invalid, default)); Equal(0, handler.Requests.Count); } foreach (string body in new[] { "{\"code\":-404}", "{\"code\":-352}", "{\"code\":0,\"data\":{}}", "{\"code\":0,\"data\":{\"card\":{\"mid\":124,\"name\":\"mismatch\"}}}", "{\"code\":0,\"data\":{\"card\":{\"mid\":123}}}", "{\"code\":0,\"data\":{\"card\":{\"mid\":123,\"name\":7}}}", "{\"code\":0,\"data\":{\"card\":{\"mid\":123,\"name\":\"x\",\"level_info\":{\"current_level\":7}}}}", "{\"code\":0,\"data\":{\"card\":{\"mid\":123,\"name\":\"x\"},\"follower\":-1}}" }) { using var client = new BilibiliProfileClient(new Handler((_, _) => Task.FromResult(Response(Encoding.UTF8.GetBytes(body))))); await ThrowsAsync(() => client.GetProfileAsync(123, default)); } using (var client = new BilibiliProfileClient(new Handler((_, _) => Task.FromResult(Response([], HttpStatusCode.PreconditionFailed))))) await ThrowsAsync(() => client.GetProfileAsync(123, default)); using (var client = new BilibiliProfileClient(new Handler((_, _) => { var response = Response([]); response.Content.Headers.ContentLength = BilibiliProfileClient.MaximumProfileBytes + 1; return Task.FromResult(response); }))) await ThrowsAsync(() => client.GetProfileAsync(123, default)); }); await Test("Profile request honors caller cancellation", async () => { var handler = new Handler(async (_, token) => { await Task.Delay(30000, token); return ProfileMetadata(); }); using var client = new BilibiliProfileClient(handler); using var cancel = new CancellationTokenSource(); Task pending = client.GetProfileAsync(123, cancel.Token); cancel.Cancel(); await ThrowsAsync(() => pending.WaitAsync(TimeSpan.FromSeconds(2))); Equal(1, handler.Requests.Count); }); await Test("Candidate profile filter deduplicates requests, reuses success and removes invalid cards", async () => { var raw = new Dictionary> { ["0000000a"] = [1, 2, 3], ["0000000b"] = [2, 4], ["0000000c"] = [] }; using var profiles = new FixtureProfileClient((uid, _) => uid == 2 ? Task.FromException(new InvalidDataException("账号不存在")) : Task.FromResult(new BilibiliProfile(uid, "成功 " + uid, "", "", null, null))); var known = new Dictionary { [1] = new(1, "已缓存", "", "", null, null) }; var progress = new ConcurrentQueue(); var result = await new CandidateProfileFilter(profiles, TimeSpan.Zero).FilterAsync(raw, known, new InlineCandidateProgress(progress.Enqueue)); Check(result.Matches["0000000a"].SequenceEqual([1L, 3L]) && result.Matches["0000000b"].SequenceEqual([4L]) && result.Matches["0000000c"].Count == 0, "Visible candidates include an invalid card or omit a successful card"); Check(profiles.Requests.Order().SequenceEqual([2L, 3L, 4L]), "Filter duplicated a UID request or fetched a cached successful profile"); Check(result.Profiles.Keys.Order().SequenceEqual([1L, 3L, 4L]) && result.FailedUids.SequenceEqual([2L]) && result.PendingUids.Count == 0, "Profile result classification is incorrect"); Equal(4, result.Total); Equal(4, result.Completed); Check(!result.Canceled, "Complete profile filter was marked canceled"); Check(progress.Any(p => p.Completed == 4 && p.Total == 4 && p.Succeeded == 3), "Profile filter final progress is missing"); using var mismatchClient = new BilibiliProfileClient(new Handler((_, _) => Task.FromResult(ProfileMetadata(124L)))); var mismatch = await new CandidateProfileFilter(mismatchClient, TimeSpan.Zero).FilterAsync(new Dictionary> { ["0000000d"] = [123] }); Check(mismatch.Matches["0000000d"].Count == 0 && mismatch.FailedUids.Contains(123), "HTTP 200 with a mismatched card mid was kept as a candidate"); }); await Test("Candidate filtering and manual profile reads share bounded concurrency and spacing", async () => { int active = 0, maximum = 0; var starts = new ConcurrentQueue(); using var profiles = new FixtureProfileClient(async (uid, token) => { starts.Enqueue(Stopwatch.GetTimestamp()); int current = Interlocked.Increment(ref active); int previous; do { previous = maximum; if (current <= previous) break; } while (Interlocked.CompareExchange(ref maximum, current, previous) != previous); try { await Task.Delay(35, token); return new BilibiliProfile(uid, "ok", "", "", null, null); } finally { Interlocked.Decrement(ref active); } }); var filter = new CandidateProfileFilter(profiles, TimeSpan.FromMilliseconds(20)); Task batch = filter.FilterAsync(new Dictionary> { ["0000000d"] = [1, 2, 3, 4] }); Task manual = filter.GetProfileAsync(5, default); await Task.WhenAll(batch, manual); Check(maximum is >= 1 and <= 2 && profiles.Requests.Count == 5, "Profile/manual requests exceeded the shared concurrency limit"); long[] ticks = starts.Order().ToArray(); Check(ticks.Zip(ticks.Skip(1), (a, b) => (b - a) / (double)Stopwatch.Frequency).All(seconds => seconds >= .015), "Shared request starts ignored the configured 20 ms interval"); }); await Test("Candidate filtering cancellation and access restrictions retain success and pending UIDs", async () => { using var cancel = new CancellationTokenSource(); using var profiles = new FixtureProfileClient((uid, _) => Task.FromResult(new BilibiliProfile(uid, "ok", "", "", null, null))); var raw = new Dictionary> { ["0000000d"] = [1, 2, 3, 4, 5, 6] }; var result = await new CandidateProfileFilter(profiles, TimeSpan.Zero).FilterAsync(raw, null, new InlineCandidateProgress(p => { if (p.Succeeded > 0) cancel.Cancel(); }), cancel.Token); Check(result.Canceled && result.Profiles.Count >= 1 && result.Matches["0000000d"].Count == result.Profiles.Count, "Cancellation discarded successful candidate cards"); Check(result.Profiles.Keys.All(uid => result.Matches["0000000d"].Contains(uid)) && result.PendingUids.All(uid => !result.Matches["0000000d"].Contains(uid)), "Pending candidates leaked into visible results"); Equal(result.Total, result.Completed + result.PendingUids.Count); using var restricted = new FixtureProfileClient((_, _) => Task.FromException(new HttpRequestException("HTTP 412", null, HttpStatusCode.PreconditionFailed))); var stopped = await new CandidateProfileFilter(restricted, TimeSpan.Zero).FilterAsync(raw, new Dictionary { [1] = new(1, "cached", "", "", null, null) }); Check(stopped.Matches["0000000d"].SequenceEqual([1L]) && stopped.Profiles.ContainsKey(1) && stopped.PendingUids.Count == 5 && stopped.FailedUids.Count == 0 && !string.IsNullOrWhiteSpace(stopped.Warning), "Access restrictions discarded cached success or treated unknown accounts as nonexistent"); Check(restricted.Requests.Count <= 2, "Restricted requests continued through the candidate list"); }); await Test("HTTP 200 platform API failures keep candidates pending and allow a later retry", async () => { foreach (int apiCode in new[] { -500, -9999 }) { bool recovered = false; var handler = new Handler((request, _) => { long uid = long.Parse(request.RequestUri!.Query[5..], CultureInfo.InvariantCulture); return Task.FromResult(recovered ? ProfileMetadata(uid) : Response(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new { code = apiCode })))); }); using var client = new BilibiliProfileClient(handler); var filter = new CandidateProfileFilter(client, TimeSpan.Zero); var raw = new Dictionary> { ["0000000d"] = [1, 2, 3] }; var known = new Dictionary { [1] = new(1, "cached", "", "", null, null) }; var stopped = await filter.FilterAsync(raw, known); Check(stopped.Matches["0000000d"].SequenceEqual([1L]) && stopped.PendingUids.SequenceEqual([2L, 3L]) && stopped.FailedUids.Count == 0 && !stopped.Canceled && !string.IsNullOrWhiteSpace(stopped.Warning), $"HTTP 200 API {apiCode} classified unknown accounts as unavailable"); Check(handler.Requests.Count is >= 1 and <= 2, "Platform failure caused additional bulk account requests"); int previousRequests = handler.Requests.Count; recovered = true; var retried = await filter.FilterAsync(raw, stopped.Profiles); Check(retried.Matches["0000000d"].SequenceEqual([1L, 2L, 3L]) && retried.PendingUids.Count == 0 && retried.FailedUids.Count == 0, "Pending candidates could not recover after the platform error cleared"); Equal(previousRequests + 2, handler.Requests.Count); } }); } private sealed class FixtureClient : IBilibiliClient { public bool Disposed; public Task GetVideoAsync(string input, CancellationToken token) => Task.FromResult(new VideoInfo(Bvid, "测试视频 · 弹幕检索界面验证", [new(1, 1, "第一部分", 900), new(2, 2, "第二部分", 900)], 1)); public Task GetDanmakuAsync(VideoPart part, long? fromMs, long? toMs, IProgress? progress, CancellationToken token) { IReadOnlyList rows = Enumerable.Range(1, 405).Select(i => Item(i.ToString(), i * 1000, i % 2 == 0 ? "这句中文弹幕支持按内容与时间检索 🎬" : "Another comment / 完整原文,不截断详情", i % 2 == 0 ? "b427a317" : "a6920cf9")).ToArray(); return Task.FromResult(new DanmakuResult(rows, 1, 1, false, null, 0, 900000)); } public void Dispose() => Disposed = true; } private sealed class FixtureProfileClient(Func>? respond = null) : IBilibiliProfileClient { private static readonly HashSet Available = [1, 123, 1000, 1001, 2000, 1_146_140_827]; public ConcurrentQueue Requests { get; } = new(); public bool Disposed; public Task GetProfileAsync(long uid, CancellationToken token) { Requests.Enqueue(uid); token.ThrowIfCancellationRequested(); if (respond is not null) return respond(uid, token); return Available.Contains(uid) ? Task.FromResult(new BilibiliProfile(uid, $"测试用户 {uid}", "", "这是用于界面验证的公开资料简介。", 6, 12345)) : Task.FromException(new InvalidDataException("模拟账号不存在:" + uid)); } public void Dispose() => Disposed = true; } private sealed class BatchFixtureClient(int count = 128) : IBilibiliClient { public Task GetVideoAsync(string input, CancellationToken token) => Task.FromResult(new VideoInfo(Bvid, "批量反查验证", [new(1, 1, "P1", 300)], 1)); public Task GetDanmakuAsync(VideoPart part, long? fromMs, long? toMs, IProgress? progress, CancellationToken token) => Task.FromResult(new DanmakuResult(Enumerable.Range(1000, count).Select(uid => Item(uid.ToString(), uid, hash: ReferenceMidHash(uid))).ToArray(), 1, 1, false, null, 0, 300000)); public void Dispose() { } } private static async Task Pages() { await Test("Real WPF page: automatic filtered candidates, profile, paging and screenshots", async () => { var client = new FixtureClient(); var profiles = new FixtureProfileClient(); using var vm = new MainPageViewModel(client, profiles, TimeSpan.Zero); var page = new MainPage(vm); var window = new Window { Content = page, Width = 1260, Height = 800, Left = -16000, Top = -16000, ShowInTaskbar = false, ShowActivated = false, WindowStyle = WindowStyle.None }; window.Show(); await Idle(); vm.Input = Bvid; await vm.QueryCommand.ExecuteAsync(null); await Idle(); Equal(405, vm.LoadedCount); Equal(200, vm.PageItems.Count); Equal(2, vm.BatchTotalCount); Equal(2, vm.BatchResolvedCount); Check(!vm.IsBatchResolving && !vm.IsValidatingCandidates && vm.CandidateValidationCompleted == vm.CandidateValidationTotal && vm.CandidateValidationPassed == 2, "Query did not finish card filtering"); int validatedRequests = profiles.Requests.Count; Check(validatedRequests >= 2 && vm.Profile is null, "Batch must validate metadata without selecting/downloading avatars"); vm.SelectedItem = vm.PageItems[1]; await vm.ProfileLoadTask; await Idle(); Equal(1000L, vm.SelectedUid); Equal(1000L, vm.Profile?.Uid); Equal(1, vm.DetailsTabIndex); Equal(validatedRequests, profiles.Requests.Count); Check(vm.SelectionDetail.Contains("这句中文") && vm.SelectionDetail.Contains(vm.SenderResolutionText), "Copyable details lost filtered candidate state"); var resolve = (Button)page.FindName("ResolveSenderButton"); Check(resolve.Command == vm.ResolveSenderCommand && resolve.IsEnabled, "Resolve retry binding failed"); var picker = (ComboBox)page.FindName("CandidatePicker"); Check(picker.Items.Count == 1 && Equals(picker.SelectedItem, vm.SelectedUid), "Candidate picker includes failed profiles"); Equal("测试用户 1000", ((TextBlock)page.FindName("ProfileNameLabel")).Text); Check(page.FindName("SenderResolutionLabel") is TextBlock && page.FindName("CandidateValidationLabel") is TextBlock && page.FindName("ProfileStatusLabel") is TextBlock && page.FindName("ProfileAvatarImage") is Image, "Profile controls missing"); Check(((Button)page.FindName("CopyUidButton")).Command == vm.CopyUidCommand && ((Button)page.FindName("CopyUidButton")).IsEnabled, "Copy UID binding failed"); Check(((Button)page.FindName("CopyProfileUrlButton")).Command == vm.CopyProfileUrlCommand && ((Button)page.FindName("OpenProfileButton")).Command == vm.OpenProfileCommand, "Homepage action bindings failed"); var grid = (DataGrid)page.FindName("ResultsGrid"); grid.UpdateLayout(); Check(grid.Columns.Count == 4 && grid.IsReadOnly, "Table configuration"); Equal("1000", vm.GetCandidateUidText("B427A317")); Equal("2000", vm.GetCandidateUidText("a6920cf9")); Equal("未提供", vm.GetCandidateUidText(null)); Equal("格式无效", vm.GetCandidateUidText("invalid")); Equal("1000", new CandidateUidConverter().Convert([vm.PageItems[1].MidHash, vm, vm.SenderResultsVersion], typeof(string), null!, CultureInfo.InvariantCulture)); Check(grid.Columns[3].GetCellContent(vm.PageItems[1]) is TextBlock cell && cell.Text == "1000", "Visible UID column did not refresh after profile filtering"); Render(page, "page-profile.png"); Render(page, "page-midhash.png"); Render(page, "page-normal.png"); window.Width = 960; window.Height = 630; await Idle(); Render(page, "page-compact.png"); Check(grid.ActualHeight >= 140, "Compact layout hides comment table"); var scroll = (ScrollViewer)page.FindName("PageScroll"); Check(scroll.ScrollableHeight > 0, "Compact footer is unreachable"); scroll.ScrollToBottom(); await Idle(); Render(page, "page-compact-bottom.png"); vm.NextCommand.Execute(null); Equal(200, vm.PageItems.Count); vm.NextCommand.Execute(null); Equal(5, vm.PageItems.Count); Check(!vm.NextCommand.CanExecute(null), "Page boundary"); vm.Keyword = "中文"; vm.FromText = "00:10"; vm.ToText = "00:30"; await vm.ApplyFilterCommand.ExecuteAsync(null); Equal(11, vm.FilteredCount); vm.SelectedPart = vm.Parts[1]; Equal(0, vm.LoadedCount); Check(!vm.ExportCommand.CanExecute(null), "Stale export after P change"); window.Close(); Check(client.Disposed && profiles.Disposed, "Window did not dispose clients"); }); await Test("XML import automatically filters cards; failed import preserves good data", async () => { string path = Path.Combine(root, "fixture.xml"); File.WriteAllText(path, "XML测试"); var profiles = new FixtureProfileClient(); using var vm = new MainPageViewModel(new FixtureClient(), profiles, TimeSpan.Zero); await vm.ImportFileAsync(path); Equal(1, vm.LoadedCount); Equal(1, vm.BatchTotalCount); Equal(1, vm.BatchResolvedCount); Equal(1, vm.CandidateValidationPassed); Check(!vm.OpenVideoCommand.CanExecute(null), "Imported filename became a browser target"); int requests = profiles.Requests.Count; vm.SelectedItem = vm.PageItems[0]; await vm.ProfileLoadTask; Equal(requests, profiles.Requests.Count); Check(vm.CandidateUids.SequenceEqual([1000L]) && vm.Profile?.Uid == 1000, "Imported row lost validated metadata"); await vm.ImportFileAsync(Path.Combine(root, "does-not-exist.xml")); Equal(1, vm.LoadedCount); Check(vm.Status.StartsWith("操作未完成"), "Import error missing"); }); await Test("Successive XML imports isolate raw candidates and successful profile caches", async () => { string first = Path.Combine(root, "filter-first.xml"), next = Path.Combine(root, "filter-next.xml"); File.WriteAllText(first, "first"); File.WriteAllText(next, "same hash in new data"); bool available = true; var profiles = new FixtureProfileClient((uid, _) => available ? Task.FromResult(new BilibiliProfile(uid, "first success", "", "", null, null)) : Task.FromException(new InvalidDataException("新数据中资料不可用"))); using var vm = new MainPageViewModel(new FixtureClient(), profiles, TimeSpan.Zero); await vm.ImportFileAsync(first); vm.SelectedItem = vm.PageItems[0]; await vm.ProfileLoadTask; Equal(123L, vm.Profile?.Uid); available = false; await vm.ImportFileAsync(next); vm.SelectedItem = vm.PageItems[0]; await vm.ProfileLoadTask; Equal(2, profiles.Requests.Count); Equal(1, vm.LoadedCount); Equal(0, vm.CandidateValidationPassed); Check(vm.CandidateUids.Count == 0 && vm.Profile is null && vm.SelectedUid is null && vm.GetCandidateUidText("884863d2") == "无可用主页", "New import reused previous successful profile/candidates"); }); await Test("Automatic CPU and card batches survive changing selected rows", async () => { var profiles = new FixtureProfileClient(); using var vm = new MainPageViewModel(new BatchFixtureClient(), profiles, TimeSpan.Zero); bool changed = false; vm.PropertyChanged += (_, e) => { if (e.PropertyName == nameof(vm.IsValidatingCandidates) && vm.IsValidatingCandidates) { vm.SelectedItem = vm.PageItems[0]; vm.SelectedItem = vm.PageItems[1]; changed = true; } }; vm.Input = Bvid; await vm.QueryCommand.ExecuteAsync(null); await vm.ProfileLoadTask; Check(changed && vm.LoadedCount == 128 && vm.BatchResolvedCount == 128 && !vm.IsBusy && !vm.IsValidatingCandidates, "Selecting a row canceled the shared validation batch"); Check(vm.SelectedItem?.Id == "1001" && vm.CandidateUids.Contains(1001) && vm.Profile?.Uid == 1001, "Selected row did not receive filtered candidates"); Equal(profiles.Requests.Count, profiles.Requests.Distinct().Count()); }); await Test("Canceling CPU batch retains comments and allows manual validation retry", async () => { var profiles = new FixtureProfileClient(); using var vm = new MainPageViewModel(new BatchFixtureClient(), profiles, TimeSpan.Zero); bool canceled = false; vm.PropertyChanged += (_, e) => { if (e.PropertyName == nameof(vm.IsBatchResolving) && vm.IsBatchResolving) { canceled = true; vm.CancelCommand.Execute(null); } }; vm.Input = Bvid; await vm.QueryCommand.ExecuteAsync(null); Check(canceled && vm.LoadedCount == 128 && vm.FilteredCount == 128 && vm.BatchResolvedCount < vm.BatchTotalCount && !vm.IsBusy, "CPU cancellation lost comments or completed incorrectly"); Equal(0, profiles.Requests.Count); Check(vm.ExportCommand.CanExecute(null), "CPU cancellation disabled comment export"); vm.SelectedItem = vm.PageItems[0]; await vm.ResolveSenderCommand.ExecuteAsync(null); await vm.ProfileLoadTask; Check(vm.CandidateUids.SequenceEqual([1000L]) && vm.Profile?.Uid == 1000, "Manual retry after canceled batch failed"); }); await Test("Canceling at CPU result publication does not expose unchecked UIDs or start HTTP", async () => { var profiles = new FixtureProfileClient(); using var vm = new MainPageViewModel(new BatchFixtureClient(), profiles, TimeSpan.Zero); bool canceled = false; vm.PropertyChanged += (_, e) => { if (e.PropertyName == nameof(vm.IsBatchResolving) && vm.IsBatchResolving) vm.SelectedItem = vm.PageItems[0]; if (e.PropertyName == nameof(vm.BatchResolvedCount) && vm.IsBatchResolving && vm.BatchResolvedCount > 0 && !canceled) { canceled = true; vm.CancelCommand.Execute(null); } }; vm.Input = Bvid; await vm.QueryCommand.ExecuteAsync(null); await vm.ProfileLoadTask; Check(canceled && vm.BatchResolvedCount > 0 && vm.LoadedCount == 128 && !vm.IsBusy, "CPU publication cancellation lost completed raw work"); Equal(0, profiles.Requests.Count); Check(vm.CandidateUids.Count == 0 && vm.Profile is null, "Unchecked CRC matches leaked into visible candidates"); Check(vm.PageItems.All(item => !long.TryParse(vm.GetCandidateUidText(item.MidHash).Split(" / ")[0], out _)), "Unchecked UID appeared in the table"); vm.SelectedItem = vm.PageItems[0]; await vm.ResolveSenderCommand.ExecuteAsync(null); await vm.ProfileLoadTask; Check(vm.CandidateUids.SequenceEqual([1000L]), "Completed raw cache could not be retried after cancellation"); }); await Test("Mixed profile outcomes filter collisions and retry raw failures without refetching success", async () => { bool recover = false; var profiles = new FixtureProfileClient((uid, _) => uid is 1 or 1_146_140_827 || (recover && uid == 2_422_059_385) ? Task.FromResult(new BilibiliProfile(uid, "有效 " + uid, "", "", null, null)) : Task.FromException(new InvalidDataException("账号不存在"))); using var vm = new MainPageViewModel(new FixtureClient(), profiles, TimeSpan.Zero); vm.SelectedItem = Item(hash: "83dcefb7"); await vm.ResolveSenderCommand.ExecuteAsync(null); await vm.ProfileLoadTask; Check(vm.CandidateUids.SequenceEqual([1L, 1_146_140_827L]) && vm.GetCandidateUidText("83dcefb7") == "1 / 1146140827", "Failed account profiles were not removed from visible collision results"); Equal(4, profiles.Requests.Count); Check(vm.SenderResolutionText.Contains("碰撞") && vm.SelectedItem.SenderText == "未公开", "Validated account was treated as a confirmed sender"); vm.SelectedUid = 1_146_140_827; await vm.ProfileLoadTask; Equal(1_146_140_827L, vm.Profile?.Uid); Equal(4, profiles.Requests.Count); recover = true; await vm.ResolveSenderCommand.ExecuteAsync(null); await vm.ProfileLoadTask; Check(vm.CandidateUids.SequenceEqual([1L, 1_146_140_827L, 2_422_059_385L]), "Raw failed candidate was discarded instead of retried"); Equal(1, profiles.Requests.Count(uid => uid == 1)); Equal(1, profiles.Requests.Count(uid => uid == 1_146_140_827)); Equal(6, profiles.Requests.Count); vm.SelectedItem = Item("same", hash: " 83DCEFB7 "); await vm.ProfileLoadTask; Equal(6, profiles.Requests.Count); vm.SelectedItem = Item(hash: "0000000a"); await vm.ResolveSenderCommand.ExecuteAsync(null); Check(vm.CandidateUids.Count == 0 && vm.GetCandidateUidText("0000000a") == "未找到", "No CRC match retained stale visible candidates"); foreach (string hash in new[] { "", "invalid", "123456789" }) { vm.SelectedItem = Item(hash: hash); Check(!vm.ResolveSenderCommand.CanExecute(null), "Invalid hash can resolve"); } vm.SelectedItem = null; Check(!vm.CopyUidCommand.CanExecute(null) && !vm.OpenProfileCommand.CanExecute(null), "Cleared selection retained account actions"); }); await Test("Unavailable profile disables account actions; raw candidate remains retryable", async () => { int calls = 0; var profiles = new FixtureProfileClient((uid, _) => Interlocked.Increment(ref calls) == 1 ? Task.FromException(new HttpRequestException("测试离线")) : Task.FromResult(new BilibiliProfile(uid, "重试成功", "", "", null, null))); using var vm = new MainPageViewModel(new FixtureClient(), profiles, TimeSpan.Zero); vm.SelectedItem = Item(hash: "884863d2"); await vm.ResolveSenderCommand.ExecuteAsync(null); Check(vm.CandidateUids.Count == 0 && vm.Profile is null && !vm.CopyUidCommand.CanExecute(null) && !vm.CopyProfileUrlCommand.CanExecute(null) && !vm.OpenProfileCommand.CanExecute(null), "Unchecked account remained actionable after network failure"); Check(vm.ResolveSenderCommand.CanExecute(null), "Unverified raw candidate cannot retry"); await vm.ResolveSenderCommand.ExecuteAsync(null); await vm.ProfileLoadTask; Equal(123L, vm.SelectedUid); Equal("重试成功", vm.Profile?.Name); Equal(2, profiles.Requests.Count); }); await Test("Manual profile refresh failure removes visibility and resolve restores the raw candidate", async () => { bool fail = false; var profiles = new FixtureProfileClient((uid, _) => fail ? Task.FromException(new InvalidDataException("资料不可用")) : Task.FromResult(new BilibiliProfile(uid, "success", "", "", null, null))); using var vm = new MainPageViewModel(new FixtureClient(), profiles, TimeSpan.Zero); vm.SelectedItem = Item(hash: "884863d2"); await vm.ResolveSenderCommand.ExecuteAsync(null); await vm.ProfileLoadTask; Check(vm.RefreshProfileCommand.CanExecute(null), "Validated card cannot refresh"); fail = true; await vm.RefreshProfileCommand.ExecuteAsync(null); await vm.ProfileLoadTask; Check(vm.CandidateUids.Count == 0 && vm.Profile is null && !vm.OpenProfileCommand.CanExecute(null) && vm.GetCandidateUidText("884863d2") is "无可用主页" or "待验证", "Refresh failure retained a visible invalid account"); fail = false; await vm.ResolveSenderCommand.ExecuteAsync(null); await vm.ProfileLoadTask; Equal(123L, vm.Profile?.Uid); Equal(3, profiles.Requests.Count); using var export = JsonDocument.Parse(DanmakuExport.Json([vm.SelectedItem!], "fixture", "complete")); Equal(JsonValueKind.Null, export.RootElement.GetProperty("items")[0].GetProperty("sender").ValueKind); }); await Test("Revalidation invalidates an older refresh before its late failure or mismatched result", async () => { foreach (bool lateFailure in new[] { true, false }) { int reads = 0; var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var late = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var profiles = new FixtureProfileClient((uid, _) => { if (uid != 1000) return Task.FromException(new InvalidDataException("模拟碰撞账号不存在")); if (Interlocked.Increment(ref reads) == 2) { entered.TrySetResult(); return late.Task; } return Task.FromResult(new BilibiliProfile(1000, "有效主页", "", "", null, null)); }); using var vm = new MainPageViewModel(new FixtureClient(), profiles, TimeSpan.Zero); vm.SelectedItem = Item(hash: "b427a317"); await vm.ResolveSenderCommand.ExecuteAsync(null); await vm.ProfileLoadTask; Check(vm.CandidateUids.SequenceEqual([1000L]) && vm.Profile?.Uid == 1000, "Initial successful account was not prepared"); Task refresh = vm.RefreshProfileCommand.ExecuteAsync(null); await entered.Task.WaitAsync(TimeSpan.FromSeconds(2)); Check(vm.ResolveSenderCommand.CanExecute(null), "Pending refresh unexpectedly blocks a new validation"); bool delivered = false; vm.PropertyChanged += (_, e) => { if (e.PropertyName != nameof(vm.IsValidatingCandidates) || !vm.IsValidatingCandidates || delivered) return; delivered = true; // The client deliberately ignores cancellation; release it only after validation invalidates its version. if (lateFailure) late.SetException(new InvalidDataException("过期刷新失败")); else late.SetResult(new BilibiliProfile(2000, "过期错位主页", "", "", null, null)); }; Task validation = vm.ResolveSenderCommand.ExecuteAsync(null); await Task.WhenAll(refresh, validation).WaitAsync(TimeSpan.FromSeconds(2)); await vm.ProfileLoadTask; Check(delivered && vm.CandidateUids.SequenceEqual([1000L]) && vm.GetCandidateUidText("b427a317") == "1000", "Late refresh removed a revalidated successful candidate"); Check(vm.Profile?.Uid == 1000 && vm.Profile.Name == "有效主页" && vm.CopyUidCommand.CanExecute(null) && vm.CopyProfileUrlCommand.CanExecute(null) && vm.OpenProfileCommand.CanExecute(null), "Late refresh replaced the card or disabled account actions"); Check(!vm.ProfileStatus.Contains("过期") && !vm.ProfileStatus.Contains("已移除") && !vm.IsLoadingProfile, "Late refresh overwrote the current preview status"); Equal(2, profiles.Requests.Count(uid => uid == 1000)); } }); await Test("Avatar decoding failure keeps a successfully validated profile candidate", async () => { var profiles = new FixtureProfileClient((uid, _) => Task.FromResult(new BilibiliProfile(uid, "头像不可用", "file:///C:/invalid-avatar.png", "", null, null))); using var vm = new MainPageViewModel(new FixtureClient(), profiles, TimeSpan.Zero); vm.SelectedItem = Item(hash: "884863d2"); await vm.ResolveSenderCommand.ExecuteAsync(null); await vm.ProfileLoadTask; Check(vm.CandidateUids.SequenceEqual([123L]) && vm.Profile?.Uid == 123 && vm.ProfileAvatar is null && !vm.IsLoadingProfile && vm.OpenProfileCommand.CanExecute(null), "Avatar failure discarded a valid public card"); }); await Test("Canceling candidate validation retains passed cards and loaded comments", async () => { var profiles = new FixtureProfileClient(); using var vm = new MainPageViewModel(new FixtureClient(), profiles, TimeSpan.Zero); bool canceled = false; vm.PropertyChanged += (_, e) => { if (e.PropertyName == nameof(vm.CandidateValidationPassed) && vm.IsValidatingCandidates && vm.CandidateValidationPassed > 0 && !canceled) { canceled = true; vm.CancelCommand.Execute(null); } }; vm.Input = Bvid; await vm.QueryCommand.ExecuteAsync(null); Check(canceled && vm.CandidateValidationPassed > 0 && vm.LoadedCount == 405 && !vm.IsBusy && !vm.IsValidatingCandidates && vm.ExportCommand.CanExecute(null), "Candidate validation cancellation discarded successful cards/comments"); Check(vm.CandidateValidationText.Contains("取消") && !vm.Status.Contains("正在取消"), "Candidate cancellation left a loading status"); Check(vm.PageItems.Any(item => long.TryParse(vm.GetCandidateUidText(item.MidHash).Split(" / ")[0], out _)), "Validated successes disappeared after cancellation"); }); await Test("Invalid query/filter preserves good data; pending network remains cancellable", async () => { using (var vm = new MainPageViewModel(new FixtureClient(), new FixtureProfileClient(), TimeSpan.Zero)) { vm.Input = Bvid; await vm.QueryCommand.ExecuteAsync(null); vm.Input = "invalid"; await vm.QueryCommand.ExecuteAsync(null); Equal(405, vm.LoadedCount); vm.FromText = "2:99"; await vm.ApplyFilterCommand.ExecuteAsync(null); Equal(405, vm.FilteredCount); Check(!vm.IsBusy, "Busy state stuck after filter rejection"); } var handler = new Handler(async (_, token) => { await Task.Delay(30000, token); return Metadata(); }); using var pending = new MainPageViewModel(new BilibiliClient(handler), new FixtureProfileClient(), TimeSpan.Zero); pending.Input = Bvid; Task query = pending.QueryCommand.ExecuteAsync(null); await Idle(); Check(pending.IsBusy && pending.CancelCommand.CanExecute(null) && !pending.QueryCommand.CanExecute(null), "Pending query is not cancellable"); pending.CancelCommand.Execute(null); await query.WaitAsync(TimeSpan.FromSeconds(2)); Check(!pending.IsBusy && pending.Status.Contains("取消") && pending.VideoTitle != "正在读取视频…", "Canceled query left loading labels"); }); } private static async Task Idle() => await Application.Current.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle); private static void Render(FrameworkElement element, string file) { element.UpdateLayout(); var bitmap = new RenderTargetBitmap((int)element.ActualWidth, (int)element.ActualHeight, 96, 96, PixelFormats.Pbgra32); bitmap.Render(element); var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap)); using var stream = File.Create(Path.Combine(root, file)); encoder.Save(stream); } private static async Task Live() { await Test("Live Bilibili metadata / actual protobuf segment / keyword-time query", async () => { using var client = new BilibiliClient(); using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(50)); var video = await client.GetVideoAsync(Bvid, timeout.Token); var part = video.Parts[0]; var result = await client.GetDanmakuAsync(part, null, null, null, timeout.Token); Check(result.Complete, result.Warning ?? "Live query incomplete"); Check(result.Items.Count > 0, "Expected public test-video comments"); var sample = result.Items.First(x => x.Content.Length > 0); var matches = new DanmakuFilter(sample.Content, sample.PositionMs, sample.PositionMs, null, null).Apply(result.Items); Check(matches.Count > 0, "Live data filter failed"); Check(result.Items.All(x => x.SenderText == "未公开"), "Sender was inferred"); Check(result.Items.Any(x => MidHashResolver.IsValidHash(x.MidHash)), "Expected actual protobuf midHash fields"); File.WriteAllText(Path.Combine(root, "live-result.json"), JsonSerializer.Serialize(new { success = true, checkedAt = DateTimeOffset.Now, video.Bvid, video.Title, part.Cid, count = result.Items.Count, result.Completed, result.Total, exactFilterMatches = matches.Count, sender = "未公开", rawSenderHashesRetained = true }, new JsonSerializerOptions { WriteIndented = true })); }); await Test("Live UID 2 public profile card and bounded avatar decoding", async () => { using var client = new BilibiliProfileClient(); using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(35)); var profile = await client.GetProfileAsync(2, timeout.Token); Equal(2L, profile.Uid); Equal("https://space.bilibili.com/2", profile.ProfileUrl); Check(!string.IsNullOrWhiteSpace(profile.Name) && !string.IsNullOrWhiteSpace(profile.AvatarUrl), "Public fixture profile has no nickname or avatar"); var avatar = await ProfileAvatarLoader.LoadAsync(profile.AvatarUrl, timeout.Token); Check(avatar is BitmapSource { PixelWidth: > 0 and <= 128, PixelHeight: > 0, IsFrozen: true }, "Avatar was not decoded at the bounded width and frozen for UI use"); var bitmap = (BitmapSource)avatar!; var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap)); using (var image = File.Create(Path.Combine(root, "profile-live-avatar.png"))) encoder.Save(image); File.WriteAllText(Path.Combine(root, "profile-live-result.json"), JsonSerializer.Serialize(new { success = true, checkedAt = DateTimeOffset.Now, profile.Uid, profile.Name, profile.Level, profile.Followers, profile.ProfileUrl, profile.AvatarUrl, avatarWidth = bitmap.PixelWidth, avatarHeight = bitmap.PixelHeight, avatarFile = "profile-live-avatar.png", profileRequests = 1, avatarRequests = 1 }, new JsonSerializerOptions { WriteIndented = true })); }); } }