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 System.Text.RegularExpressions;
using XFENewsApplication.Core.Models;

namespace XFENewsApplication.Core.Utilities.Helpers;

/// <summary>Parses provider responses without executing website code or creating UI objects.</summary>
public static class VideoContentHelper
{
    private static readonly Regex CctvVideoPlaceholder = new(
        @"(?:\[!--|<!--|&lt;!--)\s*begin:htmlVideoCode\s*(?:--\]|-->|--&gt;)(?<payload>[\s\S]*?)(?:\[!--|<!--|&lt;!--)\s*end:htmlVideoCode\s*(?:--\]|-->|--&gt;)",
        RegexOptions.IgnoreCase | RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1));

    public static string ExtractCctvVideoId(string html) => ExtractCctvVideoIds(html).FirstOrDefault() ?? string.Empty;

    public static IReadOnlyList<string> ExtractCctvVideoIds(string html)
    {
        var body = ExtractCctvArticleBody(html);
        var ids = CctvVideoPlaceholder.Matches(body.Length > 0 ? body : html)
            .Select(ReadCctvPlaceholderId).Where(id => id.Length > 0).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
        if (ids.Count > 0)
            return ids;
        // Standalone CCTV video pages expose the main player ID as a JavaScript variable.
        var id = Regex.Match(html, "\\b(?:guid|videoCenterId|videoId)\\s*[:=]\\s*['\"](?<id>[a-fA-F0-9]{32})['\"]",
            RegexOptions.IgnoreCase, TimeSpan.FromSeconds(1)).Groups["id"].Value;
        return id.Length > 0 ? [id] : [];
    }

    /// <summary>Turns CCTV CMS video slots into article video elements at their original positions.</summary>
    public static string ExpandCctvVideoPlaceholders(string html) => CctvVideoPlaceholder.Replace(html, match =>
    {
        var id = ReadCctvPlaceholderId(match);
        return id.Length > 0 ? $"<video id=\"{id}\"></video>" : "<span>视频暂不可用,请在原网页观看。</span>";
    });

    private static string ReadCctvPlaceholderId(Match placeholder) => Regex.Match(
        WebUtility.HtmlDecode(placeholder.Groups["payload"].Value), @"^\s*(?<id>[a-fA-F0-9]{32})(?:\s*,|\s*$)",
        RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1)).Groups["id"].Value.ToLowerInvariant();

    public static VideoManifest ParseCctvManifest(string json)
    {
        using var document = JsonDocument.Parse(json);
        var root = document.RootElement;
        var canPlay = GetString(root, "ack") == "yes" && GetString(root, "is_protected") != "1" && GetString(root, "is_invalid_copyright") != "1";
        var source = NormalizeUrl(GetString(root, "hls_url"));
        var chapters = new List<string>();
        if (root.ValueKind == JsonValueKind.Object && root.TryGetProperty("video", out var streams) && streams.ValueKind == JsonValueKind.Object)
        {
            var preferred = GetString(root, "default_stream");
            var selected = preferred.Length > 0 && streams.TryGetProperty(preferred, out var value) ? value : default;
            if (selected.ValueKind != JsonValueKind.Array)
                selected = streams.TryGetProperty("chapters", out value) ? value : default;
            if (selected.ValueKind == JsonValueKind.Array)
                chapters = selected.EnumerateArray().Select(chapter => NormalizeUrl(GetString(chapter, "url"))).Where(url => url.Length > 0).ToList();
            if (source.Length == 0) source = NormalizeUrl(GetString(streams, "url"));
        }
        if (source.Length == 0) source = chapters.FirstOrDefault() ?? string.Empty;
        return new VideoManifest
        {
            Title = GetString(root, "title"), PosterUrl = NormalizeUrl(GetString(root, "image")),
            SourceUrl = canPlay ? source : string.Empty,
            ChapterUrls = canPlay ? chapters : [],
            CanPlay = canPlay && source.Length > 0
        };
    }

    public static string ExtractCctvArticleBody(string html)
    {
        var content = ReadJavaScriptString(html, "contentdate");
        return content.Length > 0 ? content : ReadJavaScriptString(html, "contentData");
    }

    public static string ReadJavaScriptString(string html, string variable)
    {
        var pattern = "\\b(?:var\\s+|let\\s+|const\\s+)?" + Regex.Escape(variable) + "\\s*=\\s*(?<quote>['\"])(?<text>(?:\\\\[\\s\\S]|(?!\\k<quote>)[^\\\\])*)\\k<quote>";
        var match = Regex.Match(html, pattern, RegexOptions.None, TimeSpan.FromSeconds(1));
        if (!match.Success) return string.Empty;
        return Regex.Replace(match.Groups["text"].Value, "\\\\(?:u(?<unicode>[0-9a-fA-F]{4})|x(?<hex>[0-9a-fA-F]{2})|(?<escape>\\r\\n|[\\s\\S]))", escape =>
        {
            if (escape.Groups["unicode"].Success) return ((char)Convert.ToInt32(escape.Groups["unicode"].Value, 16)).ToString();
            if (escape.Groups["hex"].Success) return ((char)Convert.ToInt32(escape.Groups["hex"].Value, 16)).ToString();
            return escape.Groups["escape"].Value switch
            {
                "n" => "\n", "r" => "\r", "t" => "\t", "b" => "\b", "f" => "\f", "v" => "\v",
                "\r" or "\n" or "\r\n" => string.Empty, var literal => literal
            };
        }, RegexOptions.None, TimeSpan.FromSeconds(1));
    }

    public static IReadOnlyList<string> ExtractMsnVideoUrls(JsonElement resource) => FindMsnVideoUrls(resource)
        .Select(url => NormalizeUrl(url)).Where(url => url.Length > 0).Distinct(StringComparer.Ordinal).ToList();

    public static string ExtractMsnVideoId(string reference)
    {
        var id = WebUtility.HtmlDecode(reference).Trim().Trim('"').Split('/').Last();
        return Regex.IsMatch(id, "^[A-Za-z0-9_-]{1,128}$", RegexOptions.None, TimeSpan.FromSeconds(1)) ? id : string.Empty;
    }

    private static IEnumerable<string> FindMsnVideoUrls(JsonElement element, int depth = 0)
    {
        if (depth > 8) yield break;
        if (element.ValueKind == JsonValueKind.Array)
            foreach (var child in element.EnumerateArray()) foreach (var url in FindMsnVideoUrls(child, depth + 1)) yield return url;
        else if (element.ValueKind == JsonValueKind.Object)
        {
            var mediaFormat = new[] { "mimeType", "contentType", "format", "fileType", "type" }
                .Select(name => GetString(element, name)).Any(value => value.Equals("mp4", StringComparison.OrdinalIgnoreCase) ||
                    value.Equals("hls", StringComparison.OrdinalIgnoreCase) || value.StartsWith("video/", StringComparison.OrdinalIgnoreCase) || value.Contains("mpegurl", StringComparison.OrdinalIgnoreCase));
            foreach (var property in element.EnumerateObject())
            {
                if (property.Value.ValueKind == JsonValueKind.String)
                {
                    var normalized = NormalizeUrl(property.Value.GetString());
                    if (normalized.Length > 0 && Uri.TryCreate(normalized, UriKind.Absolute, out var uri) &&
                        (uri.AbsolutePath.EndsWith(".mp4", StringComparison.OrdinalIgnoreCase) || uri.AbsolutePath.EndsWith(".m3u8", StringComparison.OrdinalIgnoreCase) ||
                         mediaFormat && (property.Name.Equals("url", StringComparison.OrdinalIgnoreCase) || property.Name.Equals("src", StringComparison.OrdinalIgnoreCase)))) yield return normalized;
                }
                else if (property.Value.ValueKind is JsonValueKind.Object or JsonValueKind.Array)
                    foreach (var url in FindMsnVideoUrls(property.Value, depth + 1)) yield return url;
            }
        }
    }

    public static string NormalizeUrl(string? value, string pageUrl = "")
    {
        if (string.IsNullOrWhiteSpace(value)) return string.Empty;
        value = WebUtility.HtmlDecode(value).Trim();
        if (value.StartsWith("//")) value = "https:" + value;
        if (!Uri.TryCreate(value, UriKind.Absolute, out var uri) && Uri.TryCreate(pageUrl, UriKind.Absolute, out var baseUri)) Uri.TryCreate(baseUri, value, out uri);
        return uri is not null && (uri.Scheme == "https" || uri.Scheme == "http") ? uri.AbsoluteUri : string.Empty;
    }

    private static string GetString(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;
}