DeeplinkParseCore.cs 23 KB

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