DeeplinkParseCore.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. 
  2. using dodohold.core;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Sayaka.Common;
  5. using System.Text.Json;
  6. using System.Text.RegularExpressions;
  7. using System.Web;
  8. namespace molilian.core
  9. {
  10. public partial class DeeplinkParseCore
  11. {
  12. private static string _end_point;
  13. private static readonly string[] separators = ["\r\n", "\n"];
  14. static DeeplinkParseCore()
  15. {
  16. _end_point = Environment.GetEnvironmentVariable("EndPoint");
  17. }
  18. public static DeeplinkParseDataDTO GetFormattedObject(string content, string channel, string ip = "", string oaid = "")
  19. {
  20. return new DeeplinkParseDataDTO()
  21. {
  22. message = string.Empty,
  23. success = false,
  24. content = content,
  25. ip = ip,
  26. oaid = oaid,
  27. elapsedTime = 0,
  28. create_time = DateTime.Now,
  29. end_point = _end_point,
  30. };
  31. }
  32. public static async Task<ActionResult> ParseAsync(string content, string channel, string ip, string oaid)
  33. {
  34. var result = GetFormattedObject(content, channel, ip, oaid);
  35. content = content.Trim();
  36. var rule = DeeplinkParseRuleCore.GetOne(channel);
  37. if (rule == null)
  38. {
  39. result.success = false;
  40. result.message = "转链失败";
  41. result.reason = "无效平台";
  42. _ = TkLogCore.ParseLogAsync(result);
  43. return new APIResult(new
  44. {
  45. result.success,
  46. result.message,
  47. result.reason,
  48. });
  49. }
  50. if (ShouldIgnoreRequest(rule.IgnorePercentageCity, ip, oaid, out string reason))
  51. {
  52. result.success = false;
  53. result.message = "放弃转链";
  54. result.reason = reason;
  55. _ = TkLogCore.ParseLogAsync(result);
  56. return new APIResult(new
  57. {
  58. result.success,
  59. result.message,
  60. result.reason,
  61. });
  62. }
  63. result.channel_id = rule.channel_id;
  64. result.channel_name = rule.channel_name;
  65. result = await GenerateDeeplink(content, rule, result);
  66. _ = TkLogCore.ParseLogAsync(result);
  67. return new APIResult(new
  68. {
  69. result.success,
  70. result.message,
  71. channel = result.channel_name,
  72. result.deeplink_url,
  73. result.itemName,
  74. });
  75. }
  76. public static bool ShouldIgnoreRequest(string ignorePercentageCity, string ip, string oaid, out string reason)
  77. {
  78. reason = string.Empty;
  79. try
  80. {
  81. // IP和流量控制
  82. string? ipInfo = IP2RegionPlus.Search(ip);
  83. if (!TestParseCore.InWhitelist(ip, oaid) && AlimamaPlus.IgnoreRegionIncluded(ignorePercentageCity, ipInfo, out string regionInfo))
  84. {
  85. reason = $"地区控制:{regionInfo}";
  86. return true;
  87. }
  88. }
  89. catch (Exception ex)
  90. {
  91. reason = "配置异常";
  92. }
  93. return false;
  94. }
  95. public static async Task<DeeplinkParseDataDTO> GenerateDeeplink(string text, DeeplinkParseRuleDTO config, DeeplinkParseDataDTO result)
  96. {
  97. try
  98. {
  99. var list = config.rules.Convert2Object<List<DeeplinkParseRule>>();
  100. foreach (var rule in list)
  101. {
  102. var e = await WorkEachRule(text, config, result, rule);
  103. if (e != null) return e;
  104. }
  105. }
  106. catch (Exception ex)
  107. {
  108. }
  109. result.success = false;
  110. return result;
  111. }
  112. private static async Task<DeeplinkParseDataDTO?> WorkEachRule(string text, DeeplinkParseRuleDTO config, DeeplinkParseDataDTO result, DeeplinkParseRule rule)
  113. {
  114. if (!rule.enable) return null;
  115. string content = text;
  116. if (!string.IsNullOrEmpty(rule.url_pattern))
  117. {
  118. var regex = new Regex(rule.url_pattern);
  119. var match = regex.Match(content);
  120. if (!match.Success) return null;
  121. content = match.Groups[1].Value;
  122. }
  123. string url = ToolParsePlus.GetLink(text);
  124. try
  125. {
  126. switch (rule.url_action)
  127. {
  128. case UrlAction.Redirect:
  129. {
  130. var response = await new WebClientUtility
  131. {
  132. Proxy = ProxyNodesCore.RandomOne(),
  133. UserAgent = ProviderFakeUserAgent.RandomMobile,
  134. AllowAutoRedirect = false
  135. }.RequestAsync(url);
  136. if (response.ResponseMessage != null)
  137. {
  138. content = response.ResponseMessage.Headers.Location.ToString();
  139. //content = content.UrlDecode();
  140. }
  141. if (string.IsNullOrEmpty(content)) return null;
  142. }
  143. break;
  144. case UrlAction.Body:
  145. {
  146. var client = new WebClientUtility
  147. {
  148. Proxy = ProxyNodesCore.RandomOne(),
  149. UserAgent = ProviderFakeUserAgent.RandomMobile,
  150. AllowAutoRedirect = true
  151. };
  152. if (!string.IsNullOrEmpty(rule.post))
  153. {
  154. string postData = rule.post;
  155. // 使用现有占位符处理逻辑
  156. if (!string.IsNullOrEmpty(rule.url_pattern))
  157. {
  158. var urlRegex = new Regex(rule.url_pattern);
  159. var urlMatch = urlRegex.Match(text);
  160. if (urlMatch.Success)
  161. {
  162. for (var i = 1; i < urlMatch.Groups.Count; i++)
  163. {
  164. string val = urlMatch.Groups[i].Value;
  165. string tempPrompt = string.Empty;
  166. ReplaceProcessing(val, i, rule.replacements, ref postData, ref tempPrompt);
  167. }
  168. }
  169. }
  170. client.Post(postData);
  171. }
  172. //https://weitoutiao.zjurl.cn/tt_living/?app=news_article&module_name=Android_tt_url&room_id=MDUEDEq2rcgYaV8/SarVCgQTTv3vQwSt/yRnpWHHMzSd1LxjfgQQXTdEOrBDTfdJCzQ+vyO1aQ==&share_did=MS4wLjACAAAASvJER5nlmrwCRfsC2t661YpMGJbq2HtGQS31wppWCCm_j6e1qZ7w9bp94n9T6Ouq&share_token=99222dee-be68-4f79-af9e-c32eff162ea8&share_uid=MS4wLjABAAAA9PBhcsrMuvXb3-0VPXN47TT4TKDHqiZR-LCS4B2BodaRdd7OHm7rl1Xx3SxlLrbn&timestamp=1756194703&tt_from=copy_link&upstream_biz=client_share&utm_campaign=client_share&utm_medium=toutiao_android&utm_source=copy_link
  173. //https://weitoutiao.zjurl.cn/tt_living/?app=news_article&module_name=Android_tt_url&room_id=MDUEDEq2rcgYaV8%2FSarVCgQTTv3vQwSt%2FyRnpWHHMzSd1LxjfgQQXTdEOrBDTfdJCzQ%2BvyO1aQ%3D%3D&share_did=MS4wLjACAAAASvJER5nlmrwCRfsC2t661YpMGJbq2HtGQS31wppWCCm_j6e1qZ7w9bp94n9T6Ouq&share_token=99222dee-be68-4f79-af9e-c32eff162ea8&share_uid=MS4wLjABAAAA9PBhcsrMuvXb3-0VPXN47TT4TKDHqiZR-LCS4B2BodaRdd7OHm7rl1Xx3SxlLrbn&timestamp=1756194703&tt_from=copy_link&upstream_biz=client_share&utm_campaign=client_share&utm_medium=toutiao_android&utm_source=copy_link
  174. var response = await client.RequestAsync(url);
  175. content = response.Body();
  176. if (string.IsNullOrEmpty(content)) return null;
  177. }
  178. break;
  179. case UrlAction.None:
  180. //{
  181. // content = url;
  182. //}
  183. break;
  184. }
  185. }
  186. catch (Exception ex)
  187. {
  188. //Console.WriteLine($"{url}\t{rule.url_action}\t{ex.Message}");
  189. }
  190. if (rule.childs.Count > 0)
  191. {
  192. foreach (var sub_rule in rule.childs)
  193. {
  194. var e = await WorkEachRule(content, config, result, sub_rule);
  195. if (e != null) return e;
  196. }
  197. return null;
  198. }
  199. if (!string.IsNullOrEmpty(rule.body_pattern))
  200. {
  201. var regex = new Regex(rule.body_pattern);
  202. var match = regex.Match(content);
  203. if (!match.Success) return null;
  204. }
  205. var deeplink = rule.deeplink_template;
  206. var prompt_text = rule.prompt_text;
  207. try
  208. {
  209. var regex = new Regex(rule.pattern);
  210. var match = regex.Match(content);
  211. if (match.Success)
  212. {
  213. if (rule.resources.Count > 0)
  214. {
  215. foreach (var resource in rule.resources)
  216. {
  217. Dictionary<string, string> resResult = await ResourceProcessing(match, resource, rule.replacements);
  218. foreach (var e in resResult)
  219. {
  220. if (deeplink.Contains(e.Key))
  221. {
  222. deeplink = deeplink.Replace(e.Key, e.Value);
  223. }
  224. }
  225. }
  226. }
  227. if (match.Groups.Count > 1)
  228. {
  229. for (var i = 1; i < match.Groups.Count; i++)
  230. {
  231. string val = match.Groups[i].Value;
  232. switch (rule.plugin)
  233. {
  234. case "redu":
  235. string deeplink_url = await PluginDyParseAsync(text, val, result);
  236. if (!string.IsNullOrEmpty(deeplink_url))
  237. {
  238. result.itemName = prompt_text;
  239. result.deeplink_url = deeplink_url;
  240. result.success = true;
  241. return result;
  242. }
  243. break;
  244. }
  245. ReplaceProcessing(val, i, rule.replacements, ref deeplink, ref prompt_text);
  246. }
  247. if (rule.replace != null && rule.replace.Count > 0)
  248. {
  249. foreach (var r in rule.replace)
  250. {
  251. string key = r[0];
  252. if (string.IsNullOrEmpty(key)) continue;
  253. string val = string.Empty;
  254. if (r.Length > 1)
  255. {
  256. val = r[1];
  257. }
  258. deeplink = Regex.Replace(deeplink, key, val);
  259. }
  260. }
  261. deeplink = Regex.Replace(deeplink, @"\{\d+\}", string.Empty);
  262. prompt_text = Regex.Replace(prompt_text, @"\{\d+\}", string.Empty);
  263. if (!string.IsNullOrEmpty(deeplink))
  264. {
  265. result.deeplink_url = deeplink;
  266. result.itemName = prompt_text;
  267. result.success = true;
  268. return result;
  269. }
  270. }
  271. else
  272. {
  273. result.deeplink_url = deeplink;
  274. result.itemName = prompt_text;
  275. result.success = true;
  276. return result;
  277. }
  278. }
  279. }
  280. catch (Exception ex)
  281. {
  282. Console.WriteLine($"Error processing pattern '{rule.pattern}': {ex.Message}");
  283. }
  284. return null;
  285. }
  286. /// <summary>
  287. /// 占位符的处理
  288. /// </summary>
  289. /// <param name="word"></param>
  290. /// <param name="i"></param>
  291. /// <param name="deeplink"></param>
  292. /// <param name="prompt_text"></param>
  293. private static void ReplaceProcessing(string word, int i, List<ReplacementRule> replacements, ref string deeplink, ref string prompt_text)
  294. {
  295. if (deeplink.Contains("{url:"))
  296. {
  297. string encodedUrl = HttpUtility.UrlEncode(word);
  298. deeplink = deeplink.Replace($"{{url:{i - 1}}}", encodedUrl);
  299. }
  300. if (prompt_text.Contains("{url:"))
  301. {
  302. string encodedUrl = HttpUtility.UrlEncode(word);
  303. prompt_text = prompt_text.Replace($"{{url:{i - 1}}}", encodedUrl);
  304. }
  305. if (deeplink.Contains("{decode:"))
  306. {
  307. string encodedUrl = HttpUtility.UrlDecode(word);
  308. deeplink = deeplink.Replace($"{{decode:{i - 1}}}", encodedUrl);
  309. }
  310. if (prompt_text.Contains("{decode:"))
  311. {
  312. string encodedUrl = HttpUtility.UrlDecode(word);
  313. prompt_text = prompt_text.Replace($"{{decode:{i - 1}}}", encodedUrl);
  314. }
  315. //两次url编码
  316. if (deeplink.Contains("{url2:"))
  317. {
  318. string encodedUrl = HttpUtility.UrlEncode(word);
  319. encodedUrl = HttpUtility.UrlEncode(encodedUrl);
  320. deeplink = deeplink.Replace($"{{url2:{i - 1}}}", encodedUrl);
  321. }
  322. if (prompt_text.Contains("{url2:"))
  323. {
  324. string encodedUrl = HttpUtility.UrlEncode(word);
  325. encodedUrl = HttpUtility.UrlEncode(encodedUrl);
  326. prompt_text = prompt_text.Replace($"{{url2:{i - 1}}}", encodedUrl);
  327. }
  328. //三次url解码
  329. if (deeplink.Contains("{url3:"))
  330. {
  331. string encodedUrl = HttpUtility.UrlEncode(word);
  332. encodedUrl = HttpUtility.UrlEncode(encodedUrl);
  333. deeplink = deeplink.Replace($"{{url3:{i - 1}}}", encodedUrl);
  334. }
  335. if (prompt_text.Contains("{url3:"))
  336. {
  337. string encodedUrl = HttpUtility.UrlEncode(word);
  338. encodedUrl = HttpUtility.UrlEncode(encodedUrl);
  339. prompt_text = prompt_text.Replace($"{{url3:{i - 1}}}", encodedUrl);
  340. }
  341. //atob
  342. if (deeplink.Contains("{atob:"))
  343. {
  344. string encodedUrl = HttpUtility.UrlDecode(word);
  345. deeplink = deeplink.Replace($"{{atob:{i - 1}}}", encodedUrl.FromBase64());
  346. }
  347. if (prompt_text.Contains("{atob:"))
  348. {
  349. string encodedUrl = HttpUtility.UrlDecode(word);
  350. prompt_text = prompt_text.Replace($"{{atob:{i - 1}}}", encodedUrl.FromBase64());
  351. }
  352. //btoa
  353. if (deeplink.Contains("{btoa:"))
  354. {
  355. string encodedUrl = HttpUtility.UrlEncode(word);
  356. deeplink = deeplink.Replace($"{{btoa:{i - 1}}}", word.ToBase64());
  357. }
  358. if (prompt_text.Contains("{btoa:"))
  359. {
  360. string encodedUrl = HttpUtility.UrlEncode(word);
  361. prompt_text = prompt_text.Replace($"{{btoa:{i - 1}}}", word.ToBase64());
  362. }
  363. deeplink = deeplink.Replace($"{{{i - 1}}}", word);
  364. prompt_text = prompt_text.Replace($"{{{i - 1}}}", word);
  365. // 新增 <<>> 格式处理
  366. if (replacements != null)
  367. {
  368. deeplink = Regex.Replace(deeplink, @"<<(\w+):([^>]+)>>", match =>
  369. {
  370. var ruleName = match.Groups[1].Value;
  371. var value = match.Groups[2].Value;
  372. // 查找并应用替换规则
  373. var rule = replacements.FirstOrDefault(r => r.Name == ruleName);
  374. if (rule != null)
  375. {
  376. foreach (var r in rule.Rules)
  377. {
  378. if (r.When.Evaluate(value))
  379. {
  380. return r.Then;
  381. }
  382. }
  383. return rule.Default;
  384. }
  385. return value;
  386. });
  387. prompt_text = Regex.Replace(prompt_text, @"<<(\w+):([^>]+)>>", match =>
  388. {
  389. var ruleName = match.Groups[1].Value;
  390. var value = match.Groups[2].Value;
  391. // 查找并应用替换规则
  392. var rule = replacements.FirstOrDefault(r => r.Name == ruleName);
  393. if (rule != null)
  394. {
  395. foreach (var r in rule.Rules)
  396. {
  397. if (r.When.Evaluate(value))
  398. {
  399. return r.Then;
  400. }
  401. }
  402. return rule.Default;
  403. }
  404. return value;
  405. });
  406. }
  407. // 最后处理普通的索引替换
  408. deeplink = deeplink.Replace($"{{{i - 1}}}", word);
  409. prompt_text = prompt_text.Replace($"{{{i - 1}}}", word);
  410. }
  411. private static async Task<Dictionary<string, string>> ResourceProcessing(Match baseMatch, DeeplinkResources resource, List<ReplacementRule> replacements)
  412. {
  413. Dictionary<string, string> result = new Dictionary<string, string>();
  414. string url = resource.url_pattern;
  415. string prompt_text = string.Empty;
  416. for (var i = 1; i < baseMatch.Groups.Count; i++)
  417. {
  418. string val = baseMatch.Groups[i].Value;
  419. ReplaceProcessing(val, i, replacements, ref url, ref prompt_text);
  420. }
  421. string content = string.Empty;
  422. try
  423. {
  424. switch (resource.url_action)
  425. {
  426. case UrlAction.Redirect:
  427. {
  428. var response = await new WebClientUtility
  429. {
  430. Proxy = ProxyNodesCore.RandomOne(),
  431. UserAgent = ProviderFakeUserAgent.RandomMobile,
  432. AllowAutoRedirect = false
  433. }.RequestAsync(url);
  434. if (response.ResponseMessage != null)
  435. {
  436. content = response.ResponseMessage.Headers.Location.ToString();
  437. content = content.UrlDecode();
  438. }
  439. }
  440. break;
  441. case UrlAction.Body:
  442. case UrlAction.JsonBody:
  443. {
  444. //var response = await new WebClientUtility
  445. //{
  446. // Proxy = ProxyNodesCore.RandomOne(),
  447. // UserAgent = ProviderFakeUserAgent.RandomMobile,
  448. // AllowAutoRedirect = true
  449. //}.RequestAsync(url);
  450. var client = new WebClientUtility
  451. {
  452. Proxy = ProxyNodesCore.RandomOne(),
  453. UserAgent = ProviderFakeUserAgent.RandomMobile,
  454. AllowAutoRedirect = true
  455. };
  456. if (!string.IsNullOrEmpty(resource.post))
  457. {
  458. string postData = resource.post;
  459. // 处理POST数据中的占位符
  460. for (var i = 1; i < baseMatch.Groups.Count; i++)
  461. {
  462. string val = baseMatch.Groups[i].Value;
  463. ReplaceProcessing(val, i, replacements, ref postData, ref prompt_text);
  464. }
  465. client.Post(postData);
  466. }
  467. var response = await client.RequestAsync(url);
  468. content = response.Body();
  469. }
  470. break;
  471. case UrlAction.None:
  472. //{
  473. // content = url;
  474. //}
  475. break;
  476. }
  477. }
  478. catch (Exception ex)
  479. {
  480. //Console.WriteLine($"{url}\t{rule.url_action}\t{ex.Message}");
  481. }
  482. if (string.IsNullOrEmpty(content)) { return result; }
  483. try
  484. {
  485. JsonElement root = default;
  486. if (UrlAction.JsonBody.Equals(resource.url_action))
  487. {
  488. root = content.Convert2JsonElement();
  489. }
  490. for (int i = 0; i < resource.pattern.Count; i++)
  491. {
  492. string val = string.Empty;
  493. if (UrlAction.JsonBody.Equals(resource.url_action))
  494. {
  495. val = root.PathRead(resource.pattern[i], string.Empty);
  496. }
  497. else
  498. {
  499. var regex = new Regex(resource.pattern[i]);
  500. var match = regex.Match(content);
  501. if (match.Success)
  502. {
  503. val = match.Groups[1].Value;
  504. }
  505. }
  506. string key = $"{{{i}@{resource.name}}}";
  507. result.Add(key, val);
  508. }
  509. }
  510. catch (Exception ex) { }
  511. return result;
  512. }
  513. public static async Task<string> PluginDyParseAsync(string content, string matchText, DeeplinkParseDataDTO deeplinkResult, CancellationToken cancellationToken = default)
  514. {
  515. string ip = deeplinkResult.ip;
  516. string oaid = deeplinkResult.oaid;
  517. var result = DyUnionPlus.GetFormattedObject(content, ip, oaid);
  518. result.create_time = deeplinkResult.create_time;
  519. result.rawContent = content;
  520. bool IfExceptional = false;
  521. try
  522. {
  523. if (DyUnionPlus.ShouldIgnoreRequest(ip, oaid, out string reason))
  524. {
  525. result.success = false;
  526. result.message = "放弃转链";
  527. result.reason = reason;
  528. _ = TkLogCore.ParseLogAsync(result);
  529. return null;
  530. }
  531. var account = ReduPoolCore.GetOne();
  532. if (account == null)
  533. {
  534. result.success = false;
  535. result.message = "放弃转链";
  536. result.reason = "没有匹配账号";
  537. _ = TkLogCore.ParseLogAsync(result);
  538. return null;
  539. }
  540. var now = DateTime.Now;
  541. var ts2 = now - result.create_time;
  542. result.elapsedTime2 = (int)ts2.TotalMilliseconds;
  543. result = await DyUnionPlus.DyParseAsync(account, matchText, result, cancellationToken);
  544. switch (oaid)
  545. {
  546. case "3B191CFA4C6B48F9BA459E915B57743BEC7D424979CC9C51BCAD0C245B1C7BA2":
  547. case "6D5D56F3073844F2912B4552CEDF9E3BEC7D424979CC9C51C5461106F1915660":
  548. case "4CA55979100C4B5BAAA2AF4ABE15C360602e915cedae5786405419ccc9f4e3f8":
  549. break;
  550. default:
  551. result.deeplink_url = result.deeplink_url.Replace("snssdk1128://", "snssdk561124://");
  552. break;
  553. }
  554. var ts3 = DateTime.Now - now;
  555. result.elapsedTime3 = (int)ts3.TotalMilliseconds;
  556. }
  557. catch (Exception ex)
  558. {
  559. if (ex.Message.Contains("was canceled"))
  560. {
  561. result.success = false;
  562. result.message = "放弃转链";
  563. result.reason = "请求超时";
  564. }
  565. else
  566. {
  567. IfExceptional = true;
  568. _ = new LoggerLibrary("unionParse", "dy_error")
  569. .Info(ip, oaid)
  570. .Info(content)
  571. .Info(ex.Message, ex.StackTrace)
  572. .SaveAsync();
  573. NotifyCore.Notify(new NifyMessage
  574. {
  575. message = $"【转链异常DY】\n{content}\n\n{ex.Message}\n{ex.StackTrace}",
  576. priority = NifyMessagePriority.high,
  577. tags = ["red_circle"]
  578. });
  579. result.success = false;
  580. result.message = "内部错误";
  581. result.reason = "转链接口异常";
  582. }
  583. }
  584. _ = TkLogCore.ParseLogAsync(result);
  585. return result.deeplink_url;
  586. }
  587. }
  588. }