parse_2.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. using dodohold.core;
  2. using System.Text.RegularExpressions;
  3. using System.Diagnostics;
  4. using System.Text.Json;
  5. using TencentCloud.Fmu.V20191213.Models;
  6. namespace molilian.core
  7. {
  8. public partial class AlimamaPlus
  9. {
  10. public void UnionParse2(string content, ref TkDataDTO result)
  11. {
  12. if ("veapi".Equals(_api) && _api_id > 0)
  13. {
  14. var account = VeapiPoolCore.Get(_api_id);
  15. if (account != null)
  16. {
  17. var core = new VeapiPlus(account.name, account.key, account.sessionKey);
  18. core.UnionParse(content, ref result);
  19. return;
  20. }
  21. }
  22. UnionParse(content, ref result);
  23. }
  24. public async Task<TkDataDTO> UnionParse2Async(string content, TkDataDTO result)
  25. {
  26. if ("veapi".Equals(_api) && _api_id > 0)
  27. {
  28. var account = VeapiPoolCore.Get(_api_id);
  29. if (account != null)
  30. {
  31. var core = new VeapiPlus(account.name, account.key, account.sessionKey);
  32. result = await core.UnionParseAsync(content, result);
  33. return result;
  34. }
  35. }
  36. result = await UnionParseAsync(content, result);
  37. return result;
  38. }
  39. /// <summary>
  40. /// 提取url里面的id参数
  41. /// </summary>
  42. /// <param name="url"></param>
  43. /// <returns></returns>
  44. static string? ExtractItemId(string url)
  45. {
  46. Match match = Regex.Match(url, @"(?:\?|&)id=(\d+)");
  47. if (match.Success)
  48. {
  49. return match.Groups[1].Value;
  50. }
  51. return null;
  52. }
  53. /// <summary>
  54. /// 是否淘宝链接
  55. /// </summary>
  56. /// <param name="url"></param>
  57. /// <returns></returns>
  58. private static (bool, string) IsTaobaoUrl(string url)
  59. {
  60. if (url.Contains("//a.m.taobao.com/i"))
  61. {
  62. //第一种提取方法
  63. string itemId = url.GetContentPart("//a.m.taobao.com/i", ".htm");
  64. if (!string.IsNullOrEmpty(itemId))
  65. {
  66. string resultUrl = $"https://item.taobao.com/item.htm?id={itemId}";
  67. return (true, resultUrl);
  68. }
  69. }
  70. if (url.Contains("//item.taobao.com/item.htm?") ||
  71. url.Contains("//h5.m.taobao.com/awp/core/detail.htm?") ||
  72. url.Contains("//new.m.taobao.com/detail.htm?") ||
  73. url.Contains("//outfliggys.m.taobao.com/app/trip/rx-travel-detail") ||
  74. url.Contains("//detail.m.tmall.com/item.htm?") ||
  75. url.Contains("//tmallx.tmall.com/app/tmallx-src/goods-detail") ||
  76. url.Contains("//detail.tmall.com/item.htm?") ||
  77. url.Contains("//detail.tmall.hk/hk/item.htm?"))
  78. {
  79. string? itemId = ExtractItemId(url);
  80. if (!string.IsNullOrEmpty(itemId))
  81. {
  82. string resultUrl = $"https://item.taobao.com/item.htm?id={itemId}";
  83. return (true, resultUrl);
  84. }
  85. }
  86. return (false, url);
  87. }
  88. /// <summary>
  89. /// 排除已知的淘客链接
  90. /// </summary>
  91. /// <param name="url"></param>
  92. /// <returns></returns>
  93. static bool IsAffLink(string url)
  94. {
  95. if (!url.StartsWith("https://") || !url.StartsWith("https://")) url = "https://" + url;
  96. Uri uri = new(url);
  97. if (uri.Host.Equals("s.click.taobao.com", StringComparison.OrdinalIgnoreCase) ||
  98. uri.Host.Equals("uland.taobao.com", StringComparison.OrdinalIgnoreCase))
  99. {
  100. return true;
  101. }
  102. if (uri.Host.Equals("m.tb.cn", StringComparison.OrdinalIgnoreCase) &&
  103. uri.AbsolutePath.StartsWith("/h.") &&
  104. string.IsNullOrEmpty(uri.Query) && // No query parameters
  105. !url.Contains("?tk=")) // No "tk" parameter
  106. {
  107. return true;
  108. }
  109. return false;
  110. }
  111. /// <summary>
  112. /// 判断淘客的¥羊角符号
  113. /// </summary>
  114. /// <param name="content"></param>
  115. /// <returns></returns>
  116. static bool ContainsSpecialFormat(string content)
  117. {
  118. // 使用正则表达式匹配内容中是否含有特定格式的字符串
  119. //string pattern = @"¥[a-zA-Z0-9\s]+¥";
  120. string pattern = @"[$¥🗝₴€₤£₳✔《💰🔑🎵✔️💲🔐📲]+[a-zA-Z0-9]+[$¥🗝₴€₤£₳✔《💰🔑🎵✔️💲🔐📲]*";
  121. return Regex.IsMatch(content, pattern);
  122. }
  123. /// <summary>
  124. /// 从http获取跳转的url
  125. /// </summary>
  126. /// <param name="url"></param>
  127. /// <returns></returns>
  128. (bool, string) GetDesiredUrl(string url)
  129. {
  130. string result;
  131. try
  132. {
  133. string desiredUrlPattern = "var url = '(.*?)'";
  134. WebClientUtility client = new()
  135. {
  136. Proxy = _proxy,
  137. UserAgent = Sayaka.Common.ProviderFakeUserAgent.RandomComputer
  138. };
  139. #if DEBUG
  140. client.Proxy = null;
  141. #else
  142. client.Timeout = TimeSpan.FromMilliseconds(3000);
  143. #endif
  144. var response = client.Request(url);
  145. var responseBody = response.Body();
  146. result = responseBody;
  147. if (response.Successed)
  148. {
  149. if (response.ResponseMessage.IsSuccessStatusCode)
  150. {
  151. Match match = Regex.Match(responseBody, desiredUrlPattern);
  152. if (match.Success)
  153. {
  154. result = match.Groups[1].Value; // 返回匹配的 URL
  155. if (string.IsNullOrEmpty(result)) return (false, "没有匹配的URL");
  156. return (true, result);
  157. }
  158. }
  159. else
  160. {
  161. result = $"{response.ResponseMessage.StatusCode}\n{responseBody}";
  162. }
  163. }
  164. else
  165. {
  166. throw response.ResponseException;
  167. }
  168. }
  169. catch (Exception ex)
  170. {
  171. result = $"{ex.Message}\n{ex.StackTrace}";
  172. }
  173. return (false, result);
  174. }
  175. private (bool, string, LinkTypeEnum, string) InternalTextProcessing(string content)
  176. {
  177. bool success;
  178. string result;
  179. LinkTypeEnum link_type = LinkTypeEnum.unknown;
  180. string url = GetLink(content);
  181. if (!string.IsNullOrEmpty(url))
  182. {
  183. //排除已知的淘客链接
  184. if (IsAffLink(url)) return (false, "排除淘客链接", LinkTypeEnum.other_aff, url);
  185. //直接提取
  186. (success, result) = IsTaobaoUrl(url);
  187. if (success) return (true, result, LinkTypeEnum.goods, result);
  188. //从http获取跳转的url
  189. (success, result) = GetDesiredUrl(url);
  190. if (success)
  191. {
  192. //排除已知的淘客链接
  193. if (IsAffLink(result)) return (false, "排除淘客链接", LinkTypeEnum.other_aff, result);
  194. (success, result) = IsTaobaoUrl(result);
  195. if (success) return (true, result, LinkTypeEnum.goods, result);
  196. }
  197. link_type = GetLinkType(url);
  198. return (false, result, link_type, url);
  199. }
  200. //判断淘客的¥羊角符号
  201. if (ContainsSpecialFormat(content)) return (false, "排除淘口令", LinkTypeEnum.other_aff, null);
  202. return (false, "纯口令 没链接", link_type, null);
  203. }
  204. private LinkTypeEnum GetLinkType(string url)
  205. {
  206. if (string.IsNullOrEmpty(url)) return LinkTypeEnum.unknown;
  207. if (url.StartsWith("https://huodong.m.taobao.com/act/talent/live.html")) return LinkTypeEnum.live;
  208. if (url.StartsWith("https://web.m.taobao.com/app/tnode/web/index")) return LinkTypeEnum.video;
  209. string pattern = @"^https://shop\d+\.m\.taobao\.com";
  210. if (Regex.IsMatch(url, pattern))
  211. {
  212. return LinkTypeEnum.profile;
  213. }
  214. return LinkTypeEnum.unknown;
  215. }
  216. private void alimamaParse(string content, ref TkDataDTO result)
  217. {
  218. string t = $"{DateTime.Now.Convert2UnixTimestamp(true)}";
  219. Random random = new();
  220. double randomNumber = random.NextDouble();
  221. string randomString = randomNumber.ToString()[2..];
  222. string cna = _cookies.GetContentPart("cna=", ";");
  223. string firstFiveCharacters = cna[..Math.Min(5, cna.Length)];
  224. var variableMap = new
  225. {
  226. url = content,
  227. union_lens = $"b_pvid:a219t._portal_v2_tool_links_page_home_index_htm_{t}_{randomString}_{firstFiveCharacters}",
  228. lensScene = "PUB",
  229. spmB = "_portal_v2_tool_links_page_home_index_htm"
  230. }.Convert2Json(true).UrlEncode();
  231. variableMap = variableMap.Replace(" ", "%20");
  232. string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/xt.entry.json?" +
  233. $"t={t}&_tb_token_={_tb_token}&floorId={_floorId}&refpid={_refpid}&variableMap={variableMap}";
  234. var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
  235. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  236. .AddHeaders("Cookie", _cookies);
  237. client.Proxy = _proxy;
  238. #if DEBUG
  239. client.Proxy = null;
  240. #endif
  241. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  242. client.Timeout = TimeSpan.FromMilliseconds(1000);
  243. var response = client.Request(url);
  244. var body = string.Empty;
  245. try
  246. {
  247. if (!response.Successed)
  248. {
  249. result.channel = TkChannelEnum.tb;
  250. result.accountName = _accountName;
  251. result.link_type = LinkTypeEnum.unknown;
  252. result.success = false;
  253. result.message = "fail";
  254. if (response.ResponseException != null)
  255. {
  256. new LoggerLibrary("api_error", "fail")
  257. .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
  258. .Save();
  259. throw response.ResponseException;
  260. }
  261. return;
  262. }
  263. body = response.Body();
  264. JsonElement root = body.Convert2JsonElement();
  265. bool success = root.Read<bool>("success", false);
  266. string message = root.Read("message", string.Empty);
  267. string info_message = root.PathRead("info.message", string.Empty);
  268. if (!string.IsNullOrEmpty(info_message)) message = info_message;
  269. string taoToken = root.PathRead("data.taoToken", string.Empty);
  270. string shortLinkurl = root.PathRead("data.shortLinkurl", string.Empty);
  271. string couponLinkTaoToken = root.PathRead("data.couponLinkTaoToken", string.Empty);
  272. string couponShortLinkUrl = root.PathRead("data.couponShortLinkUrl", string.Empty);
  273. decimal couponAmount = root.PathRead<decimal>("data.couponAmount", 0);
  274. string itemId = root.PathRead("data.itemId", string.Empty);
  275. string itemName = root.PathRead("data.itemName", string.Empty);
  276. decimal promotionPrice = root.PathRead<decimal>("data.promotionPrice", 0);
  277. string sellerNickName = root.PathRead("data.sellerNickName", string.Empty);
  278. string shopTitle = root.PathRead("data.shopTitle", string.Empty);
  279. string pic = root.PathRead("data.pic", string.Empty);
  280. string qrCodeUrl = root.PathRead("data.qrCodeUrl", string.Empty);
  281. if (response.ResponseMessage != null)
  282. {
  283. switch (response.ResponseMessage.StatusCode)
  284. {
  285. case System.Net.HttpStatusCode.OK:
  286. {
  287. if (couponAmount > 0 && !string.IsNullOrEmpty(couponLinkTaoToken) && !string.IsNullOrEmpty(couponShortLinkUrl))
  288. {
  289. taoToken = couponLinkTaoToken;
  290. shortLinkurl = couponShortLinkUrl;
  291. }
  292. string shortLink = GetLink(taoToken);
  293. content = ReplaceUrls(content, shortLink);
  294. }
  295. break;
  296. case System.Net.HttpStatusCode.Found:
  297. string location = response.ResponseMessage.Headers.Location.OriginalString;
  298. if (!string.IsNullOrEmpty(location) && location.Contains("www.alimama.com/member/login.htm"))
  299. {
  300. success = false;
  301. message = "nologin";
  302. }
  303. break;
  304. default:
  305. {
  306. success = false;
  307. message = "other";
  308. }
  309. break;
  310. }
  311. }
  312. if (!success)
  313. {
  314. shortLinkurl = GetLink(content);
  315. switch (message)
  316. {
  317. case "该链接不支持转化,请更换链接尝试":
  318. case "网络错误":
  319. break;
  320. default:
  321. var _headers = response.ResponseMessage.Headers;
  322. var headers = "";
  323. foreach (var h in _headers)
  324. {
  325. foreach (var Value in h.Value)
  326. {
  327. headers += $"{h.Key}: {Value}\n";
  328. }
  329. }
  330. new LoggerLibrary("api_error", "fail")
  331. .Info(message, content)
  332. .Info(headers, body)
  333. .Save();
  334. break;
  335. }
  336. }
  337. string deeplink_url = GetDeeplink(shortLinkurl);
  338. result.channel = TkChannelEnum.tb;
  339. result.accountName = _accountName;
  340. result.link_type = success ? LinkTypeEnum.goods : result.link_type;
  341. result.success = success;
  342. result.message = message;
  343. result.content = content;
  344. result.couponAmount = couponAmount;
  345. result.taoToken = taoToken;
  346. result.shortLinkurl = shortLinkurl;
  347. result.deeplink_url = deeplink_url;
  348. result.itemId = itemId;
  349. result.itemName = itemName;
  350. result.promotionPrice = promotionPrice;
  351. result.sellerNickName = sellerNickName;
  352. result.shopTitle = shopTitle;
  353. result.pic = pic;
  354. result.qrCodeUrl = qrCodeUrl;
  355. }
  356. catch
  357. {
  358. if (response.ResponseMessage?.StatusCode == System.Net.HttpStatusCode.OK)
  359. {
  360. if (body.Contains("<p>抱歉!页面无法访问……</p>"))
  361. {
  362. throw new APIException("抱歉!页面无法访问……");
  363. }
  364. }
  365. throw;
  366. }
  367. }
  368. private async Task<TkDataDTO> alimamaParseAsync(string content, TkDataDTO result)
  369. {
  370. string t = $"{DateTime.Now.Convert2UnixTimestamp(true)}";
  371. Random random = new();
  372. double randomNumber = random.NextDouble();
  373. string randomString = randomNumber.ToString()[2..];
  374. string cna = _cookies.GetContentPart("cna=", ";");
  375. string firstFiveCharacters = cna[..Math.Min(5, cna.Length)];
  376. var variableMap = new
  377. {
  378. url = content,
  379. union_lens = $"b_pvid:a219t._portal_v2_tool_links_page_home_index_htm_{t}_{randomString}_{firstFiveCharacters}",
  380. lensScene = "PUB",
  381. spmB = "_portal_v2_tool_links_page_home_index_htm"
  382. }.Convert2Json(true).UrlEncode();
  383. variableMap = variableMap.Replace(" ", "%20");
  384. string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/xt.entry.json?" +
  385. $"t={t}&_tb_token_={_tb_token}&floorId={_floorId}&refpid={_refpid}&variableMap={variableMap}";
  386. var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
  387. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  388. .AddHeaders("Cookie", _cookies);
  389. client.Proxy = _proxy;
  390. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  391. client.Timeout = TimeSpan.FromMilliseconds(1000);
  392. #if DEBUG
  393. client.Proxy = null;
  394. client.Timeout = TimeSpan.FromMilliseconds(10000);
  395. #endif
  396. var response = client.Request(url);
  397. var body = string.Empty;
  398. try
  399. {
  400. if (!response.Successed)
  401. {
  402. result.channel = TkChannelEnum.tb;
  403. result.accountName = _accountName;
  404. result.link_type = LinkTypeEnum.unknown;
  405. result.success = false;
  406. result.message = "fail";
  407. if (response.ResponseException != null)
  408. {
  409. new LoggerLibrary("api_error", "fail")
  410. .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
  411. .Save();
  412. throw response.ResponseException;
  413. }
  414. return result;
  415. }
  416. body = response.Body();
  417. //{"code":601,"info":{"ok":false,"message":"nologin"}}
  418. JsonElement root = body.Convert2JsonElement();
  419. bool success = root.Read<bool>("success", false);
  420. string message = root.Read("message", string.Empty);
  421. string info_message = root.PathRead("info.message", string.Empty);
  422. if (!string.IsNullOrEmpty(info_message)) message = info_message;
  423. string taoToken = root.PathRead("data.taoToken", string.Empty);
  424. string shortLinkurl = root.PathRead("data.shortLinkurl", string.Empty);
  425. string couponLinkTaoToken = root.PathRead("data.couponLinkTaoToken", string.Empty);
  426. string couponShortLinkUrl = root.PathRead("data.couponShortLinkUrl", string.Empty);
  427. decimal couponAmount = root.PathRead<decimal>("data.couponAmount", 0);
  428. string couponEffectiveEndTime = root.PathRead("data.couponEffectiveEndTime", string.Empty);
  429. string couponEffectiveStartTime = root.PathRead("data.couponEffectiveStartTime", string.Empty);
  430. string itemId = root.PathRead("data.itemId", string.Empty);
  431. string itemName = root.PathRead("data.itemName", string.Empty);
  432. decimal promotionPrice = root.PathRead<decimal>("data.promotionPrice", 0);
  433. string sellerNickName = root.PathRead("data.sellerNickName", string.Empty);
  434. string shopTitle = root.PathRead("data.shopTitle", string.Empty);
  435. string pic = root.PathRead("data.pic", string.Empty);
  436. string qrCodeUrl = root.PathRead("data.qrCodeUrl", string.Empty);
  437. if (response.ResponseMessage != null)
  438. {
  439. switch (response.ResponseMessage.StatusCode)
  440. {
  441. case System.Net.HttpStatusCode.OK:
  442. {
  443. if (couponAmount > 0 && !string.IsNullOrEmpty(couponLinkTaoToken) && !string.IsNullOrEmpty(couponShortLinkUrl))
  444. {
  445. taoToken = couponLinkTaoToken;
  446. shortLinkurl = couponShortLinkUrl;
  447. }
  448. string shortLink = GetLink(taoToken);
  449. content = ReplaceUrls(content, shortLink);
  450. }
  451. break;
  452. case System.Net.HttpStatusCode.Found:
  453. string location = response.ResponseMessage.Headers.Location.OriginalString;
  454. if (!string.IsNullOrEmpty(location) && location.Contains("www.alimama.com/member/login.htm"))
  455. {
  456. success = false;
  457. message = "nologin";
  458. }
  459. break;
  460. default:
  461. {
  462. success = false;
  463. message = "other";
  464. }
  465. break;
  466. }
  467. }
  468. if (!success)
  469. {
  470. shortLinkurl = GetLink(content);
  471. switch (message)
  472. {
  473. case "该链接不支持转化,请更换链接尝试":
  474. case "网络错误":
  475. break;
  476. default:
  477. var _headers = response.ResponseMessage.Headers;
  478. var headers = "";
  479. foreach (var h in _headers)
  480. {
  481. foreach (var Value in h.Value)
  482. {
  483. headers += $"{h.Key}: {Value}\n";
  484. }
  485. }
  486. new LoggerLibrary("api_error", "fail")
  487. .Info(message, content)
  488. .Info(headers, body)
  489. .Save();
  490. break;
  491. }
  492. }
  493. string deeplink_url = GetDeeplink(shortLinkurl);
  494. result.channel = TkChannelEnum.tb;
  495. result.accountName = _accountName;
  496. result.link_type = success ? LinkTypeEnum.goods : result.link_type;
  497. result.success = success;
  498. result.message = message;
  499. result.content = content;
  500. result.couponAmount = couponAmount;
  501. result.couponEffectiveEndTime = couponEffectiveEndTime;
  502. result.couponEffectiveStartTime = couponEffectiveStartTime;
  503. result.taoToken = taoToken;
  504. result.shortLinkurl = shortLinkurl;
  505. result.deeplink_url = deeplink_url;
  506. result.itemId = itemId;
  507. result.itemName = itemName;
  508. result.promotionPrice = promotionPrice;
  509. result.sellerNickName = sellerNickName;
  510. result.shopTitle = shopTitle;
  511. result.pic = pic;
  512. result.qrCodeUrl = qrCodeUrl;
  513. }
  514. catch
  515. {
  516. if (response.ResponseMessage?.StatusCode == System.Net.HttpStatusCode.OK)
  517. {
  518. if (body.Contains("<p>抱歉!页面无法访问……</p>"))
  519. {
  520. throw new APIException("抱歉!页面无法访问……");
  521. }
  522. }
  523. throw;
  524. }
  525. return result;
  526. }
  527. }
  528. }