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 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":"科技 & 航天","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":"新闻 & 视频","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("""
""");
Assert(body == "新闻 \"视频\" & 文字
", "正文必须从数据字符串提取并正确解码 JS 转义");
Assert(VideoContentHelper.ExtractCctvArticleBody("""
""") == "正文的 '引号'
", "双引号及 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($"视频前正文
{marker}视频后正文
"));
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 = $"";
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[]
{
"708390d321124eeda83611e886b94594,0,1,16:9,newPlayer",
"<!--begin:htmlVideoCode-->708390d321124eeda83611e886b94594,0,1,16:9,newPlayer<!--end:htmlVideoCode-->"
})
Assert(VideoContentHelper.ExpandCctvVideoPlaceholders(marker) == "",
"HTML 注释或转义标记也应进入视频模板");
var invalid = VideoContentHelper.ExpandCctvVideoPlaceholders("[!--begin:htmlVideoCode--]invalid-id,0,1[!--end:htmlVideoCode--]");
Assert(!invalid.Contains("htmlVideoCode") && !invalid.Contains("