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

XFEEDToolBox

【WinUI】XFE精英危险工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Globalization;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;

namespace XFEEDToolBox.Core.News;

public sealed record GalnetSlide(GalnetArticle Article, string Image, string Title, string Teaser, string Body, bool PreviewTranslated = false, bool BodyTranslated = false, string TranslationStatus = "正在自动翻译…")
{
    public string Id => Article.Id;
    public string Date => Article.PublishedAt?.ToString("yyyy年M月d日", CultureInfo.InvariantCulture) ?? Article.GameDate;
    public string OriginalTitle => Article.Title;
    public string OriginalBody => Article.Body;
    public string Link => Article.Link;
    public static string Preview(string body)
    {
        var paragraph = body.Split('\n', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? body;
        return paragraph.Length <= 170 ? paragraph : paragraph[..167] + "…";
    }
}

/// <summary>Reads only official article metadata; site scripts and article HTML are never executed.</summary>
public sealed class GalnetMediaCatalog(string cachePath, HttpClient? client = null)
{
    private static readonly HttpClient SharedClient = new() { Timeout = TimeSpan.FromSeconds(30) };
    private static readonly TimeSpan RegexTimeout = TimeSpan.FromSeconds(1);
    private readonly HttpClient http = client ?? SharedClient;
    private readonly Dictionary<string, string> images = new(StringComparer.OrdinalIgnoreCase);
    private bool loaded;
    private DateTimeOffset retrievedAt;
    private sealed record Cache(DateTimeOffset At, Dictionary<string, string> Images);

    public static Uri ArticleUri(GalnetArticle article) => article.SourceUri is { Host: "www.elitedangerous.com" } source ? source
        : new("https://www.elitedangerous.com/news/galnet/" + Regex.Replace(article.Title.ToLowerInvariant(), "[^a-z0-9]+", "-", RegexOptions.None, RegexTimeout).Trim('-'));

    public static bool AllowedImage(string? value) => Uri.TryCreate(value, UriKind.Absolute, out var uri)
        && uri.Scheme == "https" && uri.IsDefaultPort && uri.UserInfo.Length == 0 && value.Length < 8192
        && uri.Host is "image-service.zaonce.net" or "static.zaonce.net" or "www.elitedangerous.com";

    public async Task LoadAsync(CancellationToken token)
    {
        if (loaded) return;
        loaded = true;
        try
        {
            if (!File.Exists(cachePath) || new FileInfo(cachePath).Length > 500_000) return;
            var saved = JsonSerializer.Deserialize<Cache>(await File.ReadAllTextAsync(cachePath, token));
            if (saved?.Images is null) return;
            foreach (var pair in saved.Images.Take(100))
                if (GalnetRss.OfficialUri(pair.Key) is not null && AllowedImage(pair.Value)) images[pair.Key] = pair.Value;
            retrievedAt = saved.At <= DateTimeOffset.UtcNow ? saved.At : default;
        }
        catch (OperationCanceledException) { loaded = false; throw; }
        catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException) { }
    }

    public string Image(GalnetArticle article) => images.GetValueOrDefault(ArticleUri(article).AbsoluteUri, "");

