TaobaoCouponDebugController.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. #if DEBUG
  2. // 1110 临时口令样本统计:本文件只参与 Debug 编译,Release 不包含此接口。
  3. // PID 填在 .temp/1110/taobao-crawler.local.json;Cookie 优先读取 .temp/cookie.txt,UA 优先读取 .temp/ua.txt。
  4. // 这些本地文件已被 .gitignore 排除,更新内容后无需重启服务。
  5. // 使用个人淘宝联盟账号时,PID 必须属于该 Cookie 对应账号;不要沿用生产 aid=133 的 PID。
  6. // 协议来自 molilian.core/Plus/Alimama/parse_endpoint/tool_links.cs(floorId=61446)。
  7. // 直接提交完整原文,避免生产流程的纯口令/其他推广链接预筛选影响此次样本统计。
  8. // 此入口不选号、不写账号表、不调用生产日志计数或账号停用逻辑。
  9. using System.Globalization;
  10. using System.Net;
  11. using System.Text.Json;
  12. using System.Text.RegularExpressions;
  13. using Microsoft.AspNetCore.Mvc;
  14. namespace molilian.api.Controllers;
  15. [ApiController]
  16. [Route("debug/taobao-coupon")]
  17. public sealed class TaobaoCouponDebugController(IWebHostEnvironment environment) : ControllerBase
  18. {
  19. private static readonly HttpClient Client = new(new HttpClientHandler
  20. {
  21. AllowAutoRedirect = false,
  22. UseCookies = false,
  23. UseProxy = false
  24. }) { Timeout = TimeSpan.FromSeconds(45) };
  25. private string ConfigPath => Path.GetFullPath(Path.Combine(
  26. environment.ContentRootPath, "..", ".temp", "1110", "taobao-crawler.local.json"));
  27. private bool IsLocalRequest() => HttpContext.Connection.RemoteIpAddress is { } ip &&
  28. IPAddress.IsLoopback(ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4() : ip);
  29. // 仅读取配置是否就绪,不返回 Cookie 或 _tb_token_;改本地 JSON 后无需重新编译。
  30. [HttpGet("status")]
  31. public async Task<IActionResult> Status(CancellationToken cancellationToken)
  32. {
  33. if (!IsLocalRequest()) return NotFound();
  34. var (config, error) = await ReadConfig(cancellationToken);
  35. return Ok(new { configured = error == null, message = error, pid = config?.Pid,
  36. protocol = "tool_links", configFile = ".temp/1110/taobao-crawler.local.json" });
  37. }
  38. [HttpPost("parse")]
  39. public async Task<IActionResult> Parse([FromBody] ParseInput input, CancellationToken cancellationToken)
  40. {
  41. if (!IsLocalRequest()) return NotFound();
  42. if (string.IsNullOrWhiteSpace(input.S)) return BadRequest(new { message = "口令原文不能为空" });
  43. var (config, error) = await ReadConfig(cancellationToken);
  44. if (config == null || error != null)
  45. return StatusCode(503, new { success = false, stopBatch = true, message = error });
  46. string timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture);
  47. string cna = CookieValue(config.Cookie, "cna");
  48. string variableMap = JsonSerializer.Serialize(new
  49. {
  50. url = input.S,
  51. union_lens = $"b_pvid:a219t._portal_v2_home_plus_index_htm_{timestamp}_{Random.Shared.Next(100000, 999999)}_{cna[..Math.Min(5, cna.Length)]}_mmWuH",
  52. lensScene = "PUB",
  53. spmB = "_portal_v2_tool_links_page_home_index_htm"
  54. });
  55. string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/xt.entry.json?" +
  56. $"t={timestamp}&_tb_token_={Uri.EscapeDataString(CookieValue(config.Cookie, "_tb_token_"))}" +
  57. $"&floorId=61446&refpid={Uri.EscapeDataString(config.Pid)}&variableMap={Uri.EscapeDataString(variableMap)}";
  58. using var request = new HttpRequestMessage(HttpMethod.Get, url);
  59. request.Headers.TryAddWithoutValidation("Cookie", config.Cookie);
  60. request.Headers.TryAddWithoutValidation("User-Agent", config.UserAgent);
  61. request.Headers.TryAddWithoutValidation("X-Requested-With", "XMLHttpRequest");
  62. request.Headers.TryAddWithoutValidation("Accept", "application/json");
  63. request.Headers.Referrer = new Uri("https://pub.alimama.com/portal/v2/tool/links/page/home/index.htm");
  64. try
  65. {
  66. using var response = await Client.SendAsync(request, cancellationToken);
  67. string body = await response.Content.ReadAsStringAsync(cancellationToken);
  68. int status = (int)response.StatusCode;
  69. if (status is >= 300 and < 400 || status is 401 or 403 or 429)
  70. return Ok(new { success = false, stopBatch = true, upstreamHttpStatus = status,
  71. message = "登录失效、需要验证或触发限流,请在淘宝联盟后台确认账号状态后再继续" });
  72. if (!response.IsSuccessStatusCode)
  73. return Ok(new { success = false, stopBatch = true, upstreamHttpStatus = status,
  74. message = "上游HTTP异常,暂停批量请求" });
  75. JsonDocument document;
  76. try { document = JsonDocument.Parse(body); }
  77. catch (JsonException)
  78. {
  79. return Ok(new { success = false, stopBatch = true, upstreamHttpStatus = status,
  80. errorType = body.Contains("/_____tmd_____/punish", StringComparison.OrdinalIgnoreCase) ? "browser_challenge" : "non_json",
  81. message = "上游未返回JSON,可能需要重新登录或人工验证" });
  82. }
  83. using (document)
  84. {
  85. JsonElement root = document.RootElement;
  86. JsonElement data = Property(root, "data");
  87. string message = Text(Property(root, "info"), "message");
  88. if (string.IsNullOrEmpty(message)) message = Text(root, "message");
  89. if (string.IsNullOrEmpty(message)) message = Text(root, "msgInfo");
  90. bool upstreamSuccess = Property(root, "success").ValueKind == JsonValueKind.True;
  91. string cpsUrl = Text(data, "shortLinkurl");
  92. if (string.IsNullOrEmpty(cpsUrl)) cpsUrl = Regex.Match(Text(data, "taoToken"),
  93. @"https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]", RegexOptions.IgnoreCase).Value;
  94. string couponUrl = Text(data, "couponShortLinkUrl");
  95. if (!IsHttpUrl(couponUrl)) couponUrl = Text(data, "couponShareUrl");
  96. decimal? couponAmount = decimal.TryParse(Text(data, "couponAmount"), NumberStyles.Number,
  97. CultureInfo.InvariantCulture, out decimal amount) ? amount : null;
  98. bool success = upstreamSuccess && (IsHttpUrl(cpsUrl) || IsHttpUrl(couponUrl));
  99. bool? hasCoupon = couponAmount.HasValue ? couponAmount.Value > 0 : null;
  100. bool hasCouponFields = data.ValueKind == JsonValueKind.Object && data.EnumerateObject()
  101. .Any(property => property.Name.StartsWith("coupon", StringComparison.OrdinalIgnoreCase));
  102. string couponEvidence = couponAmount.HasValue ? "上游明确返回券金额" : "券字段不完整";
  103. // 已用用户提供的有券/无券对照核验:tool_links 的无券成功响应省略全部 coupon* 字段。
  104. // 只在完整商品转链成功时采用此约定,错误响应、部分券字段缺失仍然保持未知。
  105. if (success && !hasCouponFields && IsHttpUrl(cpsUrl) && !string.IsNullOrEmpty(Text(data, "itemId")))
  106. {
  107. hasCoupon = false;
  108. couponAmount = 0;
  109. couponEvidence = "商品转链成功且未返回任何券字段(无券对照已核验)";
  110. }
  111. bool couponSuccess = success && hasCoupon == true && IsHttpUrl(couponUrl);
  112. string selectedUrl = couponSuccess ? couponUrl : IsHttpUrl(cpsUrl) ? cpsUrl : couponUrl;
  113. bool stopBatch = !upstreamSuccess &&
  114. (body.Contains("bixi.alicdn.com", StringComparison.OrdinalIgnoreCase) ||
  115. body.Contains("waf_block", StringComparison.OrdinalIgnoreCase) ||
  116. body.Contains("rgv587_flag", StringComparison.OrdinalIgnoreCase) ||
  117. Property(root, "noLogin").ValueKind == JsonValueKind.True ||
  118. Property(data, "noLogin").ValueKind == JsonValueKind.True ||
  119. Regex.IsMatch(Text(root, "msgCode") + " " + message, "nologin|login|captcha|登录|验证|频繁|限流", RegexOptions.IgnoreCase));
  120. return Ok(new
  121. {
  122. success, upstreamSuccess, couponSuccess, hasCoupon, couponAmount, couponEvidence, stopBatch,
  123. message = upstreamSuccess && !success ? "上游返回成功但没有有效推广链接" : message,
  124. protocol = "tool_links", pid = config.Pid, upstreamHttpStatus = status,
  125. itemId = Text(data, "itemId"), itemName = Text(data, "itemName"),
  126. cpsUrl, couponUrl, shortLinkurl = selectedUrl,
  127. couponEffectiveStartTime = Text(data, "couponEffectiveStartTime"),
  128. couponEffectiveEndTime = Text(data, "couponEffectiveEndTime"),
  129. // 保留响应作为逐条统计依据;不返回请求头、Cookie 或带 _tb_token_ 的请求地址。
  130. upstreamResponse = root.Clone()
  131. });
  132. }
  133. }
  134. catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
  135. {
  136. return StatusCode(504, new { success = false, stopBatch = true, message = "上游请求超时,暂停批量请求" });
  137. }
  138. catch (HttpRequestException)
  139. {
  140. return StatusCode(502, new { success = false, stopBatch = true, message = "上游网络请求失败,暂停批量请求" });
  141. }
  142. }
  143. private async Task<(LocalConfig? Config, string? Error)> ReadConfig(CancellationToken cancellationToken)
  144. {
  145. if (!System.IO.File.Exists(ConfigPath)) return (null, "请填写 .temp/1110/taobao-crawler.local.json");
  146. LocalConfig? config;
  147. try
  148. {
  149. config = JsonSerializer.Deserialize<LocalConfig>(await System.IO.File.ReadAllTextAsync(ConfigPath, cancellationToken),
  150. new JsonSerializerOptions { PropertyNameCaseInsensitive = true, ReadCommentHandling = JsonCommentHandling.Skip });
  151. if (config != null)
  152. {
  153. string localDirectory = Path.GetFullPath(Path.Combine(environment.ContentRootPath, "..", ".temp"));
  154. string cookieFile = Path.Combine(localDirectory, "cookie.txt");
  155. string userAgentFile = Path.Combine(localDirectory, "ua.txt");
  156. if (System.IO.File.Exists(cookieFile)) config.Cookie = await System.IO.File.ReadAllTextAsync(cookieFile, cancellationToken);
  157. if (System.IO.File.Exists(userAgentFile)) config.UserAgent = await System.IO.File.ReadAllTextAsync(userAgentFile, cancellationToken);
  158. }
  159. }
  160. catch (JsonException) { return (null, "本地配置JSON格式不正确"); }
  161. catch (IOException) { return (null, "暂时无法读取本地配置文件"); }
  162. if (config == null || string.IsNullOrWhiteSpace(config.Cookie)) return (config, "请填写淘宝联盟后台 Cookie");
  163. config.Cookie = config.Cookie.Trim();
  164. config.Pid = config.Pid?.Trim() ?? string.Empty;
  165. config.UserAgent = config.UserAgent?.Trim() ?? string.Empty;
  166. if (config.Cookie.Contains('\r') || config.Cookie.Contains('\n')) return (config, "Cookie应为一行,不包含换行");
  167. if (string.IsNullOrEmpty(CookieValue(config.Cookie, "_tb_token_"))) return (config, "Cookie缺少 _tb_token_,请从淘宝联盟后台请求中复制完整Cookie");
  168. if (!Regex.IsMatch(config.Pid, @"^mm_\d+_\d+_\d+$")) return (config, "请填写此账号的推广位PID(mm_数字_数字_数字)");
  169. if (string.IsNullOrWhiteSpace(config.UserAgent)) return (config, "请填写复制Cookie时浏览器的User-Agent");
  170. if (config.UserAgent.Contains('\r') || config.UserAgent.Contains('\n')) return (config, "User-Agent不能包含换行");
  171. return (config, null);
  172. }
  173. private static string CookieValue(string cookies, string name) => cookies.Split(';')
  174. .Select(part => part.Trim()).FirstOrDefault(part => part.StartsWith(name + "=", StringComparison.Ordinal))?[(name.Length + 1)..] ?? string.Empty;
  175. private static JsonElement Property(JsonElement value, string name) => value.ValueKind == JsonValueKind.Object &&
  176. value.TryGetProperty(name, out var found) ? found : default;
  177. private static string Text(JsonElement value, string name) => Property(value, name) is var found &&
  178. found.ValueKind is not (JsonValueKind.Undefined or JsonValueKind.Null) ? found.ToString() : string.Empty;
  179. private static bool IsHttpUrl(string value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme is "http" or "https";
  180. public sealed class ParseInput { public string S { get; set; } = string.Empty; }
  181. private sealed class LocalConfig
  182. {
  183. public LocalConfig() { }
  184. public string Cookie { get; set; } = string.Empty;
  185. public string Pid { get; set; } = string.Empty;
  186. public string UserAgent { get; set; } = string.Empty;
  187. }
  188. }
  189. #endif