DeeplinkParseCore.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  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. }
  142. break;
  143. case UrlAction.Body:
  144. {
  145. var response = await new WebClientUtility
  146. {
  147. Proxy = ProxyNodesCore.RandomOne(),
  148. UserAgent = ProviderFakeUserAgent.RandomMobile,
  149. AllowAutoRedirect = true
  150. }.RequestAsync(url);
  151. content = response.Body();
  152. }
  153. break;
  154. case UrlAction.None:
  155. //{
  156. // content = url;
  157. //}
  158. break;
  159. }
  160. }
  161. catch (Exception ex)
  162. {
  163. //Console.WriteLine($"{url}\t{rule.url_action}\t{ex.Message}");
  164. }
  165. if (rule.childs.Count > 0)
  166. {
  167. foreach (var sub_rule in rule.childs)
  168. {
  169. var e = await WorkEachRule(content, config, result, sub_rule);
  170. if (e != null) return e;
  171. }
  172. return null;
  173. }
  174. if (!string.IsNullOrEmpty(rule.body_pattern))
  175. {
  176. var regex = new Regex(rule.body_pattern);
  177. var match = regex.Match(content);
  178. if (!match.Success) return null;
  179. }
  180. var deeplink = rule.deeplink_template;
  181. var prompt_text = rule.prompt_text;
  182. try
  183. {
  184. var regex = new Regex(rule.pattern);
  185. var match = regex.Match(content);
  186. if (match.Success)
  187. {
  188. if (rule.resources.Count > 0)
  189. {
  190. foreach (var resource in rule.resources)
  191. {
  192. Dictionary<string, string> resResult = await ResourceProcessing(match, resource, rule.replacements);
  193. foreach (var e in resResult)
  194. {
  195. if (deeplink.Contains(e.Key))
  196. {
  197. deeplink = deeplink.Replace(e.Key, e.Value);
  198. }
  199. }
  200. }
  201. }
  202. if (match.Groups.Count > 1)
  203. {
  204. for (var i = 1; i < match.Groups.Count; i++)
  205. {
  206. string val = match.Groups[i].Value;
  207. switch (rule.plugin)
  208. {
  209. case "redu":
  210. string deeplink_url = await PluginDyParseAsync(text, val, result);
  211. if (!string.IsNullOrEmpty(deeplink_url))
  212. {
  213. result.itemName = prompt_text;
  214. result.deeplink_url = deeplink_url;
  215. result.success = true;
  216. return result;
  217. }
  218. break;
  219. }
  220. ReplaceProcessing(val, i, rule.replacements, ref deeplink, ref prompt_text);
  221. }
  222. if (rule.replace != null && rule.replace.Count > 0)
  223. {
  224. foreach (var r in rule.replace)
  225. {
  226. string key = r[0];
  227. if (string.IsNullOrEmpty(key)) continue;
  228. string val = string.Empty;
  229. if (r.Length > 1)
  230. {
  231. val = r[1];
  232. }
  233. deeplink = Regex.Replace(deeplink, key, val);
  234. }
  235. }
  236. deeplink = Regex.Replace(deeplink, @"\{\d+\}", string.Empty);
  237. prompt_text = Regex.Replace(prompt_text, @"\{\d+\}", string.Empty);
  238. if (!string.IsNullOrEmpty(deeplink))
  239. {
  240. result.deeplink_url = deeplink;
  241. result.itemName = prompt_text;
  242. result.success = true;
  243. return result;
  244. }
  245. }
  246. else
  247. {
  248. result.deeplink_url = deeplink;
  249. result.itemName = prompt_text;
  250. result.success = true;
  251. return result;
  252. }
  253. }
  254. }
  255. catch (Exception ex)
  256. {
  257. Console.WriteLine($"Error processing pattern '{rule.pattern}': {ex.Message}");
  258. }
  259. return null;
  260. }
  261. /// <summary>
  262. /// 占位符的处理
  263. /// </summary>
  264. /// <param name="word"></param>
  265. /// <param name="i"></param>
  266. /// <param name="deeplink"></param>
  267. /// <param name="prompt_text"></param>
  268. private static void ReplaceProcessing(string word, int i, List<ReplacementRule> replacements, ref string deeplink, ref string prompt_text)
  269. {
  270. if (deeplink.Contains("{url:"))
  271. {
  272. string encodedUrl = HttpUtility.UrlEncode(word);
  273. deeplink = deeplink.Replace($"{{url:{i - 1}}}", encodedUrl);
  274. }
  275. if (prompt_text.Contains("{url:"))
  276. {
  277. string encodedUrl = HttpUtility.UrlEncode(word);
  278. prompt_text = prompt_text.Replace($"{{url:{i - 1}}}", encodedUrl);
  279. }
  280. if (deeplink.Contains("{decode:"))
  281. {
  282. string encodedUrl = HttpUtility.UrlDecode(word);
  283. deeplink = deeplink.Replace($"{{decode:{i - 1}}}", encodedUrl);
  284. }
  285. if (prompt_text.Contains("{decode:"))
  286. {
  287. string encodedUrl = HttpUtility.UrlDecode(word);
  288. prompt_text = prompt_text.Replace($"{{decode:{i - 1}}}", encodedUrl);
  289. }
  290. //两次url编码
  291. if (deeplink.Contains("{url2:"))
  292. {
  293. string encodedUrl = HttpUtility.UrlEncode(word);
  294. encodedUrl = HttpUtility.UrlEncode(encodedUrl);
  295. deeplink = deeplink.Replace($"{{url2:{i - 1}}}", encodedUrl);
  296. }
  297. if (prompt_text.Contains("{url2:"))
  298. {
  299. string encodedUrl = HttpUtility.UrlEncode(word);
  300. encodedUrl = HttpUtility.UrlEncode(encodedUrl);
  301. prompt_text = prompt_text.Replace($"{{url2:{i - 1}}}", encodedUrl);
  302. }
  303. //三次url解码
  304. if (deeplink.Contains("{url3:"))
  305. {
  306. string encodedUrl = HttpUtility.UrlEncode(word);
  307. encodedUrl = HttpUtility.UrlEncode(encodedUrl);
  308. deeplink = deeplink.Replace($"{{url3:{i - 1}}}", encodedUrl);
  309. }
  310. if (prompt_text.Contains("{url3:"))
  311. {
  312. string encodedUrl = HttpUtility.UrlEncode(word);
  313. encodedUrl = HttpUtility.UrlEncode(encodedUrl);
  314. prompt_text = prompt_text.Replace($"{{url3:{i - 1}}}", encodedUrl);
  315. }
  316. //atob
  317. if (deeplink.Contains("{atob:"))
  318. {
  319. string encodedUrl = HttpUtility.UrlDecode(word);
  320. deeplink = deeplink.Replace($"{{atob:{i - 1}}}", encodedUrl.FromBase64());
  321. }
  322. if (prompt_text.Contains("{atob:"))
  323. {
  324. string encodedUrl = HttpUtility.UrlDecode(word);
  325. prompt_text = prompt_text.Replace($"{{atob:{i - 1}}}", encodedUrl.FromBase64());
  326. }
  327. //btoa
  328. if (deeplink.Contains("{btoa:"))
  329. {
  330. string encodedUrl = HttpUtility.UrlEncode(word);
  331. deeplink = deeplink.Replace($"{{btoa:{i - 1}}}", word.ToBase64());
  332. }
  333. if (prompt_text.Contains("{btoa:"))
  334. {
  335. string encodedUrl = HttpUtility.UrlEncode(word);
  336. prompt_text = prompt_text.Replace($"{{btoa:{i - 1}}}", word.ToBase64());
  337. }
  338. deeplink = deeplink.Replace($"{{{i - 1}}}", word);
  339. prompt_text = prompt_text.Replace($"{{{i - 1}}}", word);
  340. // 新增 <<>> 格式处理
  341. if (replacements != null)
  342. {
  343. deeplink = Regex.Replace(deeplink, @"<<(\w+):([^>]+)>>", match =>
  344. {
  345. var ruleName = match.Groups[1].Value;
  346. var value = match.Groups[2].Value;
  347. // 查找并应用替换规则
  348. var rule = replacements.FirstOrDefault(r => r.Name == ruleName);
  349. if (rule != null)
  350. {
  351. foreach (var r in rule.Rules)
  352. {
  353. if (r.When.Evaluate(value))
  354. {
  355. return r.Then;
  356. }
  357. }
  358. return rule.Default;
  359. }
  360. return value;
  361. });
  362. prompt_text = Regex.Replace(prompt_text, @"<<(\w+):([^>]+)>>", match =>
  363. {
  364. var ruleName = match.Groups[1].Value;
  365. var value = match.Groups[2].Value;
  366. // 查找并应用替换规则
  367. var rule = replacements.FirstOrDefault(r => r.Name == ruleName);
  368. if (rule != null)
  369. {
  370. foreach (var r in rule.Rules)
  371. {
  372. if (r.When.Evaluate(value))
  373. {
  374. return r.Then;
  375. }
  376. }
  377. return rule.Default;
  378. }
  379. return value;
  380. });
  381. }
  382. // 最后处理普通的索引替换
  383. deeplink = deeplink.Replace($"{{{i - 1}}}", word);
  384. prompt_text = prompt_text.Replace($"{{{i - 1}}}", word);
  385. }
  386. private static async Task<Dictionary<string, string>> ResourceProcessing(Match baseMatch, DeeplinkResources resource, List<ReplacementRule> replacements)
  387. {
  388. Dictionary<string, string> result = new Dictionary<string, string>();
  389. string url = resource.url_pattern;
  390. string prompt_text = string.Empty;
  391. for (var i = 1; i < baseMatch.Groups.Count; i++)
  392. {
  393. string val = baseMatch.Groups[i].Value;
  394. ReplaceProcessing(val, i, replacements, ref url, ref prompt_text);
  395. }
  396. string content = string.Empty;
  397. try
  398. {
  399. switch (resource.url_action)
  400. {
  401. case UrlAction.Redirect:
  402. {
  403. var response = await new WebClientUtility
  404. {
  405. Proxy = ProxyNodesCore.RandomOne(),
  406. UserAgent = ProviderFakeUserAgent.RandomMobile,
  407. AllowAutoRedirect = false
  408. }.RequestAsync(url);
  409. if (response.ResponseMessage != null)
  410. {
  411. content = response.ResponseMessage.Headers.Location.ToString();
  412. content = content.UrlDecode();
  413. }
  414. }
  415. break;
  416. case UrlAction.Body:
  417. case UrlAction.JsonBody:
  418. {
  419. var response = await new WebClientUtility
  420. {
  421. Proxy = ProxyNodesCore.RandomOne(),
  422. UserAgent = ProviderFakeUserAgent.RandomMobile,
  423. AllowAutoRedirect = true
  424. }.RequestAsync(url);
  425. content = response.Body();
  426. }
  427. break;
  428. case UrlAction.None:
  429. //{
  430. // content = url;
  431. //}
  432. break;
  433. }
  434. }
  435. catch (Exception ex)
  436. {
  437. //Console.WriteLine($"{url}\t{rule.url_action}\t{ex.Message}");
  438. }
  439. if (string.IsNullOrEmpty(content)) { return result; }
  440. try
  441. {
  442. JsonElement root = default;
  443. if (UrlAction.JsonBody.Equals(resource.url_action))
  444. {
  445. root = content.Convert2JsonElement();
  446. }
  447. for (int i = 0; i < resource.pattern.Count; i++)
  448. {
  449. string val = string.Empty;
  450. if (UrlAction.JsonBody.Equals(resource.url_action))
  451. {
  452. val = root.PathRead(resource.pattern[i], string.Empty);
  453. }
  454. else
  455. {
  456. var regex = new Regex(resource.pattern[i]);
  457. var match = regex.Match(content);
  458. if (match.Success)
  459. {
  460. val = match.Groups[1].Value;
  461. }
  462. }
  463. string key = $"{{{i}@{resource.name}}}";
  464. result.Add(key, val);
  465. }
  466. }
  467. catch (Exception ex) { }
  468. return result;
  469. }
  470. public static async Task<string> PluginDyParseAsync(string content, string matchText, DeeplinkParseDataDTO deeplinkResult, CancellationToken cancellationToken = default)
  471. {
  472. string ip = deeplinkResult.ip;
  473. string oaid = deeplinkResult.oaid;
  474. var result = DyUnionPlus.GetFormattedObject(content, ip, oaid);
  475. result.create_time = deeplinkResult.create_time;
  476. result.rawContent = content;
  477. bool IfExceptional = false;
  478. try
  479. {
  480. if (DyUnionPlus.ShouldIgnoreRequest(ip, oaid, out string reason))
  481. {
  482. result.success = false;
  483. result.message = "放弃转链";
  484. result.reason = reason;
  485. _ = TkLogCore.ParseLogAsync(result);
  486. return null;
  487. }
  488. var account = ReduPoolCore.GetOne();
  489. if (account == null)
  490. {
  491. result.success = false;
  492. result.message = "放弃转链";
  493. result.reason = "没有匹配账号";
  494. _ = TkLogCore.ParseLogAsync(result);
  495. return null;
  496. }
  497. var now = DateTime.Now;
  498. var ts2 = now - result.create_time;
  499. result.elapsedTime2 = (int)ts2.TotalMilliseconds;
  500. result = await DyUnionPlus.DyParseAsync(account, matchText, result, cancellationToken);
  501. switch (oaid)
  502. {
  503. case "3B191CFA4C6B48F9BA459E915B57743BEC7D424979CC9C51BCAD0C245B1C7BA2":
  504. case "6D5D56F3073844F2912B4552CEDF9E3BEC7D424979CC9C51C5461106F1915660":
  505. case "4CA55979100C4B5BAAA2AF4ABE15C360602e915cedae5786405419ccc9f4e3f8":
  506. break;
  507. default:
  508. result.deeplink_url = result.deeplink_url.Replace("snssdk1128://", "snssdk561124://");
  509. break;
  510. }
  511. var ts3 = DateTime.Now - now;
  512. result.elapsedTime3 = (int)ts3.TotalMilliseconds;
  513. }
  514. catch (Exception ex)
  515. {
  516. if (ex.Message.Contains("was canceled"))
  517. {
  518. result.success = false;
  519. result.message = "放弃转链";
  520. result.reason = "请求超时";
  521. }
  522. else
  523. {
  524. IfExceptional = true;
  525. _ = new LoggerLibrary("unionParse", "dy_error")
  526. .Info(ip, oaid)
  527. .Info(content)
  528. .Info(ex.Message, ex.StackTrace)
  529. .SaveAsync();
  530. NotifyCore.Notify(new NifyMessage
  531. {
  532. message = $"【转链异常DY】\n{content}\n\n{ex.Message}\n{ex.StackTrace}",
  533. priority = NifyMessagePriority.high,
  534. tags = ["red_circle"]
  535. });
  536. result.success = false;
  537. result.message = "内部错误";
  538. result.reason = "转链接口异常";
  539. }
  540. }
  541. _ = TkLogCore.ParseLogAsync(result);
  542. return result.deeplink_url;
  543. }
  544. }
  545. }