XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFENewsApplication

【WinUI】新闻软件

公开
关注 0 Fork 0 Star 0
UTF-8
using HtmlAgilityPack;
using System.Text.Json;
using XFENewsApplication.Core.Models;
using XFENewsApplication.Core.Utilities;
using XFENewsApplication.Core.Utilities.Helpers;

internal static class Program
{
    private static int failures;
    private static int passed;

    private static async Task<int> Main(string[] args)
    {
        Run("同页及跨页内容 ID 去重", () =>
        {
            var cache = new NewsFeedCache();
            var first = cache.AddUnique([Story("A", "https://www.msn.cn/a"), Story("A", "https://www.msn.cn/a?ocid=first")]);
            Assert(first.Count == 1, "同一页重复内容只应添加一次");
            var second = cache.AddUnique([Story("A", "https://www.msn.cn/another-path"), Story("B", "https://www.msn.cn/b")]);
            Assert(second.Count == 1 && cache.Items.Count == 2, "跨页重复 ID 必须过滤");
        });
        Run("跟踪 URL 去重保留文章查询参数", () =>
        {
            var cache = new NewsFeedCache();
            cache.AddUnique([Story(null, "https://news.cctv.com/story?id=1&utm_source=feed#content")]);
            var result = cache.AddUnique([Story(null, "https://news.cctv.com/story?id=1&ocid=home"), Story(null, "https://news.cctv.com/story?id=2")]);
            Assert(result.Count == 1 && result[0].Url.EndsWith("id=2"), "应忽略跟踪参数,保留有意义的文章参数");
        });
        Run("同 URL 不同 ID 仍须去重", () =>
        {
            var cache = new NewsFeedCache();
            Assert(cache.AddUnique([Story("A", "https://www.msn.cn/a"), Story("B", "https://www.msn.cn/a?cvid=123")]).Count == 1,
                "内容 ID 变化不能导致同一链接重复");
        });
        Run("重复卡片登记新链接和 ID 别名", () =>
        {
            var cache = new NewsFeedCache();
            Assert(cache.AddUnique([Story("A", "https://www.msn.cn/a"), Story("A", "https://www.msn.cn/b"), Story("B", "https://www.msn.cn/b")]).Count == 1,
                "重复 ID 的新链接不能在后续卡片中重新出现");
            var reverse = new NewsFeedCache();
            Assert(reverse.AddUnique([Story("A", "https://www.msn.cn/a"), Story("B", "https://www.msn.cn/a"), Story("B", "https://www.msn.cn/b")]).Count == 1,
                "重复链接的新 ID 也应作为别名登记");
        });
        Run("历史记录使用稳定内容身份", () =>
        {
            Assert(NewsFeedCache.IdentityKey(Story("A", "https://www.msn.cn/a?ocid=one"))
                == NewsFeedCache.IdentityKey(Story("a", "https://www.msn.cn/a?ocid=two")), "刷新后的跟踪链接不能重复记录同一新闻");
            Assert(NewsFeedCache.IdentityKey(Story("A", "https://www.msn.cn/a"))
                != NewsFeedCache.IdentityKey(Story("A", "https://news.cctv.com/a", source: "CCTV")), "不同新闻源的身份不能混用");
        });
        Run("新闻源缓存独立", () =>
        {
            var msn = new NewsFeedCache();
            var cctv = new NewsFeedCache();
            msn.AddUnique([Story("A", "https://www.msn.cn/a")]);
            cctv.AddUnique([Story("A", "https://news.cctv.com/a", source: "CCTV")]);
            Assert(msn.Items.Count == 1 && cctv.Items.Count == 1 && msn.NextPage == 1 && cctv.NextPage == 1,
                "切换新闻源不应互相污染内容和分页");
        });
        Run("空身份内容丢弃", () =>
        {
            Assert(new NewsFeedCache().AddUnique([new NewsSource { Title = "无效内容" }]).Count == 0, "缺少 ID 和 URL 的卡片不能进入列表");
        });
        Run("显式兴趣优先并保持同分服务顺序", () =>
        {
            var normal = Story("A", "https://www.msn.cn/a", title: "一般新闻");
            var preferred = Story("B", "https://www.msn.cn/b", title: "科技新闻");
            var equal = Story("C", "https://www.msn.cn/c", title: "科技新进展");
            var ranked = NewsRecommendationRanker.Rank([normal, preferred, equal], [], " 科技,科技;人工智能 ", true);
            Assert(ranked.Select(item => item.ID).SequenceEqual(["B", "C", "A"]), "兴趣匹配后同分文章应保留官方排序");
        });
        Run("阅读偏好仅使用 MSN 历史", () =>
        {
            var normal = Story("A", "https://www.msn.cn/a", author: "一般媒体");
            var preferred = Story("B", "https://www.msn.cn/b", author: "科技媒体");
            var history = new[] { Story("read", "https://www.msn.cn/read", author: "科技媒体"), Story("other", "https://news.cctv.com/other", author: "一般媒体", source: "CCTV") };
            Assert(NewsRecommendationRanker.Rank([normal, preferred], history, null, true)[0] == preferred,
                "阅读过的 MSN 媒体应优先,但 CCTV 历史不应影响其权重");
        });
        Run("关闭个性化保留服务排序", () =>
        {
            var original = new[] { Story("A", "https://www.msn.cn/a"), Story("B", "https://www.msn.cn/b", title: "科技") };
            Assert(NewsRecommendationRanker.Rank(original, [original[1]], "科技", false).SequenceEqual(original), "关闭后应忽略本地偏好");
        });

        Run("MSN 嵌套栏目、长 ID 和广告过滤", () =>
        {
            var result = MsnFeedParser.Parse("""
                {"sections":[{"cards":[
                  {"type":"infopane","subCards":[{"type":"article","id":"long-id-12345678901234567890","title":"科技 &amp; 航天","url":"https://www.msn.cn/a"}]},
                  {"type":"ad","subCards":[{"type":"article","id":"ad","title":"广告","url":"https://www.msn.cn/ad"}]},
                  {"type":"article","id":"long-id-12345678901234567890","title":"重复","url":"https://www.msn.cn/a?ocid=feed"}
                ],"subSections":[{"cards":[{"type":"video","id":"video-id","title":"视频新闻","url":"https://www.msn.cn/video"}]}]}]}
                """);
            Assert(result.Success && result.Count == 2 && result.NewsSourceList[0].Title == "科技 & 航天", "嵌套首卡不能漏新闻,也不能把广告加入新闻");
            Assert(result.NewsSourceList[0].ID == "long-id-12345678901234567890", "不能截断内容 ID");
        });
        Run("MSN 分页完全遵循服务游标", () =>
        {
            var result = MsnFeedParser.Parse("""
                {"sections":[],"nextPageUrl":"https://api.msn.com/news/feed/pages/weblayout?$skip=7&newsSkip=180&cardsServed=85&lastcardrank=91"}
                """, 2);
            Assert(result.Success && result.HasMore && result.Count == 0 && result.NextSkip == 7
                && result.CardsServed == 85 && result.LastCardRank == 91, "不能根据文章数修改服务分页计数");
        });
        Run("MSN 页面解析后的别名用于后续页去重", () =>
        {
            var page = MsnFeedParser.Parse("""
                {"sections":[{"cards":[{"type":"article","id":"A","title":"新闻","url":"https://www.msn.cn/a"},{"type":"article","id":"A","title":"同一新闻","url":"https://www.msn.cn/b"}]}]}
                """);
            var cache = new NewsFeedCache();
            cache.AddUnique(page.NewsSourceList);
            cache.RegisterAliases(page.IdentityAliases);
            Assert(cache.AddUnique([Story("B", "https://www.msn.cn/b")]).Count == 0,
                "单页解析剔除的链接别名不能在下一页重新出现");
        });
        Run("MSN 无游标表示末页", () =>
        {
            var result = MsnFeedParser.Parse("{\"sections\":[]}");
            Assert(result.Success && !result.HasMore && result.CardsServed == -1 && result.LastCardRank == -1, "缺失服务计数必须区分于零");
        });
        Run("重复内容页仍可继续加载但循环游标终止", () =>
        {
            var cache = new NewsFeedCache();
            var first = MsnFeedParser.Parse("{\"sections\":[],\"nextPageUrl\":\"https://api.msn.com/news/feed/pages/weblayout?$skip=1&cardsServed=30\"}");
            var second = MsnFeedParser.Parse("{\"sections\":[],\"nextPageUrl\":\"https://api.msn.com/news/feed/pages/weblayout?$skip=2&cardsServed=60\"}", 1);
            cache.AcceptMsnContinuation(first);
            cache.AcceptMsnContinuation(second);
            Assert(cache.HasMore && cache.Skip == 2 && cache.CardsServed == 60, "空内容不能覆盖服务仍有下一页的状态");
            cache.AcceptMsnContinuation(first);
            Assert(!cache.HasMore, "循环游标必须停止,避免重复请求");
        });
        Run("失败请求保持分页位置", () =>
        {
            var cache = new NewsFeedCache();
            try { cache.AcceptMsnContinuation(new NewsResult { Success = false, NextSkip = 99 }); }
            catch (ArgumentException) { }
            Assert(cache.Skip == 0 && cache.NextPageUrl is null, "失败不能消耗分页位置");
        });
        Run("MSN 异常响应可报告失败", () =>
        {
            Assert(!MsnFeedParser.Parse("not json").Success && !MsnFeedParser.Parse("{\"sections\":{}}").Success
                && !MsnFeedParser.Parse("[]").Success, "响应结构变化不能误报成功");
        });
        Run("MSN 可选图像字段类型变化", () =>
        {
            var result = MsnFeedParser.Parse("""
                {"sections":[{"cards":[{"type":"article","id":"A","title":"新闻","url":"https://www.msn.cn/a","images":[{"url":"https://www.msn.cn/a.jpg","width":"640","height":null}]}]}]}
                """);
            Assert(result.Success && result.Count == 1, "可选图像字段变化不能让整页新闻丢失");
        });
        Run("MSN 游标保持参数并更新当前身份", () =>
        {
            var options = new MsnFeedOptions { UserId = "11111111222233334444555555555555", ActivityId = "66666666-7777-8888-9999-000000000000" };
            var url = MsnFeedRequestBuilder.Build("https://assets.msn.cn", "test-key", options,
                nextPageUrl: "https://api.msn.com/news/feed/pages/weblayout?$skip=7&newsSkip=180&cardsServed=85&scn=APP_ANON&it=edgeid&user=old");
            var query = Uri.UnescapeDataString(new Uri(url).Query);
            Assert(query.Contains("$skip=7") && query.Contains("newsSkip=180") && query.Contains("cardsServed=85")
                && query.Contains("user=m-11111111222233334444555555555555")
                && !query.Contains("scn=") && !query.Contains("it=edgeid"), "必须保留服务游标并使用应用的匿名身份");
        });
        Run("MSN 游标限定新闻服务地址", () =>
        {
            Assert(!MsnFeedRequestBuilder.IsTrustedFeedUrl("https://api.msn.com.example.org/news/feed/pages/weblayout")
                && !MsnFeedRequestBuilder.IsTrustedFeedUrl("https://api.msn.com/unrelated")
                && !MsnFeedRequestBuilder.IsTrustedFeedUrl("http://api.msn.com/news/feed/pages/weblayout"), "不能跟随非新闻服务的下一页地址");
            Assert(!MsnFeedParser.Parse("{\"sections\":[],\"nextPageUrl\":\"https://example.org/page\"}").Success, "无效游标应报告失败");
        });
        Run("CCTV JSONP 正确解包与去重", () =>
        {
            var result = ClimbHelper.ParseCCTVFeed("""
                news({"data":{"list":[{"id":"A","title":"新闻 &amp; 视频","url":"https://news.cctv.com/a","brief":"简介"},{"id":"A","title":"重复","url":"https://news.cctv.com/a?utm_source=test"}]}});
                """);
            Assert(result.Success && result.Count == 1 && result.NewsSourceList[0].Title == "新闻 & 视频", "不能依赖 JSON 库隐式处理 JSONP");
            Assert(!ClimbHelper.ParseCCTVFeed("callback(not json);").Success, "无效 JSONP 应报告失败");
        });
        Run("CCTV 空页停止分页", () =>
        {
            var result = ClimbHelper.ParseCCTVFeed("news({\"data\":{\"list\":[]}})");
            Assert(result.Success && !result.HasMore && result.Count == 0, "合法空页应成功结束分页");
        });
        await RunAsync("取消请求不再访问网络", async () =>
        {
            using var canceled = new CancellationTokenSource();
            canceled.Cancel();
            await AssertCanceled(() => ClimbHelper.ClimbMSNNews(canceled.Token));
            await AssertCanceled(() => ClimbHelper.ClimbCCTVNews(canceled.Token));
        });
        Run("CCTV 新版脚本正文与转义", () =>
        {
            var body = VideoContentHelper.ExtractCctvArticleBody("""
                <div id="content_area"></div><script>var contentdate='<p>\u65b0闻 \"视频\" &amp; 文字<\/p>';</script>
                """);
            Assert(body == "<p>新闻 \"视频\" &amp; 文字</p>", "正文必须从数据字符串提取并正确解码 JS 转义");
            Assert(VideoContentHelper.ExtractCctvArticleBody("""
                <script>const contentData="<p>正文的 '引号'</p>";</script>
                """) == "<p>正文的 '引号'</p>", "双引号及 contentData 模板也应支持");
        });
        Run("CCTV 视频 ID 提取", () =>
        {
            Assert(VideoContentHelper.ExtractCctvVideoId("var guid = 'ca4fde8315a24a22ae308cb05c024a4f';") == "ca4fde8315a24a22ae308cb05c024a4f",
                "播放器必须使用页面实际的央视 GUID");
        });
        Run("CCTV 正文视频占位符转为内容模板元素", () =>
        {
            const string marker = "[!--begin:htmlVideoCode--]708390d321124eeda83611e886b94594,0,1,16:9,newPlayer[!--end:htmlVideoCode--]";
            Assert(VideoContentHelper.ExtractCctvVideoId(marker) == "708390d321124eeda83611e886b94594", "正文占位符应提供实际视频 ID");
            var document = new HtmlDocument();
            document.LoadHtml(VideoContentHelper.ExpandCctvVideoPlaceholders($"<p>视频前正文</p>{marker}<p>视频后正文</p>"));
            var nodes = document.DocumentNode.ChildNodes;
            Assert(nodes.Count == 3 && nodes[0].InnerText == "视频前正文" && nodes[1].Name == "video"
                && nodes[1].GetAttributeValue("id", "") == "708390d321124eeda83611e886b94594" && nodes[2].InnerText == "视频后正文",
                "视频必须保留在正文原位置,并且不能吞掉前后段落");
            Assert(!document.DocumentNode.InnerText.Contains("htmlVideoCode") && !document.DocumentNode.InnerText.Contains("newPlayer"),
                "内部占位参数不能作为文章文字显示");
        });
        Run("CCTV 多个正文视频按顺序解析", () =>
        {
            const string firstId = "708390d321124eeda83611e886b94594";
            const string secondId = "ca4fde8315a24a22ae308cb05c024a4f";
            var html = $"<script>var guid='11111111111111111111111111111111'; var contentdate='<p>开头</p>[!--begin:htmlVideoCode--]{firstId},0,1,16:9,newPlayer[!--end:htmlVideoCode--]<p>中间</p>[!--begin:htmlVideoCode--]{secondId},0,1,16:9,newPlayer[!--end:htmlVideoCode--]';</script>";
            Assert(VideoContentHelper.ExtractCctvVideoIds(html).SequenceEqual([firstId, secondId]),
                "正文内的视频 ID 应优先于页面其它 guid,多个视频都应保留");
            var document = new HtmlDocument();
            document.LoadHtml(VideoContentHelper.ExpandCctvVideoPlaceholders(VideoContentHelper.ExtractCctvArticleBody(html)));
            var videos = document.DocumentNode.SelectNodes("//video") ?? throw new InvalidOperationException("未生成视频内容元素");
            Assert(videos.Select(video => video.GetAttributeValue("id", "")).SequenceEqual([firstId, secondId]),
                "转换后的模板视频顺序不能变化");
        });
        Run("CCTV 视频占位符兼容 HTML 注释与转义格式", () =>
        {
            foreach (var marker in new[]
            {
                "<!--begin:htmlVideoCode-->708390d321124eeda83611e886b94594,0,1,16:9,newPlayer<!--end:htmlVideoCode-->",
                "&lt;!--begin:htmlVideoCode--&gt;708390d321124eeda83611e886b94594,0,1,16:9,newPlayer&lt;!--end:htmlVideoCode--&gt;"
            })
                Assert(VideoContentHelper.ExpandCctvVideoPlaceholders(marker) == "<video id=\"708390d321124eeda83611e886b94594\"></video>",
                    "HTML 注释或转义标记也应进入视频模板");
            var invalid = VideoContentHelper.ExpandCctvVideoPlaceholders("[!--begin:htmlVideoCode--]invalid-id,0,1[!--end:htmlVideoCode--]");
            Assert(!invalid.Contains("htmlVideoCode") && !invalid.Contains("<video") && invalid.Contains("视频暂不可用"),
                "无效占位符应显示可理解的提示");
        });
        Run("CCTV HLS 优先并保留全部 MP4 章节", () =>
        {
            var manifest = VideoContentHelper.ParseCctvManifest("""
                {"ack":"yes","title":"视频新闻","hls_url":"https://media.example/full.m3u8","default_stream":"chapters3","video":{"chapters3":[{"url":"https://media.example/1.mp4"},{"url":"https://media.example/2.mp4"}],"chapters":[{"url":"https://media.example/low.mp4"}]}}
                """);
            Assert(manifest.CanPlay && manifest.SourceUrl.EndsWith("full.m3u8")
                && manifest.ChapterUrls.SequenceEqual(["https://media.example/1.mp4", "https://media.example/2.mp4"]), "不能只播放第一段视频,也不能错误选择低码率章节");
        });
        Run("CCTV 无 HLS 时使用完整章节序列", () =>
        {
            var manifest = VideoContentHelper.ParseCctvManifest("""
                {"ack":"yes","video":{"chapters":[{"url":"https://media.example/1.mp4"},{"url":"https://media.example/2.mp4"}]}}
                """);
            Assert(manifest.CanPlay && manifest.ChapterUrls.Count == 2 && manifest.SourceUrl.EndsWith("1.mp4"), "完整章节列表必须交给播放控件");
        });
        Run("CCTV 不可播放视频保留降级状态", () =>
        {
            foreach (var json in new[]
            {
                "{\"ack\":\"no\",\"hls_url\":\"https://media.example/full.m3u8\"}",
                "{\"ack\":\"yes\",\"is_protected\":1,\"hls_url\":\"https://media.example/full.m3u8\"}",
                "{\"ack\":\"yes\",\"is_invalid_copyright\":\"1\",\"hls_url\":\"https://media.example/full.m3u8\"}", "[]"
            })
            {
                var manifest = VideoContentHelper.ParseCctvManifest(json);
                Assert(!manifest.CanPlay && manifest.SourceUrl.Length == 0, "不可播放的视频不能误作正常视频");
            }
        });
        Run("MSN 视频资源缺字段与完整 URL", () =>
        {
            using var document = JsonDocument.Parse("""
                {"videoFiles":[{"url":"//media.example/movie.mp4?token=test"},{"url":"https://media.example/movie.m3u8"}]}
                """);
            var urls = VideoContentHelper.ExtractMsnVideoUrls(document.RootElement);
            Assert(urls.Count == 2 && urls[0] == "https://media.example/movie.mp4?token=test", "不能丢失协议相对地址或播放签名参数");
            using var missing = JsonDocument.Parse("null");
            Assert(VideoContentHelper.ExtractMsnVideoUrls(missing.RootElement).Count == 0, "缺失的视频资源不得阻断文章正文");
        });
        Run("MSN 长视频 ID", () =>
        {
            Assert(VideoContentHelper.ExtractMsnVideoId("cms/api/amp/video/12345678-1234-1234-1234-123456789012") == "12345678-1234-1234-1234-123456789012",
                "视频 ID 不应被固定长度截断或拒绝");
        });
        Run("MSN 带格式标识的无扩展名视频地址", () =>
        {
            using var document = JsonDocument.Parse("""
                {"videoFiles":[{"format":"MP4","url":"https://media.example/play?id=42"},{"mimeType":"application/vnd.apple.mpegurl","url":"https://media.example/stream?id=42"}],"image":{"url":"https://media.example/photo.jpg"}}
                """);
            var urls = VideoContentHelper.ExtractMsnVideoUrls(document.RootElement);
            Assert(urls.Count == 2 && urls.All(url => !url.EndsWith("photo.jpg")), "视频格式已明确时不能只根据文件扩展名识别");
        });
        Run("正文相对媒体链接正常解析", () =>
        {
            Assert(VideoContentHelper.NormalizeUrl("../image.jpg", "https://news.cctv.com/2026/story/page.shtml") == "https://news.cctv.com/2026/image.jpg", "正文相对图片地址需要来源页面地址");
            Assert(VideoContentHelper.NormalizeUrl("javascript:alert(1)").Length == 0, "非媒体协议不应进入播放器");
        });

        if (args.Contains("--live", StringComparer.OrdinalIgnoreCase))
            await VerifyLiveFeeds();
        Console.WriteLine($"通过 {passed} 项,失败 {failures} 项。");
        return failures == 0 ? 0 : 1;
    }