    public async Task RefreshAsync(GalnetNewsSnapshot snapshot, CancellationToken token)
    {
        await LoadAsync(token).ConfigureAwait(false);
        if (snapshot.Articles.Count == 0 || DateTimeOffset.UtcNow - retrievedAt < TimeSpan.FromHours(6) && snapshot.Articles.Take(6).All(a => Image(a).Length > 0)) return;
        // The official listing supplies all current cover images in one read;
        // an individual article's sidebar only supplies its three latest items.
        var uri = new Uri("https://www.elitedangerous.com/news/galnet");
        using var request = new HttpRequestMessage(HttpMethod.Get, uri);
        request.Headers.UserAgent.ParseAdd("XFEEDToolBox-Galnet/1.0");
        request.Headers.Accept.ParseAdd("text/html");
        using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false);
        response.EnsureSuccessStatusCode();
        var html = await NewsHttp.ReadAsync(response.Content, 8_000_000, token).ConfigureAwait(false);
        var parsed = Parse(html, uri);
        if (parsed.Count == 0) throw new InvalidDataException("官网暂未返回新闻配图。");
        foreach (var pair in parsed) images[pair.Key] = pair.Value;
        retrievedAt = DateTimeOffset.UtcNow;
        try { await NewsHttp.SaveAsync(cachePath, new Cache(retrievedAt, images.TakeLast(100).ToDictionary()), token).ConfigureAwait(false); }
        catch (Exception error) when (error is IOException or UnauthorizedAccessException) { }
    }

    public static IReadOnlyDictionary<string, string> Parse(string html, Uri source)
    {
        var result = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
        string Attribute(string markup, string name)
        {
            var match = Regex.Match(markup, $"\\b{Regex.Escape(name)}\\s*=\\s*([\"'])(.*?)\\1", RegexOptions.Singleline | RegexOptions.IgnoreCase, RegexTimeout);
            return WebUtility.HtmlDecode(match.Groups[2].Value);
        }
        foreach (Match meta in Regex.Matches(html, "<meta\\b[^>]*>", RegexOptions.IgnoreCase, RegexTimeout))
            if (Attribute(meta.Value, "property") == "og:image" && AllowedImage(Attribute(meta.Value, "content"))) result[source.AbsoluteUri] = Attribute(meta.Value, "content");
        foreach (Match card in Regex.Matches(html, "<article\\b[^>]*class=[\"'](?:c-galnet-latest__article|c-galnet-listing__item)[\"'][^>]*>[\\s\\S]*?</article>", RegexOptions.IgnoreCase, RegexTimeout))
        {
            var anchor = Regex.Match(card.Value, "<a\\b[^>]*>", RegexOptions.IgnoreCase, RegexTimeout);
            var image = Regex.Match(card.Value, "<img\\b[^>]*>", RegexOptions.IgnoreCase, RegexTimeout);
            var link = Attribute(anchor.Value, "href"); var src = Attribute(image.Value, "src");
            if (link.Length > 0 && Uri.TryCreate(source, link, out var uri) && GalnetRss.OfficialUri(uri.AbsoluteUri) is not null && AllowedImage(src)) result[uri.AbsoluteUri] = src;
        }
        return result;
    }
}

/// <summary>Automatic Chinese translation of public news, with a content-addressed persistent cache.</summary>
public sealed class GalnetNewsTranslator(string cachePath, HttpClient? client = null)
{
    private static readonly HttpClient SharedClient = new() { Timeout = TimeSpan.FromSeconds(15) };
    private readonly HttpClient http = client ?? SharedClient;
    private readonly SemaphoreSlim gate = new(1, 1);
    private readonly Dictionary<string, string> cache = [];
    private bool loaded;
    private DateTimeOffset retryAfter;

    public async Task<string?> CachedAsync(string text, CancellationToken token)
    {
        await gate.WaitAsync(token).ConfigureAwait(false);
        try { await LoadCoreAsync(token).ConfigureAwait(false); return cache.GetValueOrDefault(Key(text)); }
        finally { gate.Release(); }
    }

