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

XFENewsApplication

【WinUI】新闻软件

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

namespace XFENewsApplication.Core.Utilities;

/// <summary>Parses MSN cards without assuming section positions or fixed content-ID lengths.</summary>
public static class MsnFeedParser
{
    public static NewsResult Parse(string json, int skip = 0)
    {
        try
        {
            using var document = JsonDocument.Parse(json);
            var root = document.RootElement;
            if (root.ValueKind != JsonValueKind.Object ||
                !root.TryGetProperty("sections", out var sections) || sections.ValueKind != JsonValueKind.Array)
                return Failure("MSN 新闻响应格式已改变,请稍后重试。");

            NewsFeedCache unique = new();
            List<NewsSource> allCards = [];
            foreach (var section in sections.EnumerateArray())
                allCards.AddRange(ReadCards(section));
            unique.AddUnique(allCards);

            var nextPageUrl = String(root, "nextPageUrl");
            if (!string.IsNullOrWhiteSpace(nextPageUrl) && !MsnFeedRequestBuilder.IsTrustedFeedUrl(nextPageUrl))
                return Failure("MSN 返回了无效的下一页地址。");
            var continuation = MsnFeedRequestBuilder.ParseQuery(Uri.TryCreate(nextPageUrl, UriKind.Absolute, out var nextUri) ? nextUri.Query : null);
            return new NewsResult
            {
                Success = true,
                Message = "Success",
                NewsSourceList = unique.Items,
                IdentityAliases = allCards,
                Count = unique.Items.Count,
                NextPageUrl = string.IsNullOrWhiteSpace(nextPageUrl) ? null : nextPageUrl,
                NextSkip = Number(continuation, "$skip", Math.Max(0, skip) + 1),
                LastCardRank = Number(continuation, "lastcardrank", -1),
                CardsServed = Number(continuation, "cardsServed", -1),
                HasMore = !string.IsNullOrWhiteSpace(nextPageUrl)
            };
        }
        catch (JsonException)
        {
            return Failure("MSN 新闻响应不是有效的 JSON。");
        }
    }

    private static IEnumerable<NewsSource> ReadCards(JsonElement node)
    {
        if (node.ValueKind != JsonValueKind.Object)
            yield break;
        var type = String(node, "type") ?? string.Empty;
        if (type.Equals("nativead", StringComparison.OrdinalIgnoreCase) ||
            type.Equals("displayad", StringComparison.OrdinalIgnoreCase) ||
            type.Equals("ad", StringComparison.OrdinalIgnoreCase))
            yield break;
        if (type.Equals("article", StringComparison.OrdinalIgnoreCase) ||
            type.Equals("video", StringComparison.OrdinalIgnoreCase) ||
            type.Equals("slideshow", StringComparison.OrdinalIgnoreCase))
        {
            var title = String(node, "title");
            var url = String(node, "url");
            if (!string.IsNullOrWhiteSpace(title) && Uri.TryCreate(url, UriKind.Absolute, out var articleUri) &&
                (articleUri.Scheme == Uri.UriSchemeHttps || articleUri.Scheme == Uri.UriSchemeHttp))
            {
                var provider = node.TryGetProperty("provider", out var providerNode) ? String(providerNode, "name") : null;
                var image = node.TryGetProperty("images", out var images) && images.ValueKind == JsonValueKind.Array
                    ? images.EnumerateArray().FirstOrDefault() : default;
                yield return new NewsSource
                {
                    ID = String(node, "id"),
                    Title = WebUtility.HtmlDecode(title),
                    Url = url!,
                    Abstract = WebUtility.HtmlDecode(String(node, "abstract")),
                    Authors = provider,
                    PublishTime = String(node, "publishedDateTime"),
                    ImageUrl = String(image, "url"),
                    ImageWidth = Dimension(image, "width"),
                    ImageHeight = Dimension(image, "height"),
                    Source = "MSN"
                };
            }
        }
        foreach (var property in new[] { "cards", "subCards", "subSections" })
        {
            if (!node.TryGetProperty(property, out var children) || children.ValueKind != JsonValueKind.Array)
                continue;
            foreach (var child in children.EnumerateArray())
                foreach (var article in ReadCards(child))
                    yield return article;
        }
    }

    internal static string? String(JsonElement node, string name) =>
        node.ValueKind == JsonValueKind.Object && node.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String
            ? value.GetString() : null;

    private static double Dimension(JsonElement node, string name) =>
        node.ValueKind == JsonValueKind.Object && node.TryGetProperty(name, out var value) &&
        value.ValueKind == JsonValueKind.Number && value.TryGetDouble(out var number)
            ? number : 0;

    private static int Number(Dictionary<string, string> query, string name, int fallback) =>
        query.TryGetValue(name, out var value) && int.TryParse(value, out var number) && number >= 0 ? number : fallback;

    private static NewsResult Failure(string message) => new() { Message = message, Success = false };
}