using System.Globalization; using XFENewsApplication.Core.Models; namespace XFENewsApplication.Core.Utilities; /// Builds anonymous requests using parameters observed in the MSN first-party web client. public static class MsnFeedRequestBuilder { public static string NormalizeAnonymousUserId(string? userId) { var value = userId?.Trim() ?? string.Empty; if (value.StartsWith("m-", StringComparison.OrdinalIgnoreCase)) value = value[2..]; return Guid.TryParse(value, out var guid) ? $"m-{guid.ToString("N").ToUpperInvariant()}" : string.Empty; } public static bool IsTrustedFeedUrl(string? value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps && uri.IsDefaultPort && string.IsNullOrEmpty(uri.UserInfo) && (uri.Host.Equals("api.msn.com", StringComparison.OrdinalIgnoreCase) || uri.Host.Equals("assets.msn.com", StringComparison.OrdinalIgnoreCase) || uri.Host.Equals("assets.msn.cn", StringComparison.OrdinalIgnoreCase)) && (uri.AbsolutePath.Equals("/news/feed/pages/weblayout", StringComparison.OrdinalIgnoreCase) || uri.AbsolutePath.Equals("/service/news/feed/pages/weblayout", StringComparison.OrdinalIgnoreCase)); public static string Build(string feedDomain, string apiKey, MsnFeedOptions options, int skip = 0, int lastCardCount = 0, int servedCardCount = 0, string? nextPageUrl = null) { ArgumentNullException.ThrowIfNull(options); var user = NormalizeAnonymousUserId(options.UserId); if (user.Length == 0) throw new ArgumentException("MSN 匿名用户 ID 必须是有效的 GUID。", nameof(options)); if (!Guid.TryParse(options.ActivityId, out var activity)) throw new ArgumentException("MSN 会话 ID 必须是有效的 GUID。", nameof(options)); var uri = !string.IsNullOrWhiteSpace(nextPageUrl) ? IsTrustedFeedUrl(nextPageUrl) ? new Uri(nextPageUrl) : throw new ArgumentException("MSN 返回了无效的下一页地址。", nameof(nextPageUrl)) : new Uri(new Uri(feedDomain), "/service/news/feed/pages/weblayout"); var query = ParseQuery(uri.Query); query["apikey"] = apiKey; query["user"] = user; query["activityId"] = activity.ToString(); // Account-specific scn/it values are omitted for anonymous app users. query.Remove("scn"); query.Remove("it"); if (string.IsNullOrWhiteSpace(nextPageUrl)) { query["cm"] = "zh-cn"; query["ocid"] = "hponeservicefeed"; query["audienceMode"] = "adult"; query["contentType"] = "article,video,slideshow"; query["$skip"] = Math.Max(0, skip).ToString(CultureInfo.InvariantCulture); query["newsTop"] = Math.Clamp(options.PageSize, 1, 100).ToString(CultureInfo.InvariantCulture); query["layout"] = "c2"; query["column"] = "c2"; query["colwidth"] = "300"; query["colstatus"] = "c1:0,c2:0"; query["adoffsets"] = "c1:-1,c2:-1"; query["vpSize"] = "721x674"; query["wposchema"] = "byregion"; query["l3v"] = "2"; query["timeOut"] = "2000"; if (skip == 0) query["newsSkip"] = "0"; if (lastCardCount > 0) query["lastcardrank"] = lastCardCount.ToString(CultureInfo.InvariantCulture); if (servedCardCount > 0) query["cardsServed"] = servedCardCount.ToString(CultureInfo.InvariantCulture); } return new UriBuilder(uri) { Fragment = string.Empty, Query = string.Join('&', query.Select(pair => $"{Uri.EscapeDataString(pair.Key)}={Uri.EscapeDataString(pair.Value)}")) }.Uri.AbsoluteUri; } internal static Dictionary ParseQuery(string? query) { Dictionary values = new(StringComparer.OrdinalIgnoreCase); foreach (var part in (query ?? string.Empty).TrimStart('?').Split('&', StringSplitOptions.RemoveEmptyEntries)) { var pair = part.Split('=', 2); values[Uri.UnescapeDataString(pair[0])] = pair.Length > 1 ? Uri.UnescapeDataString(pair[1]) : string.Empty; } return values; } }