using HtmlAgilityPack; using Microsoft.UI.Text; using Microsoft.UI.Xaml.Documents; using System.Net; using System.Text.Json; using System.Text.RegularExpressions; using XFENewsApplication.Core.Utilities.Helpers; using XFENewsApplication.Models; namespace XFENewsApplication.Utilities.Helper; public static class ArticleDisplayHelper { private static readonly HttpClient MediaClient = new() { Timeout = TimeSpan.FromSeconds(20) }; private const string ClassContains = "contains(concat(' ', normalize-space(@class), ' '), ' {0} ')"; public static List ConvertCCTVToArticlePart(string html) => ParseCCTV(html, string.Empty); public static async Task> ConvertCCTVToArticlePartAsync(string html, string pageUrl, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); var parts = ParseCCTV(html, pageUrl); var inlineIds = parts.OfType().Select(video => video.VideoId) .Where(id => Regex.IsMatch(id, "^[a-fA-F0-9]{32}$", RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1))) .Distinct(StringComparer.OrdinalIgnoreCase).ToList(); var videoIds = inlineIds.Count > 0 ? inlineIds : VideoContentHelper.ExtractCctvVideoIds(html); foreach (var id in videoIds) { cancellationToken.ThrowIfCancellationRequested(); var placeholderIndex = parts.FindIndex(part => part is VideoArticlePart existing && existing.VideoId.Equals(id, StringComparison.OrdinalIgnoreCase)); var video = placeholderIndex >= 0 ? (VideoArticlePart)parts[placeholderIndex] : new VideoArticlePart { VideoId = id, PageUrl = pageUrl, Title = parts.FirstOrDefault()?.Content ?? string.Empty }; await PopulateCctvVideo(video, pageUrl, cancellationToken); if (placeholderIndex < 0) { placeholderIndex = parts.FindIndex(part => part is VideoArticlePart existing && (existing.VideoId.Length == 0 && existing.Content.Length == 0 && existing.PageUrl == pageUrl || existing.Content.Length > 0 && existing.Content == video.Content)); if (placeholderIndex >= 0) { var existing = (VideoArticlePart)parts[placeholderIndex]; video.Description = existing.Description; video.PosterUrl = First(video.PosterUrl, existing.PosterUrl); parts[placeholderIndex] = video; } else parts.Insert(Math.Min(1, parts.Count), video); } } return parts; } private static async Task PopulateCctvVideo(VideoArticlePart video, string pageUrl, CancellationToken cancellationToken) { try { // First-party metadata endpoint used by CCTV's official player. using var request = new HttpRequestMessage(HttpMethod.Get, $"https://vdn.apps.cntv.cn/api/getHttpVideoInfo.do?pid={video.VideoId}"); if (Uri.TryCreate(pageUrl, UriKind.Absolute, out var referer)) request.Headers.Referrer = referer; using var response = await MediaClient.SendAsync(request, cancellationToken); response.EnsureSuccessStatusCode(); var manifest = VideoContentHelper.ParseCctvManifest(await response.Content.ReadAsStringAsync(cancellationToken)); video.Title = First(manifest.Title, video.Title); video.PosterUrl = manifest.PosterUrl; if (!manifest.CanPlay) video.PlaybackError = "此视频暂不能直接播放,请在原网页观看。"; else { video.Content = manifest.SourceUrl; video.FallbackSourceUrls = [.. manifest.ChapterUrls]; } } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } catch (Exception ex) when (ex is HttpRequestException or JsonException or TaskCanceledException) { video.PlaybackError = "视频加载失败,可以刷新新闻或在原网页观看。"; } cancellationToken.ThrowIfCancellationRequested(); } private static List ParseCCTV(string html, string pageUrl) { var document = new HtmlDocument(); document.LoadHtml(html); var root = document.DocumentNode; var title = First(Clean(root.SelectSingleNode("//*[@id='title_area']//h1 | //h1 | //*[@class='ph_title_l']")?.InnerText), Meta(root, "og:title"), Clean(root.SelectSingleNode("//title")?.InnerText)); var parts = Title(title); // The 2026 template fills content_area from a JavaScript string. Decode data without running scripts. var embedded = VideoContentHelper.ExtractCctvArticleBody(html); var body = root.SelectSingleNode("//*[@id='content_area'] | //div[" + string.Format(ClassContains, "content_area") + "]"); if (embedded.Length == 0) { if (body is null || string.IsNullOrWhiteSpace(body.InnerText)) body = root.SelectSingleNode("//*[" + string.Format(ClassContains, "video_brief") + "]") ?? root.SelectSingleNode("//*[@id='text_area'] | //div[" + string.Format(ClassContains, "text_area") + "]"); embedded = body?.InnerHtml ?? string.Empty; } if (embedded.Length > 0) { var bodyDocument = new HtmlDocument(); bodyDocument.LoadHtml(VideoContentHelper.ExpandCctvVideoPlaceholders(embedded)); ParseNodes(parts, title, [], [], bodyDocument.DocumentNode.ChildNodes, bodyDocument.DocumentNode, pageUrl); } if (parts.Count <= 1) { var description = First(Meta(root, "og:description"), Meta(root, "description")); if (description.Length > 0 && description != title) parts.Add(new TextArticlePart { Content = description }); } return parts; } public static List ConvertMSNNewsToArticlePart(string json) => ParseMSN(json, string.Empty); public static async Task> ConvertMSNNewsToArticlePartAsync(string json, string pageUrl, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); var parts = ParseMSN(json, pageUrl); using var source = JsonDocument.Parse(json); var locale = Get(source.RootElement, "locale"); if (!Regex.IsMatch(locale, "^[a-z]{2}-[a-z]{2}$", RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1))) locale = "zh-cn"; foreach (var video in parts.OfType()) { if (video.Content.Length == 0 && VideoContentHelper.ExtractMsnVideoId(video.VideoId).Length > 0) try { var host = locale.Equals("zh-cn", StringComparison.OrdinalIgnoreCase) ? "assets.msn.cn" : "assets.msn.com"; var detailJson = await MediaClient.GetStringAsync($"https://{host}/content/view/v2/Detail/{locale}/{video.VideoId}", cancellationToken); using var detail = JsonDocument.Parse(detailJson); PopulateVideo(video, detail.RootElement, pageUrl); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } catch (Exception ex) when (ex is HttpRequestException or JsonException or TaskCanceledException) { video.PlaybackError = "视频加载失败,可以刷新新闻或在原网页观看。"; } if (video.Content.Length == 0 && video.PlaybackError.Length == 0) video.PlaybackError = "此视频需要使用来源网站的播放器,请在原网页观看。"; } cancellationToken.ThrowIfCancellationRequested(); return parts; } private static List ParseMSN(string json, string pageUrl) { using var document = JsonDocument.Parse(json); var root = document.RootElement; if (root.ValueKind != JsonValueKind.Object) throw new JsonException("新闻正文响应格式不正确。"); var title = Get(root, "title"); var parts = Title(title); var images = new Dictionary(StringComparer.OrdinalIgnoreCase); var videos = new Dictionary(StringComparer.OrdinalIgnoreCase); if (root.TryGetProperty("provider", out var provider) && provider.ValueKind == JsonValueKind.Object) { var names = root.TryGetProperty("authors", out var authors) && authors.ValueKind == JsonValueKind.Array ? authors.EnumerateArray().Select(author => Get(author, "name")).Where(name => name.Length > 0) : []; parts.Add(new AuthorArticlePart { Content = provider.TryGetProperty("logo", out var logo) ? Get(logo, "url") : string.Empty, PublishDateTime = GetRelativeTimeDescription(Get(root, "publishedDateTime")), ReadTime = root.TryGetProperty("readTimeMin", out var readTime) && readTime.ValueKind == JsonValueKind.Number && readTime.TryGetInt32(out var minutes) && minutes > 0 ? minutes.ToString() : string.Empty, ProviderName = Get(provider, "name"), AuthorName = First(string.Join(", ", names), Get(provider, "name")) }); } if (root.TryGetProperty("imageResources", out var imageResources) && imageResources.ValueKind == JsonValueKind.Array) foreach (var image in imageResources.EnumerateArray()) foreach (var key in new[] { Get(image, "cmsId"), Get(image, "id") }.Where(key => key.Length > 0)) { images[key] = Url(Get(image, "url"), pageUrl); images[key.Split('/').Last()] = images[key]; } if (root.TryGetProperty("videoResources", out var resources) && resources.ValueKind == JsonValueKind.Array) foreach (var resource in resources.EnumerateArray()) foreach (var key in new[] { Get(resource, "cmsId"), Get(resource, "id") }.Where(key => key.Length > 0)) { videos[key] = resource; videos[key.Split('/').Last()] = resource; } if (root.TryGetProperty("slides", out var slides) && slides.ValueKind == JsonValueKind.Array) { var flipImages = new List(); foreach (var slide in slides.EnumerateArray()) { if (slide.ValueKind != JsonValueKind.Object || !slide.TryGetProperty("image", out var image) || Get(image, "url").Length == 0) continue; flipImages.Add(new FlipImage { ImageUrl = Url(Get(image, "url"), pageUrl), Description = Get(image, "caption"), Attribution = Get(image, "attribution"), Title = Get(slide, "title") }); } if (flipImages.Count > 0) parts.Add(new FlipImageArticlePart { Images = flipImages }); } if (Get(root, "type").Equals("video", StringComparison.OrdinalIgnoreCase) || root.TryGetProperty("videoFiles", out _)) { var video = new VideoArticlePart { VideoId = Get(root, "id"), PageUrl = pageUrl }; PopulateVideo(video, root, pageUrl); parts.Add(video); } var body = parts.OfType().Any() ? Get(root, "body") : First(Get(root, "body"), Get(root, "abstract"), Get(root, "description")); var html = new HtmlDocument(); html.LoadHtml(body); ParseNodes(parts, title, images, videos, html.DocumentNode.ChildNodes, html.DocumentNode, pageUrl); return parts; } private static void PopulateVideo(VideoArticlePart video, JsonElement resource, string pageUrl) { if (resource.ValueKind != JsonValueKind.Object) return; video.Title = First(Get(resource, "title"), video.Title); video.Description = Clean(First(Get(resource, "description"), Get(resource, "abstract"), video.Description)); video.PageUrl = First(video.PageUrl, pageUrl, Url(Get(resource, "sourceHref"), pageUrl)); if (resource.TryGetProperty("thumbnail", out var thumbnail)) { video.PosterUrl = First(Url(Get(thumbnail, "url"), pageUrl), video.PosterUrl); if (thumbnail.ValueKind == JsonValueKind.Object && thumbnail.TryGetProperty("image", out var thumbnailImage)) video.PosterUrl = First(Url(Get(thumbnailImage, "url"), pageUrl), video.PosterUrl); } if (resource.TryGetProperty("image", out var image)) video.PosterUrl = First(Url(Get(image, "url"), pageUrl), video.PosterUrl); var urls = VideoContentHelper.ExtractMsnVideoUrls(resource); video.Content = First(urls.FirstOrDefault(url => new Uri(url).AbsolutePath.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase)), urls.FirstOrDefault(), video.Content); video.AlternativeSourceUrls = urls.Where(url => url != video.Content).ToList(); } private static void ParseNodes(List parts, string title, Dictionary images, Dictionary videos, HtmlNodeCollection nodes, HtmlNode block, string pageUrl) { foreach (var node in nodes) { if (node.Name == "video" || node.GetAttributeValue("data-reference", string.Empty).Equals("video", StringComparison.OrdinalIgnoreCase)) { var cmsId = node.GetAttributeValue("data-document-id", node.GetAttributeValue("id", string.Empty)).Trim('"'); var id = VideoContentHelper.ExtractMsnVideoId(cmsId); if (id.Length > 0 && parts.OfType().Any(part => part.VideoId == id)) continue; var video = new VideoArticlePart { VideoId = id, Title = node.GetAttributeValue("title", string.Empty), Description = Clean(node.GetAttributeValue("data-description", string.Empty)), PosterUrl = Url(node.GetAttributeValue("poster", string.Empty), pageUrl), PageUrl = pageUrl, Content = Url(First(node.GetAttributeValue("src", string.Empty), node.SelectSingleNode(".//source")?.GetAttributeValue("src", string.Empty)), pageUrl) }; if (videos.TryGetValue(cmsId, out var resource) || videos.TryGetValue(id, out resource)) PopulateVideo(video, resource, pageUrl); parts.Add(video); continue; } switch (node.Name.ToLowerInvariant()) { case "script": case "style": case "noscript": case "#comment": break; case "img": var imageId = node.GetAttributeValue("data-document-id", string.Empty).Trim('"'); var imageUrl = images.TryGetValue(imageId, out var mapped) || images.TryGetValue(imageId.Split('/').Last(), out mapped) ? mapped : string.Empty; imageUrl = First(imageUrl, Url(First(node.GetAttributeValue("src", string.Empty), node.GetAttributeValue("data-src", string.Empty), node.GetAttributeValue("data-original", string.Empty)), pageUrl)); if (imageUrl.Length > 0) parts.Add(new ImageArticlePart { Content = imageUrl, From = First(node.GetAttributeValue("alt", string.Empty), title) }); break; case "br": Append(parts, block, new LineBreak()); break; case "h1": case "h2": case "h3": case "h4": case "h5": case "h6": var heading = Clean(node.InnerText); if (heading.Length > 0 && heading != title) parts.Add(new TitleArticlePart { Content = heading, FontSize = node.Name == "h1" ? 40 : node.Name == "h2" ? 32 : 24, FontWeight = FontWeights.SemiBold }); break; case "blockquote": var quote = Clean(node.InnerText); if (quote.Length > 0) parts.Add(new QuoteArticlePart { Content = quote, FontSize = 24, FontWeight = FontWeights.SemiBold }); break; case "#text": if (!string.IsNullOrWhiteSpace(node.InnerText) || (node.InnerText.Length > 0 && !node.InnerText.Contains('\n') && !node.InnerText.Contains('\r') && block.Name != "#document")) Append(parts, block, new Run { Text = WebUtility.HtmlDecode(node.InnerText) }); break; case "strong": case "b": case "em": case "i": case "u": case "a": case "span": case "sub": case "sup": if (node.SelectSingleNode(".//img | .//video | .//*[@data-reference='video']") is not null) ParseNodes(parts, title, images, videos, node.ChildNodes, block, pageUrl); else Append(parts, block, Inline(node, pageUrl)); break; case "iframe": parts.Add(new VideoArticlePart { Title = node.GetAttributeValue("title", "嵌入内容"), PageUrl = First(Url(node.GetAttributeValue("src", string.Empty), pageUrl), pageUrl), PlaybackError = "此内容使用来源网站的播放器,请在原网页观看。" }); break; default: if (node.HasChildNodes) ParseNodes(parts, title, images, videos, node.ChildNodes, node, pageUrl); break; } } } private static Inline Inline(HtmlNode node, string pageUrl) { if (node.Name == "#text") return new Run { Text = WebUtility.HtmlDecode(node.InnerText) }; if (node.Name == "br") return new LineBreak(); Span span = node.Name switch { "strong" or "b" => new Bold(), "em" or "i" => new Italic(), "u" => new Underline(), _ => new Span() }; if (node.Name == "a" && Uri.TryCreate(Url(node.GetAttributeValue("href", string.Empty), pageUrl), UriKind.Absolute, out var uri)) span = new Hyperlink { NavigateUri = uri }; foreach (var child in node.ChildNodes.Where(child => child.Name is not "script" and not "style" and not "#comment")) span.Inlines.Add(Inline(child, pageUrl)); return span; } private static void Append(List parts, HtmlNode block, Inline inline) { var id = block.GetHashCode().ToString(); if (parts.LastOrDefault() is not CustomTextArticlePart text) { text = new CustomTextArticlePart { Content = id }; parts.Add(text); } else if (text.Content != id) { text.Content = id; text.CustomTextBlock.Inlines.Add(new LineBreak()); text.CustomTextBlock.Inlines.Add(new LineBreak()); } text.CustomTextBlock.Inlines.Add(inline); } private static List Title(string title) => title.Length == 0 ? [] : [new TextArticlePart { Content = title, FontSize = 40, FontWeight = FontWeights.Bold }]; private static string Meta(HtmlNode root, string name) => Clean(root.SelectSingleNode($"//meta[@property='{name}' or @name='{name}']")?.GetAttributeValue("content", string.Empty)); private static string Clean(string? value) { if (string.IsNullOrWhiteSpace(value)) return string.Empty; var document = new HtmlDocument(); document.LoadHtml(value); return WebUtility.HtmlDecode(document.DocumentNode.InnerText).Trim(); } private static string Get(JsonElement element, string name) => element.ValueKind == JsonValueKind.Object && element.TryGetProperty(name, out var value) && value.ValueKind is not JsonValueKind.Null and not JsonValueKind.Undefined ? value.ToString() : string.Empty; private static string First(params string?[] values) => values.FirstOrDefault(value => !string.IsNullOrWhiteSpace(value)) ?? string.Empty; private static string Url(string? value, string pageUrl) => VideoContentHelper.NormalizeUrl(value, pageUrl); public static string GetRelativeTimeDescription(DateTime time) { var span = DateTime.Now - time.ToLocalTime(); if (span.TotalSeconds < 60) return "现在"; if (span.TotalMinutes < 60) return $"{(int)span.TotalMinutes} 分钟前"; if (span.TotalHours < 24) return $"{(int)span.TotalHours} 小时前"; if (span.TotalDays < 7) return $"{(int)span.TotalDays} 天前"; return time.ToLocalTime().ToString("yyyy年MM月dd日 HH:mm"); } public static string GetRelativeTimeDescription(string time) => DateTime.TryParse(time, out var dateTime) ? GetRelativeTimeDescription(dateTime) : "暂无时间"; }