    public async Task<string> TranslateAsync(string text, CancellationToken token)
    {
        if (string.IsNullOrWhiteSpace(text)) return text;
        await gate.WaitAsync(token).ConfigureAwait(false);
        try
        {
            await LoadCoreAsync(token).ConfigureAwait(false);
            var key = Key(text);
            if (cache.TryGetValue(key, out var saved)) return saved;
            if (DateTimeOffset.UtcNow < retryAfter) throw new HttpRequestException("自动翻译服务暂时不可用,稍后会重试。");
            var paragraphs = new List<string>();
            foreach (var paragraph in text.Split('\n', StringSplitOptions.RemoveEmptyEntries))
            {
                var chunks = new List<string>();
                foreach (var chunk in Chunks(paragraph))
                {
                    var chunkKey = Key(chunk);
                    if (cache.TryGetValue(chunkKey, out var cached)) { chunks.Add(cached); continue; }
                    using var request = new HttpRequestMessage(HttpMethod.Get, "https://api.mymemory.translated.net/get?langpair=en%7Czh-CN&q=" + Uri.EscapeDataString(chunk));
                    request.Headers.UserAgent.ParseAdd("XFEEDToolBox-Galnet/1.0");
                    using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false);
                    if ((int)response.StatusCode == 429) { retryAfter = DateTimeOffset.UtcNow.AddHours(1); throw new HttpRequestException("自动翻译服务额度暂时不足。"); }
                    response.EnsureSuccessStatusCode();
                    using var json = JsonDocument.Parse(await NewsHttp.ReadAsync(response.Content, 200_000, token).ConfigureAwait(false));
                    var root = json.RootElement;
                    if (!root.TryGetProperty("responseStatus", out var status) || status.GetInt32() != 200)
                    {
                        retryAfter = DateTimeOffset.UtcNow.AddHours(1);
                        throw new HttpRequestException("自动翻译服务暂时不可用,稍后会重试。");
                    }
                    var translated = WebUtility.HtmlDecode(root.GetProperty("responseData").GetProperty("translatedText").GetString());
                    if (string.IsNullOrWhiteSpace(translated) || translated.Length > 20_000 || translated.StartsWith("MYMEMORY WARNING", StringComparison.OrdinalIgnoreCase))
                        throw new InvalidDataException("翻译服务未返回有效译文。");
                    cache[chunkKey] = translated; chunks.Add(translated);
                }
                paragraphs.Add(string.Concat(chunks));
            }
            var result = string.Join("\n\n", paragraphs);
            token.ThrowIfCancellationRequested();
            cache[key] = result;
            try { await NewsHttp.SaveAsync(cachePath, cache.TakeLast(800).ToDictionary(), token).ConfigureAwait(false); }
            catch (Exception error) when (error is IOException or UnauthorizedAccessException) { }
            return result;
        }
        finally { gate.Release(); }
    }

    private async Task LoadCoreAsync(CancellationToken token)
    {
        if (loaded) return;
        loaded = true;
        try
        {
            if (!File.Exists(cachePath) || new FileInfo(cachePath).Length > 4_000_000) return;
            var saved = JsonSerializer.Deserialize<Dictionary<string, string>>(await File.ReadAllTextAsync(cachePath, token));
            if (saved is not null) foreach (var pair in saved.TakeLast(800))
                if (pair.Key.Length == 64 && pair.Value is { Length: > 0 and <= 150_000 }) cache[pair.Key] = pair.Value;
        }
        catch (OperationCanceledException) { loaded = false; throw; }
        catch (Exception error) when (error is IOException or UnauthorizedAccessException or JsonException) { }
    }
    private static string Key(string text) => Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes("zh-CN\0" + text)));
    public static IEnumerable<string> Chunks(string text)
    {
        // The public service limits each query to 500 UTF-8 bytes. Keep both
        // surrogate pairs and word boundaries intact, with headroom for spaces.
        while (text.Length > 0)
        {
            var length = 0; var bytes = 0;
            foreach (var rune in text.EnumerateRunes())
            {
                if (bytes + rune.Utf8SequenceLength > 450) break;
                bytes += rune.Utf8SequenceLength; length += rune.Utf16SequenceLength;
            }
            if (length < text.Length && text.LastIndexOf(' ', length - 1, length) is var space && space > length / 2) length = space + 1;
            yield return text[..length]; text = text[length..];
        }
    }
}

internal static class NewsHttp
{
    public static async Task<string> ReadAsync(HttpContent content, int limit, CancellationToken token)
    {
        if (content.Headers.ContentLength > limit) throw new InvalidDataException("新闻响应超过读取上限。");
        await using var stream = await content.ReadAsStreamAsync(token).ConfigureAwait(false);
        using var output = new MemoryStream(); var buffer = new byte[8192]; int count;
        while ((count = await stream.ReadAsync(buffer, token).ConfigureAwait(false)) > 0)
        {
            if (output.Length + count > limit) throw new InvalidDataException("新闻响应超过读取上限。");
            output.Write(buffer, 0, count);
        }
        return Encoding.UTF8.GetString(output.ToArray());
    }
    public static async Task SaveAsync<T>(string path, T value, CancellationToken token)
    {
        Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
        var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
        try { await File.WriteAllTextAsync(temporary, JsonSerializer.Serialize(value), token).ConfigureAwait(false); token.ThrowIfCancellationRequested(); File.Move(temporary, path, true); }
        finally { if (File.Exists(temporary)) File.Delete(temporary); }
    }
}