parse.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  1. using System.Text;
  2. using dodohold.core;
  3. using System.Text.RegularExpressions;
  4. using System.Net;
  5. using System.Linq;
  6. using System.Security.Cryptography;
  7. using TencentCloud.Ecm.V20190719.Models;
  8. using System.Diagnostics;
  9. using static dodohold.core.ZTOExpress.CreateOrderArgs;
  10. using System.Text.Json;
  11. using TencentCloud.Tcm.V20210413.Models;
  12. using TencentCloud.Tione.V20211111.Models;
  13. using System.Runtime.InteropServices.Marshalling;
  14. namespace molilian.core
  15. {
  16. public partial class AlimamaPlus
  17. {
  18. private string _accountName;
  19. private int _accountId;
  20. private string _company;
  21. private string _tb_token;
  22. private string _floorId;
  23. private string _refpid;
  24. private string _user_agent;
  25. private string _cookies;
  26. public string _proxyName;
  27. public WebProxy? _proxy = null;
  28. private string _api;
  29. private int _api_id = 0;
  30. public TkConfigDTO _config;
  31. private static string _end_point;
  32. private TkPoolDTO _account;
  33. static Random _random = new Random();
  34. public static string _url_pattern = @"https?://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]";
  35. static AlimamaPlus()
  36. {
  37. _end_point = Environment.GetEnvironmentVariable("EndPoint");
  38. }
  39. public AlimamaPlus(TkPoolDTO account)
  40. {
  41. // string accountName, string tb_token, string floorId, string refpid,
  42. // string cookies, string user_agent, string nodeName
  43. _config = TkConfigCore.Get();
  44. _account = account;
  45. _accountId = account.id;
  46. _accountName = account.name;
  47. _company = account.company;
  48. _tb_token = account.tb_token;
  49. _floorId = account.floorId;
  50. _refpid = account.refpid;
  51. _cookies = account.cookies;
  52. _user_agent = account.user_agent?.Trim();
  53. if (!string.IsNullOrEmpty(account.nodeName))
  54. {
  55. _proxyName = ProxyNodesCore.GetSelectOne(account.nodeName);
  56. _proxy = ProxyNodesCore.GetOne(_proxyName);
  57. }
  58. _api = account.api;
  59. _api_id = account.api_id;
  60. }
  61. public bool ShouldIgnoreOtherAff(string content)
  62. {
  63. TkDataDTO result = new();
  64. //(_, _, var link_type, _) = InternalTextProcessing(content, ref result);
  65. InternalTextProcessing(content, ref result);
  66. return result.link_type == LinkTypeEnum.other_aff;
  67. }
  68. public async Task<TkDataDTO> UnionParseAsync(UnionParseRequest request, string content, TkDataDTO result, bool isTaobaoUrl, CancellationToken cancellationToken = default,
  69. Dictionary<string, long> swData = null)
  70. {
  71. result.itemName = "点击打开淘宝APP";
  72. // 先保留短链,选定节点后再决定是否展开。
  73. result = await InternalTextProcessingAsync(content, result, cancellationToken, swData, preserveShortLinks: true);
  74. bool hasShortLink = result.link_type == LinkTypeEnum.baseDomain;
  75. bool shortLinkExpanded = false;
  76. bool ShouldStopAfterTextProcessing()
  77. {
  78. if (result.link_type == LinkTypeEnum.other_aff)
  79. {
  80. result.channel = TkChannelEnum.tb;
  81. result.channel_type = ChannelTypeEnum.tb;
  82. result.success = false;
  83. result.message = "放弃转链";
  84. result.reason = "其他推广链接";
  85. result.subCode = TkSubCodeEnum.OtherPromo;
  86. result.accountName = string.Empty;
  87. result.content = content;
  88. return true;
  89. }
  90. if (!result.success)
  91. {
  92. switch (result.link_type)
  93. {
  94. case LinkTypeEnum.profile:
  95. case LinkTypeEnum.live:
  96. case LinkTypeEnum.video:
  97. case LinkTypeEnum.note:
  98. case LinkTypeEnum.goods:
  99. case LinkTypeEnum.baseDomain:
  100. result.reason = string.Empty;
  101. break;
  102. default:
  103. result.reason = "非标准链接";
  104. result.subCode = TkSubCodeEnum.NonStdLink;
  105. return true;
  106. }
  107. }
  108. return false;
  109. }
  110. if (ShouldStopAfterTextProcessing()) return result;
  111. //============================== 放弃转链-地区过滤 ==============================
  112. bool is_ignore2 = FlowControlIgnoreRequest(request, out string reason);
  113. string message = "放弃转链";
  114. if (is_ignore2)
  115. {
  116. if ("7".Equals(_account.parseEndpoint))
  117. {
  118. message = "转链失败";
  119. result.reason = "fail2";
  120. }
  121. result.success = false;
  122. result.message = message;
  123. result.reason = reason;
  124. result.subCode = TkSubCodeEnum.TrafficCtrl;
  125. return result;
  126. }
  127. switch (request.CommerceType)
  128. {
  129. case 1:
  130. case 2:
  131. result.success = false;
  132. result.message = "放弃转链";
  133. result.reason = $"厂商放弃{request.CommerceType}";
  134. result.subCode = TkSubCodeEnum.PartnersDrop;
  135. return result;
  136. }
  137. //2025-02-06 增加重试机制
  138. int try_count = 0;
  139. while (try_count == 0 || try_count <= _config.tk_parse_retry_count)
  140. {
  141. if (try_count >= 3) break;
  142. (int ep_id, string tkEndpoint) = await TkEndpointManager.GetConvertApiAsync(_accountId, isTaobaoUrl, _account.parseEndpoint);
  143. result.tkEndpoint = ep_id;
  144. // 其他节点只展开一次;tbk_dg 始终使用原始短链。
  145. if (hasShortLink && !shortLinkExpanded && tkEndpoint != "tbk_dg" &&
  146. !string.IsNullOrEmpty(tkEndpoint) && tkEndpoint != "ALL")
  147. {
  148. result = await InternalTextProcessingAsync(content, result, cancellationToken, swData);
  149. shortLinkExpanded = true;
  150. if (ShouldStopAfterTextProcessing()) return result;
  151. }
  152. switch (tkEndpoint)
  153. {
  154. case "moose_share":
  155. result = await endpoint_moose_share(result.content, result, cancellationToken);
  156. break;
  157. case "promo_goods":
  158. result = await endpoint_promo_goods(result.content, result, cancellationToken);
  159. break;
  160. case "tool_links":
  161. result = await endpoint_tool_links(result.content, result, cancellationToken);
  162. break;
  163. case "aliyun":
  164. result = await endpoint_aliyun(result.content, result, cancellationToken);
  165. break;
  166. case "tbk_dg":
  167. result = await endpoint_tbk_dg(hasShortLink ? content : result.content, result, cancellationToken);
  168. break;
  169. case "aiopen":
  170. result = await endpoint_aiopen(result.content, result, cancellationToken);
  171. break;
  172. case "veapi":
  173. case "ddx":
  174. case "other_api":
  175. if (!string.IsNullOrEmpty(_api) && _api_id > 0)
  176. {
  177. var account = OtherApiPoolCore.Get(_api_id);
  178. if (account != null)
  179. {
  180. var core = new OtherApiPlus(account.name, account.key, account.sessionKey, tkEndpoint, account.api_url);
  181. string refpid = string.IsNullOrEmpty(account.refpid) ? _refpid : account.refpid;
  182. result = await core.UnionParseAsync(result.content, refpid, result, cancellationToken);
  183. return result;
  184. }
  185. }
  186. else
  187. {
  188. result.link_type = LinkTypeEnum.unknown;
  189. result.subCode = TkSubCodeEnum.Other;
  190. result.success = false;
  191. result.message = "放弃转链";
  192. result.reason = "接口配置失败";
  193. return result;
  194. }
  195. break;
  196. //case "ALL":
  197. // //没有可以用的接口了
  198. // result.link_type = LinkTypeEnum.unknown;
  199. // result.subCode = TkSubCodeEnum.ParseDeny;
  200. // result.success = false;
  201. // result.message = "放弃转链";
  202. // result.reason = "接口风控ALL";
  203. // return result;
  204. default:
  205. result.link_type = LinkTypeEnum.unknown;
  206. result.subCode = TkSubCodeEnum.ParseDeny;
  207. result.success = false;
  208. result.message = "放弃转链";
  209. result.reason = $"接口风控{tkEndpoint}";
  210. break;
  211. }
  212. if (!"该链接不支持转化,请更换链接尝试".Equals(result.message)) break;
  213. try_count++;
  214. }
  215. result.retry_count = try_count;
  216. result.commercial = result.success;
  217. if (result.success && "brwsimilar".Equals(request.RiskStrategy))
  218. {
  219. // 需要搜同款才进入这个逻辑
  220. result.PromotionImg = await InternalCallPromotionQuery(result.pic, request.Oaid, request.Ip, _account.useCouponLinkFirst);
  221. // "pic": "https://img.alicdn.com/i4/6000000004750/O1CN01w4wgqa1kxYS1BadZp_!!6000000004750-0-sm.jpg",
  222. //result.pic
  223. //result.PromotionImg[*].pic
  224. int i = 0;
  225. foreach (var item in result.PromotionImg)
  226. {
  227. i++;
  228. item.clickTracks = TracksCore.BuildBrwSimilarPath(TrackType.Click, result, item, i);
  229. item.exposeTracks = TracksCore.BuildBrwSimilarPath(TrackType.Expose, result, item, i);
  230. item.pic = NormalizeAlicdnImageUrl(item.pic);
  231. }
  232. DateTime now = DateTime.Now;
  233. if (now < new DateTime(2026, 8, 22))
  234. {
  235. _ = new LoggerLibrary("AlimamaPlus", "PromotionImageCount")
  236. .Info(now.ToString("yyyy-MM-dd HH:mm:ss.fff"), i.ToString())
  237. .SaveAsync();
  238. }
  239. }
  240. result.pic = NormalizeAlicdnImageUrl(result.pic);
  241. if (!result.success)
  242. {
  243. result.itemName = "点击打开淘宝APP";
  244. }
  245. if (string.IsNullOrEmpty(result.itemName) || result.link_type == LinkTypeEnum.profile)
  246. {
  247. result.itemName = "点击打开淘宝APP";
  248. }
  249. return result;
  250. }
  251. private async Task<List<PromotionQueryItemDTO>> InternalCallPromotionQuery(string pic, string oaid, string ip, bool useCouponLinkFirst)
  252. {
  253. if (string.IsNullOrWhiteSpace(pic))
  254. {
  255. return [];
  256. }
  257. static bool TryParseItems(JsonElement element, out List<PromotionQueryItemDTO> items)
  258. {
  259. items = [];
  260. if (element.ValueKind == JsonValueKind.Array)
  261. {
  262. items = JsonSerializer.Deserialize<List<PromotionQueryItemDTO>>(element.GetRawText()) ?? [];
  263. return true;
  264. }
  265. if (element.ValueKind != JsonValueKind.Object)
  266. {
  267. return false;
  268. }
  269. if (element.TryGetProperty("promotionImg", out var promotionImg) && promotionImg.ValueKind == JsonValueKind.Array)
  270. {
  271. items = JsonSerializer.Deserialize<List<PromotionQueryItemDTO>>(promotionImg.GetRawText()) ?? [];
  272. return true;
  273. }
  274. if (element.TryGetProperty("PromotionImg", out promotionImg) && promotionImg.ValueKind == JsonValueKind.Array)
  275. {
  276. items = JsonSerializer.Deserialize<List<PromotionQueryItemDTO>>(promotionImg.GetRawText()) ?? [];
  277. return true;
  278. }
  279. return false;
  280. }
  281. static List<PromotionQueryItemDTO> RemoveFirstItem(List<PromotionQueryItemDTO> items)
  282. {
  283. return items.Count > 0 ? items.Skip(1).ToList() : [];
  284. }
  285. string requestUrl = "https://similar.molilian.com/api/unsafePromotionQuery";
  286. string targetPic = NormalizeAlicdnImageUrl(pic.StartsWith("//") ? $"https:{pic}" : pic, 1200);
  287. object postData = new
  288. {
  289. url = targetPic,
  290. oaid,
  291. ip,
  292. recommand = false,
  293. useCouponLinkFirst
  294. };
  295. string post = postData.Convert2Json();
  296. try
  297. {
  298. var client = new WebClientUtility().SetContentType("application/json")
  299. .Post(post);
  300. var response = await client.RequestAsync(requestUrl, "POST");
  301. var body = response.Body();
  302. if (string.IsNullOrWhiteSpace(body))
  303. {
  304. return [];
  305. }
  306. var root = body.Convert2JsonElement();
  307. if (TryParseItems(root, out var result))
  308. {
  309. return RemoveFirstItem(result);
  310. }
  311. if (root.ValueKind == JsonValueKind.Object)
  312. {
  313. if (root.TryGetProperty("data", out var data) && TryParseItems(data, out result))
  314. {
  315. return RemoveFirstItem(result);
  316. }
  317. if (root.TryGetProperty("result", out var resultNode) && TryParseItems(resultNode, out result))
  318. {
  319. return RemoveFirstItem(result);
  320. }
  321. }
  322. _ = new LoggerLibrary("AlimamaPlus", "InternalCallPromotionQuery")
  323. .Info(post, body)
  324. .SaveAsync();
  325. }
  326. catch (Exception ex)
  327. {
  328. _ = new LoggerLibrary("AlimamaPlus", "InternalCallPromotionQuery")
  329. .Info(requestUrl, post)
  330. .Info(ex.Message, ex.StackTrace)
  331. .SaveAsync();
  332. }
  333. return [];
  334. }
  335. private static string NormalizeAlicdnImageUrl(string pic, int size = 400)
  336. {
  337. string formatSuffix = size switch
  338. {
  339. 1200 => "_1200x1200q90.jpg_.webp",
  340. _ => "_400x400q90.jpg_.webp"
  341. };
  342. if (string.IsNullOrWhiteSpace(pic))
  343. {
  344. return pic;
  345. }
  346. if (!pic.Contains("img.alicdn.com", StringComparison.OrdinalIgnoreCase))
  347. {
  348. return pic;
  349. }
  350. if (Regex.IsMatch(pic, @"_\d+x\d+q\d+\.jpg_\.webp(?:[?#].*)?$", RegexOptions.IgnoreCase))
  351. {
  352. return pic;
  353. }
  354. return $"{pic}{formatSuffix}";
  355. }
  356. public static bool ContainsTaobaoId(string content, string rawContent)
  357. {
  358. var match = Regex.Match(content, @"(?<=[?&]id=)\d+(?=&|$)");
  359. if (!match.Success) return false;
  360. string id = match.Value;
  361. return Regex.IsMatch(rawContent, $@"(^|\D){id}($|\D)");
  362. }
  363. public static string ReplaceUrls(string content, string shortLink)
  364. {
  365. if (string.IsNullOrEmpty(content) || string.IsNullOrEmpty(shortLink)) return content;
  366. string result = content;
  367. Regex regex = new(_url_pattern);
  368. MatchCollection matches = regex.Matches(content);
  369. foreach (Match m in matches.Cast<Match>())
  370. {
  371. string url = m.Value;
  372. if (url.Contains("https://s.tb.cn/") ||
  373. url.Contains("http://s.tb.cn/") ||
  374. url.Contains("http://m.tb.cn/") ||
  375. url.Contains("http://m.tb.cn/") ||
  376. url.Contains("http://e.tb.cn/") ||
  377. url.Contains("https://e.tb.cn/"))
  378. {
  379. result = result.Replace(url, shortLink);
  380. }
  381. }
  382. return result;
  383. }
  384. public static string RemoveUrls(string content)
  385. {
  386. if (string.IsNullOrEmpty(content)) return content;
  387. string result = content;
  388. Regex regex = new(_url_pattern);
  389. MatchCollection matches = regex.Matches(content);
  390. foreach (Match m in matches.Cast<Match>())
  391. {
  392. string url = m.Value;
  393. result = result.Replace(url, string.Empty);
  394. }
  395. return result;
  396. }
  397. public static string GetLink(string content)
  398. {
  399. if (string.IsNullOrEmpty(content)) return content;
  400. //string pattern = @"https?:\/\/?([\da-z\.-]+)\.([a-z]{2,6})(:\d{1,5})?([\/\w\.-]*)*\/?(#[\S]+)?(\?[\S]+)?";
  401. Regex regex = new(_url_pattern);
  402. MatchCollection matches = regex.Matches(content);
  403. string result = string.Empty;
  404. if (matches.Count > 0)
  405. {
  406. result = Regex.Replace(matches[^1].Value, @"\++$", "");
  407. }
  408. result = result.Replace("&nbsp;", "");
  409. if (result.StartsWith("http://e.tb.cn/")) result = result.Replace("http://", "https://");
  410. return result;
  411. }
  412. public static string GetTaobaoLink(string content)
  413. {
  414. if (string.IsNullOrEmpty(content)) return content;
  415. string pattern = @"(https?://(?:[\w-]+\.)*(?:tb\.cn|taobao\.com|juhuasuan\.com|tmall\.com|tmall\.hk)(?:/[a-zA-Z0-9\-\._~:/?#[\]@!$&'()*+,;=%]*)?)";
  416. Regex regex = new(pattern, RegexOptions.IgnoreCase);
  417. MatchCollection matches = regex.Matches(content);
  418. if (matches.Count > 0)
  419. {
  420. string result = Regex.Replace(matches[^1].Value, @"\++$", "");
  421. return result;
  422. }
  423. return string.Empty;
  424. }
  425. public static string GetDeeplink(string url)
  426. {
  427. if (string.IsNullOrEmpty(url)) return "tbopen://m.taobao.com/tbopen/index.html";
  428. string result = $"tbopen://m.taobao.com/tbopen/index.html?action=ali.open.nav&module=h5&h5Url={url.UrlEncode()}";
  429. //string result = $"tbopen://m.taobao.com/tbopen/index.html?action=ali.open.nav&module=h5&bootImage=0&afcPromotionOpen=false&bc_fl_src=h5_huanduan&source=slk_dp&h5Url={url.UrlEncode()}";
  430. return result;
  431. }
  432. public static string GetTitle(string content)
  433. {
  434. if (string.IsNullOrEmpty(content)) return string.Empty;
  435. string url = GetLink(content);
  436. if (!string.IsNullOrEmpty(url)) content = content.Replace(url, string.Empty);
  437. content = content.Replace("点击链接直接打开 或者 淘宝搜索直接打开", string.Empty).Trim();
  438. string[] words = Regex.Split(content, @"\s+");
  439. string word = words[^1];
  440. word = word.TrimStart('「').TrimEnd('」');
  441. return word;
  442. }
  443. public static bool IgnoreRegionIncluded(string _ignoreRegions, string? ipInfo, out string regionInfo)
  444. {
  445. regionInfo = string.Empty;
  446. if (string.IsNullOrEmpty(_ignoreRegions) || string.IsNullOrEmpty(ipInfo)) return false;
  447. string[] parts = ipInfo.Split('|');
  448. string countryInfo = null;
  449. if (parts.Length >= 4)
  450. {
  451. countryInfo = parts[0];
  452. regionInfo = parts[3];
  453. }
  454. if (string.IsNullOrEmpty(regionInfo)) return false;
  455. if (string.IsNullOrEmpty(countryInfo)) return false;
  456. string[] ignoreRegions = _ignoreRegions.Split('|');
  457. if (ignoreRegions.Contains(regionInfo)) return true;
  458. if (ignoreRegions.Contains(countryInfo))
  459. {
  460. regionInfo = countryInfo;
  461. return true;
  462. }
  463. foreach (var region in ignoreRegions)
  464. {
  465. if ("海外".Equals(region) && !"中国".Equals(countryInfo) && !"0".Equals(countryInfo))
  466. {
  467. regionInfo = "海外";
  468. return true;
  469. }
  470. }
  471. return false;
  472. }
  473. public static async Task<bool> OtherPlatformAsync(string content)
  474. {
  475. try
  476. {
  477. //腾讯会议
  478. string wemeetId = await ToolParsePlus.GetWemeetIdAsync(content);
  479. if (!string.IsNullOrEmpty(wemeetId)) return true;
  480. //百度网盘
  481. string surl = string.Empty, pwd = string.Empty;
  482. _ = ToolParsePlus.GetPanLink(content, ref surl, ref pwd);
  483. if (!string.IsNullOrEmpty(surl)) return true;
  484. //JD
  485. string url = JdUnionPlus.GetLink(content);
  486. var urlType = JdUnionPlus.GetLinkType(url, out _, out _);
  487. if (urlType != LinkTypeEnum.unknown) return true;
  488. //DY
  489. url = DyUnionPlus.GetLink(content);
  490. urlType = DyUnionPlus.GetLinkType(content, url);
  491. if (urlType != LinkTypeEnum.unknown) return true;
  492. }
  493. catch { }
  494. return false;
  495. }
  496. public static bool MatchRegexes(string text, List<string> extended)
  497. {
  498. text = RemoveUrls(text);
  499. string special_symbols = $"\\$\\(\\)\\/\\#\\&\\<\\>฿¢¥¥$🗝₰₵₲¤₪₴€₤£₳《¢💰🔑🎵✔💲🔐📲";
  500. string[] base_patterns =
  501. [
  502. $@"(.*?\d{{2}}\s[a-zA-Z]{{2}}\d{{4}}\s.*?[{special_symbols}]+[a-zA-Z0-9\s]+[{special_symbols}]).*",
  503. $@"[{special_symbols}]+\s*([a-zA-Z]{{1,2}}\d{{2,4}}\s[a-zA-Z0-9]{{11}}|[a-zA-Z0-9]{{11}}[a-zA-Z]{{1,2}}\d{{2,4}}\s|[a-zA-Z0-9]{{11}})\s*[{special_symbols}]+",
  504. @"🍑♭ɑ◑下单|Tao宝"
  505. ];
  506. List<string> mergedArray = extended.Union(base_patterns).ToList();
  507. /*
  508. (.*?\\d{2}\\s[a-zA-Z]{2}\\d{4}\\s.*?[\\$\\(\\)\\/\\#\\&\\<\\>฿¢¥¥$🗝₰₵₲¤₪₴€₤£₳《¢💰🔑🎵✔💲🔐📲]+[a-zA-Z0-9\\s]+[\\$\\(\\)\\/\\#\\&\\<\\>฿¢¥¥$🗝₰₵₲¤₪₴€₤£₳《¢💰🔑🎵✔💲🔐📲])).*\n[\\$\\(\\)\\/\\#\\&\\<\\>฿¢¥¥$🗝₰₵₲¤₪₴€₤£₳《¢💰🔑🎵✔💲🔐📲]+\\s*([a-zA-Z]{1,2}\\d{2,4}\\s[a-zA-Z0-9]{11}|[a-zA-Z0-9]{11}[a-zA-Z]{1,2}\\d{2,4}\\s|[a-zA-Z0-9]{11})\\s*[\\$\\(\\)\\/\\#\\&\\<\\>฿¢¥¥$🗝₰₵₲¤₪₴€₤£₳《¢💰🔑🎵✔💲🔐📲]+\n🍑♭ɑ◑下单|Tao宝
  509. 【3瓶】恩威万蓝莓叶黄素酯软糖儿童成人上班族如酸涩肿胀可服用,<z5TYWAblvTw >:// HU7709,打開/
  510. 置顶小助手,方便下次查询\r\n1★【劵】无\r\n2★【返.佣】 0.29圆 \r\n3★【付款.价】24.9 圆\r\n \r\n 1 ¢HZv5WAboi0D¢(/:/ HU8866\r\
  511. n长按覆制本内容,打开TaoBao/\r\n-\r\n返佣是指商家的推广佣.金\r\n通过我回复的口令下単收货后,我
  512. 会微信红.苞返给你!!\r\n\r\n有疑问可回复“人工”咨询客服*/
  513. //🍑🔗上 水和肌精华水& CZ0 VWdCWC2gj97&,
  514. //6฿04ZDWzrwxjN)/ CA97
  515. //1😘 腹制这条(CZ00 iHvtWzrXa7O(:/
  516. //¥EC8DG4Zj0dhd8DOw¥MF6563 oIo0WzOF1Cp##X-PyVpHiPlyj1OP##
  517. //6.6₵vU2jWzIW3Qx₲/ CZ5224
  518. //$F56nWzIDSFZ$
  519. //0復製这条口令( CZ00 D0M4WzI0jFJ¢,📱咑開[Tao宝]就可下单:/
  520. //8fuzhi本条消息:¤ CZ3458 JSR1WzrPCBU¤,打开🍑♭ɑ◑下单/
  521. //5€Lz6SWzrkLDw¥:// CZ13
  522. //3₲Igq3Wzkc5np₳:// CZ15
  523. //9.9🎈【康师傅易拉罐6罐】口伶:6₰TnxKWzr0wff₪:// CZ69
  524. //4₲99Y0WzJdK6S₳:// CZ46
  525. //4fuzhi本条消息:¤ CZ0002 WVCSWzrk6Ix¤,打开🍑♭ɑ◑下单/
  526. bool anyMatch = false;
  527. foreach (string pattern in mergedArray)
  528. {
  529. if (Regex.IsMatch(text, pattern, RegexOptions.IgnoreCase))
  530. {
  531. anyMatch = true;
  532. }
  533. }
  534. return anyMatch;
  535. }
  536. public static bool MatchOtherInfo(string text, List<string> extended)
  537. {
  538. string[] base_patterns =
  539. [
  540. "[ďȌƯƔɪƝɖƟɏƖԂȎȗϓɫɧơȲǏđǫƲƳɨǹƊȮǚƴɬɲƿȖȳɳɗʮϔӢǙɦɒɎƥʘưΊƞǪȈʠΌǓϒίȠƠƱƗǸþŌŬÿĩŅÞÓũŸÎŎûįŇĎÖÙŷÏňÜÝÍñĎÒüŶľńĎ0ųŷÏŇdǒǔyí℡抖yí℡ÞŐûŷÌñ]{6}",
  541. @"(?:.+)极速版(?:口令|搜索)",
  542. @"##[a-zA-Z0-9]+##\[抖音(?:极速版)?(?:口令|搜索)\]",
  543. @"岽|亰|菄|京东|婛",
  544. "打开【剪映】",
  545. "weishi://|baiduhaokan://",
  546. "复制打开「UC浏览器」|UC瀏覽器",
  547. "番茄免费小说",
  548. @"\?chanTag=[^&\s]*口令",
  549. @"(https?://pan\.baidu\.com/s/[A-Za-z0-9?\-_=]+)",
  550. @"https?:\/\/meeting\.tencent\.com[^\s]*",
  551. @"#腾讯会议:(\d{3}-\d{3}-\d{3})"
  552. ];
  553. List<string> mergedArray = extended.Union(base_patterns).ToList();
  554. bool anyMatch = false;
  555. foreach (string pattern in mergedArray)
  556. {
  557. if (Regex.IsMatch(text, pattern, RegexOptions.IgnoreCase))
  558. {
  559. anyMatch = true;
  560. }
  561. }
  562. return anyMatch;
  563. }
  564. public static bool MatchMultiToken(string text, List<string> extended)
  565. {
  566. text = RemoveUrls(text);
  567. string special_symbols = $"\\$\\(\\)\\/\\#\\&\\<\\>฿¢¥¥$🗝₰₵₲¤₪₴€₤£₳《¢💰🔑🎵✔💲🔐📲";
  568. string[] base_patterns =
  569. [
  570. @"[!$¥%]+([a-zA-Z0-9]{16})[!$¥%]+",
  571. @"\^v(\d+#[a-zA-Z0-9]+)(?:\?.*)?\^",
  572. "##([a-zA-Z0-9\\-]+)##",
  573. $@"(.*?\d{{2}}\s[a-zA-Z]{{2}}\d{{4}}\s.*?[{special_symbols}]+[a-zA-Z0-9\s]+[{special_symbols}]).*",
  574. $@"[{special_symbols}]+\s*([a-zA-Z]{{1,2}}\d{{2,4}}\s[a-zA-Z0-9]{{11}}|[a-zA-Z0-9]{{11}}[a-zA-Z]{{1,2}}\d{{2,4}}\s|[a-zA-Z0-9]{{11}})\s*[{special_symbols}]+",
  575. ];
  576. // PAGE6:/^v130091#P2J6EDxN8p8?chanTag=d9dc522bdea27437514052ea50f6a787^
  577. List<string> mergedArray = extended.Union(base_patterns).ToList();
  578. int matchCount = 0;
  579. foreach (string pattern in mergedArray)
  580. {
  581. Match match = Regex.Match(text, pattern, RegexOptions.IgnoreCase);
  582. if (match.Success)
  583. {
  584. matchCount++;
  585. text = text.Replace(match.Groups[^1].Value, ""); // 移除匹配的部分文本
  586. }
  587. }
  588. return matchCount >= 2;
  589. }
  590. public static bool FilterRiskLink(string ip, string oaid, string content, out string reason)
  591. {
  592. reason = string.Empty;
  593. string itemId = ExtractItemId(content);
  594. if (string.IsNullOrEmpty(itemId)) return false;
  595. string cacheKey = $":cache:parse:{ip}_{oaid}_{itemId}";
  596. int flag = RedisHelper.Get<int>(cacheKey);
  597. if (flag > 0)
  598. {
  599. reason = $"口令用户";
  600. return true;
  601. }
  602. return false;
  603. }
  604. public static bool ShouldIgnoreRequest(UnionParseRequest request, out string reason)
  605. {
  606. reason = string.Empty;
  607. ////2025-05-11 brw不做风控
  608. //if (!string.IsNullOrEmpty(riskStrategy) && !"os".Equals(riskStrategy) && launchScene != -1) return false;
  609. switch (request.RiskStrategy)
  610. {
  611. case "tbpush":
  612. case "brwsimilar":
  613. case "icon":
  614. return false;
  615. }
  616. try
  617. {
  618. // IP和流量控制
  619. var config = TkConfigCore.Get();
  620. string ignorePercentageCity = config.ignorePercentageCity;
  621. string? ipInfo = IP2RegionPlus.Search(request.Ip);
  622. if (!TestParseCore.InWhitelist(request.Ip, request.Oaid) && IgnoreRegionIncluded(ignorePercentageCity, ipInfo, out string regionInfo))
  623. {
  624. reason = $"地区控制:{regionInfo}";
  625. return true;
  626. }
  627. if (TkLogCore.InBlacklist(config.blacklist_oaid, request.Oaid))
  628. {
  629. reason = "OAID黑名单";
  630. return true;
  631. }
  632. int limit_num = config.tk_limit_per_ip_24h;
  633. if (!TestParseCore.InWhitelist(request.Ip, request.Oaid) && limit_num > 0)
  634. {
  635. int num = TkLogCore.getClientRequestTotalByIp(TkChannelEnum.tb, request.Ip);
  636. if (num >= limit_num)
  637. {
  638. reason = "IP控制";
  639. return true;
  640. }
  641. }
  642. limit_num = config.tk_limit_per_oaid_24h;
  643. if (!TestParseCore.InWhitelist(request.Ip, request.Oaid) && limit_num > 0)
  644. {
  645. int num = TkLogCore.getClientRequestTotalByOAID(TkChannelEnum.tb, request.Oaid);
  646. if (num >= limit_num)
  647. {
  648. reason = "OAID控制";
  649. return true;
  650. }
  651. }
  652. }
  653. catch (Exception ex)
  654. {
  655. reason = "配置异常";
  656. }
  657. return false;
  658. }
  659. public static bool FlowControlIgnoreRequest(UnionParseRequest request, out string reason)
  660. {
  661. reason = string.Empty;
  662. ////2025-05-11 brw不做风控
  663. //if (!string.IsNullOrEmpty(riskStrategy) && !"os".Equals(riskStrategy) && launchScene != -1) return false;
  664. switch (request.RiskStrategy)
  665. {
  666. case "tbpush":
  667. case "brwsimilar":
  668. case "icon":
  669. return false;
  670. }
  671. if (TestParseCore.InWhitelist(request.Ip, request.Oaid)) return false;
  672. try
  673. {
  674. // IP和流量控制
  675. var config = TkConfigCore.Get();
  676. int ignorePercentage = config.ignorePercentage;
  677. if (ignorePercentage == 0) return false;
  678. var randomValue = (decimal)_random.Next(0, 100);
  679. bool result = randomValue <= ignorePercentage; // 如果生成的随机数小于忽略百分比,则返回 true,表示需要忽略请求
  680. if (result)
  681. {
  682. reason = "流量控制";
  683. return true;
  684. }
  685. }
  686. catch (Exception ex)
  687. {
  688. reason = $"配置异常";
  689. }
  690. return false;
  691. }
  692. public static bool IsDigitsOnly(string? s)
  693. {
  694. return !string.IsNullOrEmpty(s)
  695. && s.AsSpan().IndexOfAnyExceptInRange('0', '9') < 0;
  696. }
  697. public static TkDataDTO GetFormattedObject(UnionParseRequest request)
  698. {
  699. string content = request.Content;
  700. switch (request.RiskStrategy)
  701. {
  702. case "tbpush":
  703. case "brwsimilar":
  704. case "icon":
  705. case "req":
  706. if (IsDigitsOnly(content))
  707. {
  708. content = $"https://item.taobao.com/item.htm?id={content}";
  709. }
  710. break;
  711. }
  712. string shortLinkurl = GetTaobaoLink(content);
  713. string deeplink_url = GetDeeplink(shortLinkurl);
  714. return new TkDataDTO()
  715. {
  716. message = string.Empty,
  717. subCode = TkSubCodeEnum.Other,
  718. channel = TkChannelEnum.tb,
  719. accountName = string.Empty,
  720. success = false,
  721. content = content,
  722. rawContent = request.Content,
  723. link_type = LinkTypeEnum.unknown,
  724. ip = request.Ip,
  725. oaid = request.Oaid,
  726. couponAmount = 0,
  727. taoToken = string.Empty,
  728. elapsedTime = 0,
  729. itemName = "点击打开淘宝APP",
  730. shortLinkurl = shortLinkurl,
  731. deeplink_url = deeplink_url,
  732. create_time = DateTime.Now,
  733. end_point = _end_point,
  734. parse_type = request.Type,
  735. riskStrategy = request.RiskStrategy,
  736. launchScene = request.LaunchScene,
  737. };
  738. }
  739. public static string OppoDecode(string content)
  740. {
  741. try
  742. {
  743. string secretKey = "BwFeIvOEDZy9MFGi0JLZBO4yEhR44DGV";
  744. byte[] keyBytes = Encoding.UTF8.GetBytes(secretKey);
  745. if (!content.Contains("%IV%")) return content;
  746. string cipherText = content.GetContentPart("", "%IV%");
  747. string ivText = content.GetContentPart("%IV%", "");
  748. byte[] cipherBytes = Convert.FromBase64String(cipherText);
  749. byte[] ivBytes = Convert.FromBase64String(ivText);
  750. using RijndaelManaged aes = new();
  751. aes.Key = keyBytes;
  752. aes.IV = ivBytes;
  753. aes.Mode = CipherMode.CFB;
  754. aes.Padding = PaddingMode.PKCS7;
  755. ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
  756. var outBytes = decryptor.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
  757. content = outBytes.ConvertToString();
  758. }
  759. catch (Exception e) { }
  760. return content;
  761. }
  762. }
  763. }