| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 |
- #if DEBUG
- // 1110 临时口令样本统计:本文件只参与 Debug 编译,Release 不包含此接口。
- // PID 填在 .temp/1110/taobao-crawler.local.json;Cookie 优先读取 .temp/cookie.txt,UA 优先读取 .temp/ua.txt。
- // 这些本地文件已被 .gitignore 排除,更新内容后无需重启服务。
- // 使用个人淘宝联盟账号时,PID 必须属于该 Cookie 对应账号;不要沿用生产 aid=133 的 PID。
- // 协议来自 molilian.core/Plus/Alimama/parse_endpoint/tool_links.cs(floorId=61446)。
- // 直接提交完整原文,避免生产流程的纯口令/其他推广链接预筛选影响此次样本统计。
- // 此入口不选号、不写账号表、不调用生产日志计数或账号停用逻辑。
- using System.Globalization;
- using System.Net;
- using System.Text.Json;
- using System.Text.RegularExpressions;
- using Microsoft.AspNetCore.Mvc;
- namespace molilian.api.Controllers;
- [ApiController]
- [Route("debug/taobao-coupon")]
- public sealed class TaobaoCouponDebugController(IWebHostEnvironment environment) : ControllerBase
- {
- private static readonly HttpClient Client = new(new HttpClientHandler
- {
- AllowAutoRedirect = false,
- UseCookies = false,
- UseProxy = false
- }) { Timeout = TimeSpan.FromSeconds(45) };
- private string ConfigPath => Path.GetFullPath(Path.Combine(
- environment.ContentRootPath, "..", ".temp", "1110", "taobao-crawler.local.json"));
- private bool IsLocalRequest() => HttpContext.Connection.RemoteIpAddress is { } ip &&
- IPAddress.IsLoopback(ip.IsIPv4MappedToIPv6 ? ip.MapToIPv4() : ip);
- // 仅读取配置是否就绪,不返回 Cookie 或 _tb_token_;改本地 JSON 后无需重新编译。
- [HttpGet("status")]
- public async Task<IActionResult> Status(CancellationToken cancellationToken)
- {
- if (!IsLocalRequest()) return NotFound();
- var (config, error) = await ReadConfig(cancellationToken);
- return Ok(new { configured = error == null, message = error, pid = config?.Pid,
- protocol = "tool_links", configFile = ".temp/1110/taobao-crawler.local.json" });
- }
- [HttpPost("parse")]
- public async Task<IActionResult> Parse([FromBody] ParseInput input, CancellationToken cancellationToken)
- {
- if (!IsLocalRequest()) return NotFound();
- if (string.IsNullOrWhiteSpace(input.S)) return BadRequest(new { message = "口令原文不能为空" });
- var (config, error) = await ReadConfig(cancellationToken);
- if (config == null || error != null)
- return StatusCode(503, new { success = false, stopBatch = true, message = error });
- string timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(CultureInfo.InvariantCulture);
- string cna = CookieValue(config.Cookie, "cna");
- string variableMap = JsonSerializer.Serialize(new
- {
- url = input.S,
- union_lens = $"b_pvid:a219t._portal_v2_home_plus_index_htm_{timestamp}_{Random.Shared.Next(100000, 999999)}_{cna[..Math.Min(5, cna.Length)]}_mmWuH",
- lensScene = "PUB",
- spmB = "_portal_v2_tool_links_page_home_index_htm"
- });
- string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/xt.entry.json?" +
- $"t={timestamp}&_tb_token_={Uri.EscapeDataString(CookieValue(config.Cookie, "_tb_token_"))}" +
- $"&floorId=61446&refpid={Uri.EscapeDataString(config.Pid)}&variableMap={Uri.EscapeDataString(variableMap)}";
- using var request = new HttpRequestMessage(HttpMethod.Get, url);
- request.Headers.TryAddWithoutValidation("Cookie", config.Cookie);
- request.Headers.TryAddWithoutValidation("User-Agent", config.UserAgent);
- request.Headers.TryAddWithoutValidation("X-Requested-With", "XMLHttpRequest");
- request.Headers.TryAddWithoutValidation("Accept", "application/json");
- request.Headers.Referrer = new Uri("https://pub.alimama.com/portal/v2/tool/links/page/home/index.htm");
- try
- {
- using var response = await Client.SendAsync(request, cancellationToken);
- string body = await response.Content.ReadAsStringAsync(cancellationToken);
- int status = (int)response.StatusCode;
- if (status is >= 300 and < 400 || status is 401 or 403 or 429)
- return Ok(new { success = false, stopBatch = true, upstreamHttpStatus = status,
- message = "登录失效、需要验证或触发限流,请在淘宝联盟后台确认账号状态后再继续" });
- if (!response.IsSuccessStatusCode)
- return Ok(new { success = false, stopBatch = true, upstreamHttpStatus = status,
- message = "上游HTTP异常,暂停批量请求" });
- JsonDocument document;
- try { document = JsonDocument.Parse(body); }
- catch (JsonException)
- {
- return Ok(new { success = false, stopBatch = true, upstreamHttpStatus = status,
- errorType = body.Contains("/_____tmd_____/punish", StringComparison.OrdinalIgnoreCase) ? "browser_challenge" : "non_json",
- message = "上游未返回JSON,可能需要重新登录或人工验证" });
- }
- using (document)
- {
- JsonElement root = document.RootElement;
- JsonElement data = Property(root, "data");
- string message = Text(Property(root, "info"), "message");
- if (string.IsNullOrEmpty(message)) message = Text(root, "message");
- if (string.IsNullOrEmpty(message)) message = Text(root, "msgInfo");
- bool upstreamSuccess = Property(root, "success").ValueKind == JsonValueKind.True;
- string cpsUrl = Text(data, "shortLinkurl");
- if (string.IsNullOrEmpty(cpsUrl)) cpsUrl = Regex.Match(Text(data, "taoToken"),
- @"https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]", RegexOptions.IgnoreCase).Value;
- string couponUrl = Text(data, "couponShortLinkUrl");
- if (!IsHttpUrl(couponUrl)) couponUrl = Text(data, "couponShareUrl");
- decimal? couponAmount = decimal.TryParse(Text(data, "couponAmount"), NumberStyles.Number,
- CultureInfo.InvariantCulture, out decimal amount) ? amount : null;
- bool success = upstreamSuccess && (IsHttpUrl(cpsUrl) || IsHttpUrl(couponUrl));
- bool? hasCoupon = couponAmount.HasValue ? couponAmount.Value > 0 : null;
- bool hasCouponFields = data.ValueKind == JsonValueKind.Object && data.EnumerateObject()
- .Any(property => property.Name.StartsWith("coupon", StringComparison.OrdinalIgnoreCase));
- string couponEvidence = couponAmount.HasValue ? "上游明确返回券金额" : "券字段不完整";
- // 已用用户提供的有券/无券对照核验:tool_links 的无券成功响应省略全部 coupon* 字段。
- // 只在完整商品转链成功时采用此约定,错误响应、部分券字段缺失仍然保持未知。
- if (success && !hasCouponFields && IsHttpUrl(cpsUrl) && !string.IsNullOrEmpty(Text(data, "itemId")))
- {
- hasCoupon = false;
- couponAmount = 0;
- couponEvidence = "商品转链成功且未返回任何券字段(无券对照已核验)";
- }
- bool couponSuccess = success && hasCoupon == true && IsHttpUrl(couponUrl);
- string selectedUrl = couponSuccess ? couponUrl : IsHttpUrl(cpsUrl) ? cpsUrl : couponUrl;
- bool stopBatch = !upstreamSuccess &&
- (body.Contains("bixi.alicdn.com", StringComparison.OrdinalIgnoreCase) ||
- body.Contains("waf_block", StringComparison.OrdinalIgnoreCase) ||
- body.Contains("rgv587_flag", StringComparison.OrdinalIgnoreCase) ||
- Property(root, "noLogin").ValueKind == JsonValueKind.True ||
- Property(data, "noLogin").ValueKind == JsonValueKind.True ||
- Regex.IsMatch(Text(root, "msgCode") + " " + message, "nologin|login|captcha|登录|验证|频繁|限流", RegexOptions.IgnoreCase));
- return Ok(new
- {
- success, upstreamSuccess, couponSuccess, hasCoupon, couponAmount, couponEvidence, stopBatch,
- message = upstreamSuccess && !success ? "上游返回成功但没有有效推广链接" : message,
- protocol = "tool_links", pid = config.Pid, upstreamHttpStatus = status,
- itemId = Text(data, "itemId"), itemName = Text(data, "itemName"),
- cpsUrl, couponUrl, shortLinkurl = selectedUrl,
- couponEffectiveStartTime = Text(data, "couponEffectiveStartTime"),
- couponEffectiveEndTime = Text(data, "couponEffectiveEndTime"),
- // 保留响应作为逐条统计依据;不返回请求头、Cookie 或带 _tb_token_ 的请求地址。
- upstreamResponse = root.Clone()
- });
- }
- }
- catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested)
- {
- return StatusCode(504, new { success = false, stopBatch = true, message = "上游请求超时,暂停批量请求" });
- }
- catch (HttpRequestException)
- {
- return StatusCode(502, new { success = false, stopBatch = true, message = "上游网络请求失败,暂停批量请求" });
- }
- }
- private async Task<(LocalConfig? Config, string? Error)> ReadConfig(CancellationToken cancellationToken)
- {
- if (!System.IO.File.Exists(ConfigPath)) return (null, "请填写 .temp/1110/taobao-crawler.local.json");
- LocalConfig? config;
- try
- {
- config = JsonSerializer.Deserialize<LocalConfig>(await System.IO.File.ReadAllTextAsync(ConfigPath, cancellationToken),
- new JsonSerializerOptions { PropertyNameCaseInsensitive = true, ReadCommentHandling = JsonCommentHandling.Skip });
- if (config != null)
- {
- string localDirectory = Path.GetFullPath(Path.Combine(environment.ContentRootPath, "..", ".temp"));
- string cookieFile = Path.Combine(localDirectory, "cookie.txt");
- string userAgentFile = Path.Combine(localDirectory, "ua.txt");
- if (System.IO.File.Exists(cookieFile)) config.Cookie = await System.IO.File.ReadAllTextAsync(cookieFile, cancellationToken);
- if (System.IO.File.Exists(userAgentFile)) config.UserAgent = await System.IO.File.ReadAllTextAsync(userAgentFile, cancellationToken);
- }
- }
- catch (JsonException) { return (null, "本地配置JSON格式不正确"); }
- catch (IOException) { return (null, "暂时无法读取本地配置文件"); }
- if (config == null || string.IsNullOrWhiteSpace(config.Cookie)) return (config, "请填写淘宝联盟后台 Cookie");
- config.Cookie = config.Cookie.Trim();
- config.Pid = config.Pid?.Trim() ?? string.Empty;
- config.UserAgent = config.UserAgent?.Trim() ?? string.Empty;
- if (config.Cookie.Contains('\r') || config.Cookie.Contains('\n')) return (config, "Cookie应为一行,不包含换行");
- if (string.IsNullOrEmpty(CookieValue(config.Cookie, "_tb_token_"))) return (config, "Cookie缺少 _tb_token_,请从淘宝联盟后台请求中复制完整Cookie");
- if (!Regex.IsMatch(config.Pid, @"^mm_\d+_\d+_\d+$")) return (config, "请填写此账号的推广位PID(mm_数字_数字_数字)");
- if (string.IsNullOrWhiteSpace(config.UserAgent)) return (config, "请填写复制Cookie时浏览器的User-Agent");
- if (config.UserAgent.Contains('\r') || config.UserAgent.Contains('\n')) return (config, "User-Agent不能包含换行");
- return (config, null);
- }
- private static string CookieValue(string cookies, string name) => cookies.Split(';')
- .Select(part => part.Trim()).FirstOrDefault(part => part.StartsWith(name + "=", StringComparison.Ordinal))?[(name.Length + 1)..] ?? string.Empty;
- private static JsonElement Property(JsonElement value, string name) => value.ValueKind == JsonValueKind.Object &&
- value.TryGetProperty(name, out var found) ? found : default;
- private static string Text(JsonElement value, string name) => Property(value, name) is var found &&
- found.ValueKind is not (JsonValueKind.Undefined or JsonValueKind.Null) ? found.ToString() : string.Empty;
- private static bool IsHttpUrl(string value) => Uri.TryCreate(value, UriKind.Absolute, out var uri) && uri.Scheme is "http" or "https";
- public sealed class ParseInput { public string S { get; set; } = string.Empty; }
- private sealed class LocalConfig
- {
- public LocalConfig() { }
- public string Cookie { get; set; } = string.Empty;
- public string Pid { get; set; } = string.Empty;
- public string UserAgent { get; set; } = string.Empty;
- }
- }
- #endif
|