parse.cs 35 KB

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