    private static async Task VerifyLiveFeeds()
    {
        using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(90));
        try
        {
            var options = new MsnFeedOptions { UserId = Guid.NewGuid().ToString("N"), ActivityId = Guid.NewGuid().ToString() };
            var first = await ClimbHelper.ClimbMSNNews(timeout.Token, options);
            Assert(first.Success && first.NewsSourceList.Count > 0, first.Message ?? "MSN 首页应返回新闻");
            Console.WriteLine($"MSN 第一页:{first.NewsSourceList.Count} 条新闻");
            Assert(first.HasMore && first.NextPageUrl is not null, "MSN 第一页应返回官方下一页游标");
            var next = await ClimbHelper.ClimbMSNNews(timeout.Token, options, first.NextSkip, first.LastCardRank,
                first.CardsServed, first.NextPageUrl);
            Assert(next.Success && next.NewsSourceList.Count > 0 && next.NextSkip > first.NextSkip, "MSN 应按照服务游标推进下一页");
            var cache = new NewsFeedCache();
            cache.AddUnique(first.NewsSourceList);
            Assert(cache.AddUnique(next.NewsSourceList).Count > 0, "MSN 第二页应包含新内容");
            Console.WriteLine($"MSN 第二页:{next.NewsSourceList.Count} 条新闻,分页成功");
            var cctv = await ClimbHelper.ClimbCCTVNews(timeout.Token, 1);
            Assert(cctv.Success && cctv.NewsSourceList.Count > 0, "CCTV 第一页应返回新闻");
            var nextCctv = await ClimbHelper.ClimbCCTVNews(timeout.Token, 2);
            Assert(nextCctv.Success && nextCctv.NewsSourceList.Count > 0, "CCTV 第二页应返回新闻");
            Assert(!cctv.NewsSourceList.Select(item => item.ID).SequenceEqual(nextCctv.NewsSourceList.Select(item => item.ID)), "CCTV 第二页不应重复第一页");
            using var mediaClient = new HttpClient { Timeout = TimeSpan.FromSeconds(20) };
            var currentArticle = await mediaClient.GetStringAsync(cctv.NewsSourceList[0].Url, timeout.Token);
            Assert(VideoContentHelper.ExtractCctvArticleBody(currentArticle).Length > 0
                || VideoContentHelper.ExtractCctvVideoId(currentArticle).Length > 0, "当前央视页面应包含可解析的正文或视频标识");
            // Recent first-party sample exercises the official player metadata, rather than a third-party URL.
            const string videoPage = "https://tv.cctv.com/2026/10/05/VIDE1fiKIqMXtbEZXnAQQvKa261005.shtml";
            var videoHtml = await mediaClient.GetStringAsync(videoPage, timeout.Token);
            var videoId = VideoContentHelper.ExtractCctvVideoId(videoHtml);
            Assert(videoId.Length == 32, "央视视频页面应提供实际视频 GUID");
            var metadata = await mediaClient.GetStringAsync($"https://vdn.apps.cntv.cn/api/getHttpVideoInfo.do?pid={videoId}", timeout.Token);
            var manifest = VideoContentHelper.ParseCctvManifest(metadata);
            Assert(manifest.CanPlay && manifest.SourceUrl.Length > 0 && manifest.ChapterUrls.Count > 1, "央视 API 应返回完整播放资源及章节");
            Console.WriteLine($"CCTV 正文和视频元数据:{manifest.ChapterUrls.Count} 个完整章节");
            var msnVideo = await mediaClient.GetStringAsync("https://assets.msn.com/content/view/v2/Detail/en-us/AA2dANXA", timeout.Token);
            using var videoDocument = JsonDocument.Parse(msnVideo);
            var videoRoot = videoDocument.RootElement;
            var msnStreams = VideoContentHelper.ExtractMsnVideoUrls(videoRoot);
            Assert(videoRoot.GetProperty("type").GetString() == "video" && !string.IsNullOrWhiteSpace(videoRoot.GetProperty("body").GetString())
                && msnStreams.Count > 1, "MSN 真实视频详情应同时保留文字正文及完整播放地址");
            var mp4 = msnStreams.First(url => new Uri(url).AbsolutePath.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase));
            using var head = new HttpRequestMessage(HttpMethod.Head, mp4);
            using var videoResponse = await mediaClient.SendAsync(head, HttpCompletionOption.ResponseHeadersRead, timeout.Token);
            Assert(videoResponse.IsSuccessStatusCode && videoResponse.Content.Headers.ContentType?.MediaType == "video/mp4", "MSN 第一方视频 MP4 地址应可访问");
            Console.WriteLine($"MSN 视频文字、{msnStreams.Count} 个播放资源及 MP4 响应验证成功");
            passed++;
            Console.WriteLine("PASS 第一方服务联网验证");
        }
        catch (Exception ex)
        {
            failures++;
            Console.Error.WriteLine($"FAIL 第一方服务联网验证: {ex.Message}");
        }
    }

    private static NewsSource Story(string? id, string url, string title = "新闻", string? author = null, string source = "MSN") =>
        new() { ID = id, Url = url, Title = title, Authors = author, Source = source };

    private static void Run(string name, Action action)
    {
        try { action(); passed++; Console.WriteLine($"PASS {name}"); }
        catch (Exception ex) { failures++; Console.Error.WriteLine($"FAIL {name}: {ex.Message}"); }
    }

    private static void Assert(bool condition, string message)
    {
        if (!condition)
            throw new InvalidOperationException(message);
    }

    private static async Task RunAsync(string name, Func<Task> action)
    {
        try { await action(); passed++; Console.WriteLine($"PASS {name}"); }
        catch (Exception ex) { failures++; Console.Error.WriteLine($"FAIL {name}: {ex.Message}"); }
    }

    private static async Task AssertCanceled(Func<Task<NewsResult>> action)
    {
        try { await action(); }
        catch (OperationCanceledException) { return; }
        throw new InvalidOperationException("已取消的请求必须传播取消状态");
    }
}