using System.Net; using System.Text.Json; using System.Text.RegularExpressions; using XFENewsApplication.Core.Models; namespace XFENewsApplication.Core.Utilities.Helpers; public static class ClimbHelper { private static readonly HttpClient Client = CreateClient(); private static readonly SemaphoreSlim ConfigurationLock = new(1, 1); private static DateTimeOffset configurationExpires; private static string feedDomain = "https://assets.msn.cn"; public static string? MSNAPI { get; set; } public static string? ActiveId { get; set; } = Guid.NewGuid().ToString(); public static string? UserId { get; set; } = Guid.NewGuid().ToString("N"); public static async Task GetMSNAPI(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); await ConfigurationLock.WaitAsync(cancellationToken); try { if (!string.IsNullOrWhiteSpace(MSNAPI) && configurationExpires > DateTimeOffset.UtcNow) return MSNAPI; // Read the current build and service hosts from MSN instead of pinning a resolver version. var html = await GetStringAsync("https://www.msn.cn/zh-cn", cancellationToken); var settingsAttribute = Regex.Match(html, "data-client-settings=\"([^\"]+)\"", RegexOptions.IgnoreCase); if (!settingsAttribute.Success) throw new InvalidDataException("MSN 首页配置格式已改变。"); using var settingsDocument = JsonDocument.Parse(WebUtility.HtmlDecode(settingsAttribute.Groups[1].Value)); var settings = settingsDocument.RootElement; var endpoints = settings.GetProperty("servicesEndpoints"); var crs = endpoints.GetProperty("crs"); var crsDomain = MsnFeedParser.String(crs, "domain") ?? string.Empty; var crsPath = MsnFeedParser.String(crs, "path") ?? "/resolver/api/resolve/"; var crsVersion = MsnFeedParser.String(crs, "v") ?? "v3"; var discoveredFeedDomain = MsnFeedParser.String(endpoints.GetProperty("feedService"), "domain") ?? string.Empty; if (!IsTrustedServiceDomain(crsDomain) || !IsTrustedServiceDomain(discoveredFeedDomain) || !crsPath.StartsWith("/resolver/api/resolve/", StringComparison.Ordinal)) throw new InvalidDataException("MSN 首页返回了无效的服务地址。"); var browser = settings.GetProperty("browser"); if (browser.TryGetProperty("detected", out var detectedBrowser)) browser = detectedBrowser; var scope = new { audienceMode = "adult", browser, deviceFormFactor = MsnFeedParser.String(settings, "deviceFormFactor") ?? "desktop", domain = MsnFeedParser.String(settings, "domain") ?? "www.msn.cn", locale = settings.GetProperty("locale"), os = "windows", platform = "web", pageType = "hp", pageExperiments = Array.Empty() }; var build = MsnFeedParser.String(settings.GetProperty("bundleInfo"), "v"); var resolver = new Uri(new Uri(crsDomain), $"{crsPath.TrimEnd('/')}/{Uri.EscapeDataString(crsVersion)}/config/"); var configUrl = $"{resolver}?expType=AppConfig&expInstance=default&apptype=homePage&v={Uri.EscapeDataString(build ?? string.Empty)}&targetScope={Uri.EscapeDataString(JsonSerializer.Serialize(scope))}"; var configuration = await GetStringAsync(configUrl, cancellationToken); var key = ParseMSNApiKey(configuration); feedDomain = discoveredFeedDomain; MSNAPI = key; configurationExpires = DateTimeOffset.UtcNow.AddHours(6); return key; } finally { ConfigurationLock.Release(); } } public static string ParseMSNApiKey(string configuration) { using var document = JsonDocument.Parse(configuration); var key = MsnFeedParser.String(document.RootElement.GetProperty("configs") .GetProperty("StripeWC/default").GetProperty("properties"), "apikey"); return !string.IsNullOrWhiteSpace(key) ? key : throw new InvalidDataException("MSN 配置未提供新闻服务密钥。"); } public static Task ClimbMSNNews(CancellationToken cancellationToken, int skip = 0, int lastCardCount = 0, int servedCardCount = 0) => ClimbMSNNews(cancellationToken, new MsnFeedOptions { UserId = UserId, ActivityId = ActiveId }, skip, lastCardCount, servedCardCount); public static async Task ClimbMSNNews(CancellationToken cancellationToken, MsnFeedOptions options, int skip = 0, int lastCardCount = 0, int servedCardCount = 0, string? nextPageUrl = null) { try { for (var attempt = 0; attempt < 2; attempt++) { var apiKey = await GetMSNAPI(cancellationToken); var requestUrl = MsnFeedRequestBuilder.Build(feedDomain, apiKey, options, skip, lastCardCount, servedCardCount, nextPageUrl); try { var json = await GetStringAsync(requestUrl, cancellationToken, options.UserId); return MsnFeedParser.Parse(json, skip); } catch (HttpRequestException ex) when (attempt == 0 && (ex.StatusCode == HttpStatusCode.Unauthorized || ex.StatusCode == HttpStatusCode.Forbidden)) { // A rotated key is refreshed once; ordinary failures do not reset the continuation. configurationExpires = DateTimeOffset.MinValue; } } return Failure("无法获取 MSN 新闻,请稍后重试。"); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } catch (Exception ex) when (ex is HttpRequestException or JsonException or InvalidDataException or KeyNotFoundException or InvalidOperationException or ArgumentException or OperationCanceledException) { return Failure("无法获取 MSN 新闻,请检查网络连接或稍后重试。"); } } public static async Task ClimbMSNNews(string requestUrl, CancellationToken cancellationToken) { if (!MsnFeedRequestBuilder.IsTrustedFeedUrl(requestUrl)) return Failure("MSN 新闻服务地址无效。"); try { var json = await GetStringAsync(requestUrl, cancellationToken); var query = MsnFeedRequestBuilder.ParseQuery(new Uri(requestUrl).Query); var skip = query.TryGetValue("$skip", out var value) && int.TryParse(value, out var page) ? page : 0; return MsnFeedParser.Parse(json, skip); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException) { return Failure("无法获取 MSN 新闻,请检查网络连接或稍后重试。"); } } public static async Task ClimbCCTVNews(CancellationToken cancellationToken, int skip = 1, string type = "news") { if (!Regex.IsMatch(type, "^[a-zA-Z0-9_-]+$")) return Failure("央视新闻分类无效。"); try { var page = Math.Max(1, skip); var jsonp = await GetStringAsync($"https://news.cctv.com/2019/07/gaiban/cmsdatainterface/page/{type}_{page}.jsonp?cb={type}", cancellationToken); var result = ParseCCTVFeed(jsonp); result.NextSkip = page + 1; return result; } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } catch (Exception ex) when (ex is HttpRequestException or OperationCanceledException) { return Failure("无法获取央视新闻,请检查网络连接或稍后重试。"); } } public static NewsResult ParseCCTVFeed(string jsonp) { try { var value = jsonp.Trim(); if (!value.StartsWith('{')) { var wrapper = Regex.Match(value, "^[a-zA-Z_$][a-zA-Z0-9_.$]*\\s*\\(([\\s\\S]*)\\)\\s*;?$"); if (!wrapper.Success) return Failure("央视新闻响应不是有效的 JSONP。"); value = wrapper.Groups[1].Value; } using var document = JsonDocument.Parse(value); if (document.RootElement.ValueKind != JsonValueKind.Object || !document.RootElement.TryGetProperty("data", out var data) || data.ValueKind != JsonValueKind.Object || !data.TryGetProperty("list", out var list) || list.ValueKind != JsonValueKind.Array) return Failure("央视新闻响应格式已改变。"); NewsFeedCache unique = new(); unique.AddUnique(list.EnumerateArray().Select(node => new NewsSource { Title = WebUtility.HtmlDecode(MsnFeedParser.String(node, "title") ?? string.Empty), ID = MsnFeedParser.String(node, "id"), Url = MsnFeedParser.String(node, "url") ?? string.Empty, Abstract = WebUtility.HtmlDecode(MsnFeedParser.String(node, "brief")), ImageUrl = MsnFeedParser.String(node, "image"), PublishTime = MsnFeedParser.String(node, "focus_date"), Source = "CCTV" }).Where(news => !string.IsNullOrWhiteSpace(news.Title) && !string.IsNullOrWhiteSpace(news.Url))); return new NewsResult { NewsSourceList = unique.Items, Success = true, Message = "Success", Count = unique.Items.Count, HasMore = list.GetArrayLength() > 0 }; } catch (JsonException) { return Failure("央视新闻响应不是有效的 JSON。"); } } public static async Task ClimbWeiboHotSearch(CancellationToken cancellationToken) { try { var json = await GetStringAsync("https://m.weibo.cn/api/container/getIndex?containerid=106003type%3D25%26t%3D3%26disable_hot%3D1%26filter_type%3Drealtimehot&luicode=20000061&lfid=5070140584495876", cancellationToken); using var document = JsonDocument.Parse(json); List results = []; foreach (var card in document.RootElement.GetProperty("data").GetProperty("cards").EnumerateArray()) { if (!card.TryGetProperty("card_group", out var group) || group.ValueKind != JsonValueKind.Array) continue; foreach (var node in group.EnumerateArray()) { var heat = ValueText(node, "desc_extr"); var title = MsnFeedParser.String(node, "desc"); if (string.IsNullOrWhiteSpace(heat) || string.IsNullOrWhiteSpace(title)) continue; results.Add(new NewsSource { Title = WebUtility.HtmlDecode(title), Abstract = heat, Source = "微博热搜", ImageWidth = 30, ImageHeight = 30, Index = results.Count + 1, ImageUrl = MsnFeedParser.String(node, "icon") }); } } return HotSearchResult(results); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } catch (Exception ex) when (ex is HttpRequestException or JsonException or KeyNotFoundException or InvalidOperationException or OperationCanceledException) { return Failure("无法获取微博热搜,请稍后重试。"); } } public static async Task ClimbBilibiliHotSearch(CancellationToken cancellationToken) { try { var json = await GetStringAsync("https://api.bilibili.com/x/web-interface/search/square?limit=50&platform=web&web_location=333.1007", cancellationToken); using var document = JsonDocument.Parse(json); List results = []; foreach (var node in document.RootElement.GetProperty("data").GetProperty("trending").GetProperty("list").EnumerateArray()) { var title = MsnFeedParser.String(node, "keyword"); if (string.IsNullOrWhiteSpace(title)) continue; results.Add(new NewsSource { Title = title, Abstract = ValueText(node, "heat_score"), Source = "B站热搜", ImageWidth = double.MaxValue, ImageHeight = 18, Index = results.Count + 1, ImageUrl = MsnFeedParser.String(node, "icon") }); } return HotSearchResult(results); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { throw; } catch (Exception ex) when (ex is HttpRequestException or JsonException or KeyNotFoundException or InvalidOperationException or OperationCanceledException) { return Failure("无法获取 B 站热搜,请稍后重试。"); } } private static string? ValueText(JsonElement node, string name) => node.TryGetProperty(name, out var value) && value.ValueKind != JsonValueKind.Null ? value.ToString() : null; private static NewsResult HotSearchResult(List items) => new() { NewsSourceList = items, Success = items.Count > 0, Message = items.Count > 0 ? "Success" : "没有获取到数据", Count = items.Count }; private static NewsResult Failure(string message) => new() { Success = false, Message = message }; private static bool IsTrustedServiceDomain(string value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps && uri.IsDefaultPort && string.IsNullOrEmpty(uri.UserInfo) && uri.AbsolutePath == "/" && (uri.Host.Equals("assets.msn.cn", StringComparison.OrdinalIgnoreCase) || uri.Host.Equals("assets.msn.com", StringComparison.OrdinalIgnoreCase) || uri.Host.Equals("www.msn.cn", StringComparison.OrdinalIgnoreCase) || uri.Host.Equals("www.msn.com", StringComparison.OrdinalIgnoreCase)); private static HttpClient CreateClient() { var client = new HttpClient(new HttpClientHandler { UseCookies = false }) { Timeout = TimeSpan.FromSeconds(30) }; client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/537.36 XFENewsApplication/1.0"); client.DefaultRequestHeaders.Accept.ParseAdd("application/json, text/html;q=0.9, */*;q=0.8"); return client; } private static async Task GetStringAsync(string url, CancellationToken cancellationToken, string? userId = null) { for (var attempt = 0; ; attempt++) { cancellationToken.ThrowIfCancellationRequested(); try { using var request = new HttpRequestMessage(HttpMethod.Get, url); var anonymousId = MsnFeedRequestBuilder.NormalizeAnonymousUserId(userId); if (anonymousId.Length > 0) request.Headers.TryAddWithoutValidation("Cookie", $"MUID={anonymousId[2..]}"); using var response = await Client.SendAsync(request, cancellationToken); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(cancellationToken); } catch (HttpRequestException ex) when (attempt < 2 && (ex.StatusCode is null or HttpStatusCode.RequestTimeout or HttpStatusCode.TooManyRequests || (int)ex.StatusCode >= 500)) { await Task.Delay(TimeSpan.FromMilliseconds(250 * (1 << attempt)), cancellationToken); } } } }