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] + "…"; } } /// Reads only official article metadata; site scripts and article HTML are never executed. 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 images = new(StringComparer.OrdinalIgnoreCase); private bool loaded; private DateTimeOffset retrievedAt; private sealed record Cache(DateTimeOffset At, Dictionary 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(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 Parse(string html, Uri source) { var result = new Dictionary(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, "]*>", 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, "]*class=[\"'](?:c-galnet-latest__article|c-galnet-listing__item)[\"'][^>]*>[\\s\\S]*?", RegexOptions.IgnoreCase, RegexTimeout)) { var anchor = Regex.Match(card.Value, "]*>", RegexOptions.IgnoreCase, RegexTimeout); var image = Regex.Match(card.Value, "]*>", 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; } } /// Automatic Chinese translation of public news, with a content-addressed persistent cache. 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 cache = []; private bool loaded; private DateTimeOffset retryAfter; public async Task 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 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(); foreach (var paragraph in text.Split('\n', StringSplitOptions.RemoveEmptyEntries)) { var chunks = new List(); 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>(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 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 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(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); } } }