parse_2.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083
  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. using System;
  7. using MySqlX.XDevAPI;
  8. using static dodohold.core.ZTOExpress.CreateOrderArgs;
  9. using System.Threading;
  10. using TencentCloud.Tcm.V20210413.Models;
  11. using COSXML.Network;
  12. using System.Net;
  13. namespace molilian.core
  14. {
  15. public partial class AlimamaPlus
  16. {
  17. public static async Task<TkDataDTO> testTaskAsync(TkDataDTO result, CancellationToken token)
  18. {
  19. string url = "https://www.taobao.com";
  20. try
  21. {
  22. WebClientUtility client = new WebClientUtility();
  23. Thread.Sleep(5000);
  24. //await Task.Delay(5000, token); // 使用Task.Delay代替Thread.Sleep
  25. client.Timeout = TimeSpan.FromMilliseconds(3000);
  26. var response = await client.RequestAsync(url);
  27. var body = response.Body();
  28. }
  29. catch
  30. {
  31. result.success = false;
  32. result.message = "Error";
  33. }
  34. return result;
  35. }
  36. public void UnionParse2(string content, ref TkDataDTO result)
  37. {
  38. if ("veapi".Equals(_api) && _api_id > 0)
  39. {
  40. var account = VeapiPoolCore.Get(_api_id);
  41. if (account != null)
  42. {
  43. var core = new VeapiPlus(account.name, account.key, account.sessionKey);
  44. core.UnionParse(content, ref result);
  45. return;
  46. }
  47. }
  48. UnionParse(content, ref result);
  49. }
  50. public async Task<TkDataDTO> UnionParse2Async(string content, int commerceType, TkDataDTO result,
  51. CancellationToken cancellationToken = default,
  52. Dictionary<string, long> swData = null)
  53. {
  54. if ("veapi".Equals(_api) && _api_id > 0)
  55. {
  56. var account = VeapiPoolCore.Get(_api_id);
  57. if (account != null)
  58. {
  59. var core = new VeapiPlus(account.name, account.key, account.sessionKey);
  60. result = await core.UnionParseAsync(content, result, cancellationToken);
  61. return result;
  62. }
  63. }
  64. result = await UnionParseAsync(content, commerceType, result, cancellationToken, swData);
  65. return result;
  66. }
  67. /// <summary>
  68. /// 提取url里面的id参数
  69. /// </summary>
  70. /// <param name="url"></param>
  71. /// <returns></returns>
  72. public static string? ExtractItemId(string url)
  73. {
  74. Match match = Regex.Match(url, @"(?:\?|&)id=(\d+)");
  75. if (match.Success)
  76. {
  77. return match.Groups[1].Value;
  78. }
  79. return null;
  80. }
  81. /// <summary>
  82. /// 是否淘宝链接,如果是商品链接就格式化成https://item.taobao.com/item.htm?id=****
  83. /// </summary>
  84. /// <param name="url"></param>
  85. /// <returns></returns>
  86. private static (bool, string) IsTaobaoUrl(string url)
  87. {
  88. if (url.Contains("//a.m.taobao.com/i") ||
  89. url.Contains("//internal.tt.detail.taobao.com/i"))
  90. {
  91. //第一种提取方法
  92. string itemId = url.GetContentPart(".com/i", ".htm");
  93. if (!string.IsNullOrEmpty(itemId) && int.TryParse(itemId, out int _))
  94. {
  95. string resultUrl = $"https://item.taobao.com/item.htm?id={itemId}";
  96. return (true, resultUrl);
  97. }
  98. }
  99. //https://pages-g.m.taobao.com/wow/z/app/detail-next/item/index?x-ssr=true&id=753169018016
  100. if (url.Contains("//item.taobao.com/item.htm?") ||
  101. url.Contains("//pages-g.m.taobao.com/wow/z/app/detail-next/item/index?") ||
  102. url.Contains("//main.m.taobao.com/detail/index.html?") ||
  103. url.Contains("//h5.m.taobao.com/awp/core/detail.htm?") ||
  104. url.Contains("//new.m.taobao.com/detail.htm?") ||
  105. url.Contains("//outfliggys.m.taobao.com/app/trip/rx-travel-detail") ||
  106. url.Contains("//detail.m.tmall.com/item.htm?") ||
  107. url.Contains("//tmallx.tmall.com/app/tmallx-src/goods-detail") ||
  108. url.Contains("//detail.tmall.com/item.htm?") ||
  109. url.Contains("//internal.tt.detail.taobao.com/item.htm?") ||
  110. url.Contains("//internal.tt.detail.taobao.com/") ||
  111. url.Contains("//detail.tmall.hk/hk/item.htm?"))
  112. {
  113. string? itemId = ExtractItemId(url);
  114. if (!string.IsNullOrEmpty(itemId))
  115. {
  116. string resultUrl = $"https://item.taobao.com/item.htm?id={itemId}";
  117. return (true, resultUrl);
  118. }
  119. }
  120. return (false, url);
  121. }
  122. /// <summary>
  123. /// 排除已知的淘客链接
  124. /// </summary>
  125. /// <param name="url"></param>
  126. /// <returns></returns>
  127. public static bool IsAffLink(string url)
  128. {
  129. if (!url.StartsWith("https://") || !url.StartsWith("https://")) url = "https://" + url;
  130. Uri uri = new(url);
  131. if (uri.Host.Equals("s.click.taobao.com", StringComparison.OrdinalIgnoreCase) ||
  132. uri.Host.Equals("uland.taobao.com", StringComparison.OrdinalIgnoreCase))
  133. {
  134. return true;
  135. }
  136. return false;
  137. }
  138. /// <summary>
  139. /// 判断淘客的¥羊角符号
  140. /// </summary>
  141. /// <param name="content"></param>
  142. /// <returns></returns>
  143. static bool ContainsSpecialFormat(string content)
  144. {
  145. // 使用正则表达式匹配内容中是否含有特定格式的字符串
  146. //string pattern = @"¥[a-zA-Z0-9\s]+¥";
  147. string pattern = @"[$¥🗝₴€₤£₳✔《💰🔑🎵✔️💲🔐📲₡]+[a-zA-Z0-9\s]+[$¥🗝₴€₤£₳✔《💰🔑🎵✔️💲🔐📲₡]*";
  148. return Regex.IsMatch(content, pattern);
  149. }
  150. public TimeSpan GetRequestTimeout(int deduction = 0)
  151. {
  152. #if DEBUG
  153. return TimeSpan.FromMilliseconds(10 * 1000);
  154. #endif
  155. int min = (int)(_config.rt_max * 0.3);
  156. if (_config.rt_max == 0) return TimeSpan.FromMilliseconds(1000);
  157. int timeout = _config.rt_max;
  158. if (deduction == 0)
  159. {
  160. timeout -= min;
  161. return TimeSpan.FromMilliseconds(timeout);
  162. }
  163. timeout -= deduction;
  164. if (timeout <= min) return TimeSpan.FromMilliseconds(1);
  165. return TimeSpan.FromMilliseconds(min);
  166. }
  167. /// <summary>
  168. /// 从http获取跳转的url
  169. /// </summary>
  170. /// <param name="url"></param>
  171. /// <returns></returns>
  172. public async Task<(bool, string)> GetDesiredUrlAsync(WebProxy proxy, string url, CancellationToken cancellationToken = default)
  173. {
  174. string result;
  175. try
  176. {
  177. if (!url.Contains("m.tb.cn") &&
  178. !url.Contains("u.tb.cn") &&
  179. !url.Contains("e.tb.cn") &&
  180. !url.Contains("s.tb.cn"))
  181. return (false, "不是淘宝短网址");
  182. if (!_account.enable_deep_url) return (true, url);
  183. string desiredUrlPattern = "var url = '(.*?)'";
  184. WebClientUtility client = new()
  185. {
  186. Proxy = proxy,
  187. UserAgent = Sayaka.Common.ProviderFakeUserAgent.RandomComputer
  188. };
  189. if (url.Contains("u.tb.cn"))
  190. {
  191. client.AllowAutoRedirect = false;
  192. }
  193. url = url.Replace("http://u.tb.cn", "https://u.tb.cn");
  194. #if DEBUG
  195. client.Proxy = null;
  196. var response = await client.RequestAsync(url, "GET");
  197. #else
  198. client.Timeout = GetRequestTimeout(0);
  199. var response = await client.RequestAsync(url, "GET", cancellationToken);
  200. #endif
  201. if (response.ResponseMessage.StatusCode == HttpStatusCode.Found &&
  202. !string.IsNullOrEmpty(response.ResponseMessage?.Headers?.Location?.OriginalString))
  203. {
  204. string redirectUrl = response.ResponseMessage?.Headers?.Location?.OriginalString;
  205. return (true, redirectUrl);
  206. }
  207. var responseBody = response.Body();
  208. result = responseBody;
  209. if (response.Successed)
  210. {
  211. if (response.ResponseMessage.IsSuccessStatusCode)
  212. {
  213. Match match = Regex.Match(responseBody, desiredUrlPattern);
  214. if (match.Success)
  215. {
  216. result = match.Groups[1].Value; // 返回匹配的 URL
  217. if (string.IsNullOrEmpty(result)) return (false, "没有匹配的URL");
  218. if (result.StartsWith("//"))
  219. result = "https:" + result;
  220. return (true, result);
  221. }
  222. }
  223. else
  224. {
  225. result = $"{response.ResponseMessage.StatusCode}\n{responseBody}";
  226. }
  227. }
  228. else
  229. {
  230. throw response.ResponseException;
  231. }
  232. }
  233. catch (Exception ex)
  234. {
  235. _ = new LoggerLibrary("api_error", "desiredUrl_error").Info(ex.Message, ex.StackTrace).SaveAsync();
  236. result = "网络异常";
  237. }
  238. return (false, result);
  239. }
  240. /// <summary>
  241. /// 从http获取跳转的url
  242. /// </summary>
  243. /// <param name="url"></param>
  244. /// <returns></returns>
  245. (bool, string) GetDesiredUrl(string url)
  246. {
  247. string result;
  248. try
  249. {
  250. if (!url.Contains("m.tb.cn") && !url.Contains("e.tb.cn") && !url.Contains("s.tb.cn"))
  251. return (false, "不是淘宝短网址");
  252. string desiredUrlPattern = "var url = '(.*?)'";
  253. WebClientUtility client = new()
  254. {
  255. Proxy = ProxyNodesCore.RandomOne(_account.nodeName),
  256. UserAgent = Sayaka.Common.ProviderFakeUserAgent.RandomComputer
  257. };
  258. #if DEBUG
  259. client.Proxy = null;
  260. #endif
  261. client.Timeout = GetRequestTimeout(0);
  262. var response = client.Request(url);
  263. var responseBody = response.Body();
  264. result = responseBody;
  265. if (response.Successed)
  266. {
  267. if (response.ResponseMessage.IsSuccessStatusCode)
  268. {
  269. Match match = Regex.Match(responseBody, desiredUrlPattern);
  270. if (match.Success)
  271. {
  272. result = match.Groups[1].Value; // 返回匹配的 URL
  273. if (string.IsNullOrEmpty(result)) return (false, "没有匹配的URL");
  274. return (true, result);
  275. }
  276. }
  277. else
  278. {
  279. result = $"{response.ResponseMessage.StatusCode}\n{responseBody}";
  280. }
  281. }
  282. else
  283. {
  284. throw response.ResponseException;
  285. }
  286. }
  287. catch (Exception ex)
  288. {
  289. result = $"{ex.Message}\n{ex.StackTrace}";
  290. }
  291. return (false, result);
  292. }
  293. private void InternalTextProcessing(string content, ref TkDataDTO result)
  294. {
  295. //(result.success, result.content, result.link_type, result.shortLinkurl) = InternalTextProcessing(content,ref result);
  296. bool success;
  297. string resultText;
  298. LinkTypeEnum link_type = LinkTypeEnum.unknown;
  299. string url = GetLink(content);
  300. if (!string.IsNullOrEmpty(url))
  301. {
  302. //排除已知的淘客链接
  303. if (IsAffLink(url))
  304. {
  305. result.success = false;
  306. result.content = "排除淘客链接";
  307. result.link_type = LinkTypeEnum.other_aff;
  308. result.shortLinkurl = url;
  309. return;
  310. //return (false, "排除淘客链接", LinkTypeEnum.other_aff, url);
  311. }
  312. //直接提取
  313. (success, resultText) = IsTaobaoUrl(url);
  314. if (success)
  315. {
  316. result.success = true;
  317. result.content = resultText;
  318. result.link_type = LinkTypeEnum.goods;
  319. result.shortLinkurl = resultText;
  320. return;
  321. //return (true, result, LinkTypeEnum.goods, result);
  322. }
  323. //从http获取跳转的url
  324. Stopwatch stopwatch = Stopwatch.StartNew();
  325. stopwatch.Start();
  326. (success, resultText) = GetDesiredUrl(url);
  327. stopwatch.Stop();
  328. // 获取执行时间
  329. result.elapsedTime2 = (int)stopwatch.ElapsedMilliseconds;
  330. if (success)
  331. {
  332. //排除已知的淘客链接
  333. if (IsAffLink(resultText))
  334. {
  335. result.success = false;
  336. result.content = "排除淘客链接";
  337. result.link_type = LinkTypeEnum.other_aff;
  338. result.shortLinkurl = url;
  339. return;
  340. //return (false, "排除淘客链接", LinkTypeEnum.other_aff, url);
  341. }
  342. (success, resultText) = IsTaobaoUrl(resultText);
  343. if (success)
  344. {
  345. result.success = true;
  346. result.content = resultText;
  347. result.link_type = LinkTypeEnum.goods;
  348. result.shortLinkurl = resultText;
  349. return;
  350. //return (true, resultText, LinkTypeEnum.goods, resultText);
  351. }
  352. link_type = GetLinkType(resultText);
  353. }
  354. else
  355. {
  356. link_type = GetLinkType(url);
  357. }
  358. result.success = false;
  359. result.content = resultText;
  360. result.link_type = link_type;
  361. result.shortLinkurl = url;
  362. return;
  363. //return (false, result, link_type, url);
  364. }
  365. //判断淘客的¥羊角符号
  366. if (ContainsSpecialFormat(content))
  367. {
  368. result.success = false;
  369. result.content = "排除淘口令";
  370. result.link_type = LinkTypeEnum.other_aff;
  371. result.shortLinkurl = null;
  372. return;
  373. //return (false, "排除淘口令", LinkTypeEnum.other_aff, null);
  374. }
  375. //todo 临时应急 0614
  376. //return (false, "纯口令 没链接", link_type, null);
  377. result.success = false;
  378. result.content = "纯口令 没链接";
  379. result.link_type = LinkTypeEnum.other_aff;
  380. result.shortLinkurl = null;
  381. }
  382. public async Task<TkDataDTO> InternalTextProcessingAsync(string content, TkDataDTO result,
  383. CancellationToken cancellationToken = default,
  384. Dictionary<string, long> swData = null)
  385. {
  386. bool success;
  387. string resultText;
  388. result.link_type = LinkTypeEnum.unknown;
  389. //============================== 放弃转链-其他推广链接 ==============================
  390. string url = GetLink(content);
  391. if (!string.IsNullOrEmpty(url))
  392. {
  393. bool is_aff = IsAffLink(url);
  394. if (is_aff)
  395. {
  396. result.success = false;
  397. result.message = "放弃转链";
  398. result.reason = "其他推广链接";
  399. result.subCode = TkSubCodeEnum.OtherPromo;
  400. result.link_type = LinkTypeEnum.other_aff;
  401. result.shortLinkurl = url;
  402. return result;
  403. }
  404. (success, resultText) = IsTaobaoUrl(url);
  405. if (success)
  406. {
  407. result.success = true;
  408. result.content = resultText;
  409. result.link_type = LinkTypeEnum.goods;
  410. result.shortLinkurl = resultText;
  411. return result;
  412. }
  413. Stopwatch sw = Stopwatch.StartNew();
  414. var proxy = ProxyNodesCore.RandomOne(_account.nodeName);
  415. if (_proxy != null && proxy != null && _proxy.Address != proxy.Address)
  416. {
  417. result.proxy_node = proxy?.Address?.Authority;
  418. }
  419. (success, resultText) = await GetDesiredUrlAsync(proxy, url, cancellationToken);
  420. sw.Stop();
  421. // 获取执行时间
  422. result.elapsedTime2 = (int)sw.ElapsedMilliseconds;
  423. swData?.Add("\tGetDesiredUrlAsync", sw.ElapsedMilliseconds);
  424. //============================== 放弃转链-请求超时 ==============================
  425. #if DEBUG
  426. #else
  427. if (result.elapsedTime2 >= _config.rt_max || (!success && resultText.Contains("was canceled")))
  428. {
  429. result.success = false;
  430. result.message = "放弃转链";
  431. result.reason = "请求超时";
  432. result.subCode = TkSubCodeEnum.Other;
  433. return result;
  434. }
  435. #endif
  436. if (success)
  437. {
  438. string desiredUrl = resultText;
  439. //============================== 放弃转链-其他推广链接 ==============================
  440. bool is_aff2 = IsAffLink(desiredUrl);
  441. if (is_aff2)
  442. {
  443. result.success = false;
  444. result.message = "放弃转链";
  445. result.reason = "其他推广链接";
  446. result.subCode = TkSubCodeEnum.OtherPromo;
  447. result.link_type = LinkTypeEnum.other_aff;
  448. result.shortLinkurl = url;
  449. return result;
  450. }
  451. (success, desiredUrl) = IsTaobaoUrl(desiredUrl);
  452. if (success)
  453. {
  454. result.success = true;
  455. result.content = desiredUrl;
  456. result.link_type = LinkTypeEnum.goods;
  457. result.shortLinkurl = desiredUrl;
  458. return result;
  459. }
  460. result.link_type = GetLinkType(desiredUrl);
  461. }
  462. else
  463. {
  464. result.link_type = GetLinkType(url);
  465. if ("网络错误".Equals(resultText))
  466. {
  467. result.link_type = LinkTypeEnum.unknown;
  468. result.content = resultText;
  469. result.reason = resultText;
  470. }
  471. }
  472. if (result.content.Contains("霸下通用 web 页面-验证码"))
  473. {
  474. result.subCode = TkSubCodeEnum.Captcha;
  475. result.reason = "霸下验证码";
  476. }
  477. else
  478. {
  479. switch (result.link_type)
  480. {
  481. case LinkTypeEnum.profile:
  482. case LinkTypeEnum.live:
  483. case LinkTypeEnum.video:
  484. case LinkTypeEnum.note:
  485. case LinkTypeEnum.goods:
  486. case LinkTypeEnum.baseDomain:
  487. result.reason = string.Empty;
  488. result.content = content;
  489. break;
  490. default:
  491. result.reason = "非标准链接";
  492. result.subCode = TkSubCodeEnum.NonStdLink;
  493. break;
  494. }
  495. //if (result.link_type == LinkTypeEnum.baseDomain)
  496. //{
  497. // result.content = content;
  498. //}
  499. //else
  500. //{
  501. // result.reason = "非标准链接";
  502. // result.subCode = TkSubCodeEnum.NonStdLink;
  503. //}
  504. }
  505. result.success = false;
  506. result.message = "放弃转链";
  507. result.content = resultText;
  508. result.shortLinkurl = url;
  509. return result;
  510. //return (false, result, link_type, url);
  511. }
  512. //判断淘客的¥羊角符号
  513. bool is_aff3 = ContainsSpecialFormat(content);
  514. if (is_aff3)
  515. {
  516. result.success = false;
  517. result.message = "放弃转链";
  518. result.reason = "排除淘口令";
  519. result.subCode = TkSubCodeEnum.OtherPromo;
  520. result.link_type = LinkTypeEnum.other_aff;
  521. result.shortLinkurl = null;
  522. return result;
  523. //return (false, "排除淘口令", LinkTypeEnum.other_aff, null);
  524. }
  525. //todo 临时应急 0614
  526. //return (false, "纯口令 没链接", link_type, null);
  527. result.success = false;
  528. result.message = "放弃转链";
  529. result.reason = "纯口令 没链接";
  530. result.subCode = TkSubCodeEnum.OtherPromo;
  531. result.link_type = LinkTypeEnum.other_aff;
  532. result.shortLinkurl = null;
  533. return result;
  534. }
  535. private LinkTypeEnum GetLinkType(string url)
  536. {
  537. if (string.IsNullOrEmpty(url)) return LinkTypeEnum.unknown;
  538. if (url.Contains("m.tb.cn") || url.Contains("s.tb.cn") || url.Contains("e.tb.cn")) return LinkTypeEnum.baseDomain;
  539. if (url.StartsWith("https://huodong.m.taobao.com/act/talent/live.html")) return LinkTypeEnum.live;
  540. if (url.StartsWith("https://web.m.taobao.com/app/tnode/web/index")) return LinkTypeEnum.video;
  541. if (url.StartsWith("https://shop.m.taobao.com/shop/shopIndex.htm")) return LinkTypeEnum.profile;
  542. string pattern = @"^https://shop\d+(\.m)*\.taobao\.com";
  543. if (Regex.IsMatch(url, pattern))
  544. {
  545. return LinkTypeEnum.profile;
  546. }
  547. //https://shop.m.taobao.com/shop/shopIndex.htm?
  548. return LinkTypeEnum.unknown;
  549. }
  550. public async Task<TkDataDTO> alimamaParseAsync(string content, TkDataDTO result, CancellationToken cancellationToken = default)
  551. {
  552. string t = $"{DateTime.Now.Convert2UnixTimestamp(true)}";
  553. Random random = new();
  554. double randomNumber = random.NextDouble();
  555. string randomString = randomNumber.ToString()[2..];
  556. string cna = _cookies.GetContentPart("cna=", ";");
  557. string firstFiveCharacters = cna[..Math.Min(5, cna.Length)];
  558. var variableMap = new
  559. {
  560. url = content,
  561. union_lens = $"b_pvid:a219t._portal_v2_tool_links_page_home_index_htm_{t}_{randomString}_{firstFiveCharacters}",
  562. lensScene = "PUB",
  563. spmB = "_portal_v2_tool_links_page_home_index_htm"
  564. }.Convert2Json(true).UrlEncode();
  565. variableMap = variableMap.Replace(" ", "%20");
  566. string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/xt.entry.json?" +
  567. $"t={t}&_tb_token_={_tb_token}&floorId={_floorId}&refpid={_refpid}&variableMap={variableMap}";
  568. Stopwatch stopwatch = Stopwatch.StartNew();
  569. stopwatch.Start();
  570. var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
  571. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  572. .AddHeaders("Cookie", _cookies);
  573. client.Proxy = _proxy;
  574. #if DEBUG
  575. client.Proxy = null;
  576. #endif
  577. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  578. client.Timeout = GetRequestTimeout(result.elapsedTime2);
  579. //var response = client.Request(url);
  580. #if DEBUG
  581. var response = await client.RequestAsync(url, "GET");
  582. #else
  583. var response = await client.RequestAsync(url, "GET", cancellationToken);
  584. #endif
  585. stopwatch.Stop();
  586. result.elapsedTime3 = (int)stopwatch.ElapsedMilliseconds;
  587. var body = string.Empty;
  588. try
  589. {
  590. if (!response.Successed)
  591. {
  592. result.channel = TkChannelEnum.tb;
  593. result.link_type = LinkTypeEnum.unknown;
  594. result.success = false;
  595. result.message = "fail";
  596. if (response.ResponseException != null)
  597. {
  598. _ = new LoggerLibrary("api_error", "fail")
  599. .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
  600. .SaveAsync();
  601. throw response.ResponseException;
  602. }
  603. return result;
  604. }
  605. if (response.ResponseMessage.StatusCode == System.Net.HttpStatusCode.Found)
  606. {
  607. _ = new LoggerLibrary("api_error", "fail")
  608. .Info($"302:{response.ResponseMessage.Headers.Location}")
  609. .SaveAsync();
  610. throw new Exception("302 Found, was canceled");
  611. }
  612. JsonElement root;
  613. try
  614. {
  615. body = response.Body();
  616. root = body.Convert2JsonElement();
  617. }
  618. catch (Exception ex)
  619. {
  620. _ = new LoggerLibrary("api_error", "fail")
  621. .Info(ex.Message, ex.StackTrace)
  622. .SaveAsync();
  623. if (body.Contains("https://g.alicdn.com/sd/punish/waf_block.html"))
  624. {
  625. result.channel = TkChannelEnum.tb;
  626. result.link_type = LinkTypeEnum.unknown;
  627. result.success = false;
  628. result.message = "waf_block";
  629. return result;
  630. }
  631. throw new Exception(body);
  632. }
  633. bool success = root.Read<bool>("success", false);
  634. string message = root.Read("message", string.Empty);
  635. string info_message = root.PathRead("info.message", string.Empty);
  636. if (!string.IsNullOrEmpty(info_message)) message = info_message;
  637. string taoToken = root.PathRead("data.taoToken", string.Empty);
  638. string shortLinkurl = root.PathRead("data.shortLinkurl", string.Empty);
  639. string couponLinkTaoToken = root.PathRead("data.couponLinkTaoToken", string.Empty);
  640. string couponShortLinkUrl = root.PathRead("data.couponShortLinkUrl", string.Empty);
  641. decimal couponAmount = root.PathRead<decimal>("data.couponAmount", 0);
  642. string couponEffectiveEndTime = root.PathRead("data.couponEffectiveEndTime", string.Empty);
  643. string couponEffectiveStartTime = root.PathRead("data.couponEffectiveStartTime", string.Empty);
  644. string itemId = root.PathRead("data.itemId", string.Empty);
  645. string itemName = root.PathRead("data.itemName", string.Empty);
  646. decimal promotionPrice = root.PathRead<decimal>("data.promotionPrice", 0);
  647. string sellerNickName = root.PathRead("data.sellerNickName", string.Empty);
  648. string shopTitle = root.PathRead("data.shopTitle", string.Empty);
  649. string pic = root.PathRead("data.pic", string.Empty);
  650. if (pic.StartsWith("//")) pic = "https:" + pic;
  651. string qrCodeUrl = root.PathRead("data.qrCodeUrl", string.Empty);
  652. if (response.ResponseMessage != null)
  653. {
  654. switch (response.ResponseMessage.StatusCode)
  655. {
  656. case System.Net.HttpStatusCode.OK:
  657. {
  658. if (couponAmount > 0 && !string.IsNullOrEmpty(couponLinkTaoToken) && !string.IsNullOrEmpty(couponShortLinkUrl))
  659. {
  660. taoToken = couponLinkTaoToken;
  661. shortLinkurl = couponShortLinkUrl;
  662. }
  663. string shortLink = GetLink(taoToken);
  664. content = ReplaceUrls(content, shortLink);
  665. }
  666. break;
  667. case System.Net.HttpStatusCode.Found:
  668. string location = response.ResponseMessage.Headers.Location.OriginalString;
  669. if (!string.IsNullOrEmpty(location) && location.Contains("www.alimama.com/member/login.htm"))
  670. {
  671. success = false;
  672. message = "nologin";
  673. }
  674. break;
  675. default:
  676. {
  677. success = false;
  678. message = "other";
  679. }
  680. break;
  681. }
  682. }
  683. if (!success)
  684. {
  685. shortLinkurl = GetLink(content);
  686. switch (message)
  687. {
  688. case "该商品已经下架或未加入淘宝客":
  689. case "该链接不支持转化,请更换链接尝试":
  690. result.subCode = TkSubCodeEnum.NoConvert;
  691. break;
  692. case "网络错误":
  693. result.subCode = TkSubCodeEnum.NetError;
  694. break;
  695. default:
  696. var _headers = response.ResponseMessage.Headers;
  697. var headers = "";
  698. foreach (var h in _headers)
  699. {
  700. foreach (var Value in h.Value)
  701. {
  702. headers += $"{h.Key}: {Value}\n";
  703. }
  704. }
  705. _ = new LoggerLibrary("api_error", "fail")
  706. .Info(message, content)
  707. .Info(headers, body)
  708. .SaveAsync();
  709. break;
  710. }
  711. }
  712. shortLinkurl = GetLink(taoToken);
  713. string deeplink_url = GetDeeplink(shortLinkurl);
  714. result.channel = TkChannelEnum.tb;
  715. if (success)
  716. {
  717. result.subCode = TkSubCodeEnum.Success;
  718. switch (result.link_type)
  719. {
  720. case LinkTypeEnum.profile:
  721. case LinkTypeEnum.goods:
  722. case LinkTypeEnum.video:
  723. case LinkTypeEnum.live:
  724. break;
  725. default:
  726. result.link_type = LinkTypeEnum.goods;
  727. break;
  728. }
  729. }
  730. result.success = success;
  731. result.message = message;
  732. result.reason = string.Empty;
  733. result.content = content;
  734. result.couponAmount = couponAmount;
  735. result.couponEffectiveEndTime = couponEffectiveEndTime;
  736. result.couponEffectiveStartTime = couponEffectiveStartTime;
  737. result.taoToken = taoToken;
  738. result.shortLinkurl = shortLinkurl;
  739. result.deeplink_url = deeplink_url;
  740. result.itemId = itemId;
  741. result.itemName = itemName;
  742. result.promotionPrice = promotionPrice;
  743. result.sellerNickName = sellerNickName;
  744. result.shopTitle = shopTitle;
  745. result.pic = pic;
  746. result.qrCodeUrl = qrCodeUrl;
  747. }
  748. catch (Exception ex)
  749. {
  750. if (response.ResponseMessage?.StatusCode == System.Net.HttpStatusCode.OK)
  751. {
  752. if (body.Contains("<p>抱歉!页面无法访问……</p>"))
  753. {
  754. throw new APIException("抱歉!页面无法访问……");
  755. }
  756. }
  757. throw;
  758. }
  759. return result;
  760. }
  761. private TkDataDTO alimamaParse(string content, TkDataDTO result)
  762. {
  763. string t = $"{DateTime.Now.Convert2UnixTimestamp(true)}";
  764. Random random = new();
  765. double randomNumber = random.NextDouble();
  766. string randomString = randomNumber.ToString()[2..];
  767. string cna = _cookies.GetContentPart("cna=", ";");
  768. string firstFiveCharacters = cna[..Math.Min(5, cna.Length)];
  769. var variableMap = new
  770. {
  771. url = content,
  772. union_lens = $"b_pvid:a219t._portal_v2_tool_links_page_home_index_htm_{t}_{randomString}_{firstFiveCharacters}",
  773. lensScene = "PUB",
  774. spmB = "_portal_v2_tool_links_page_home_index_htm"
  775. }.Convert2Json(true).UrlEncode();
  776. variableMap = variableMap.Replace(" ", "%20");
  777. string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/xt.entry.json?" +
  778. $"t={t}&_tb_token_={_tb_token}&floorId={_floorId}&refpid={_refpid}&variableMap={variableMap}";
  779. Stopwatch stopwatch = Stopwatch.StartNew();
  780. stopwatch.Start();
  781. var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
  782. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  783. .AddHeaders("Cookie", _cookies);
  784. client.Proxy = _proxy;
  785. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  786. #if DEBUG
  787. client.Proxy = null;
  788. url = "https://47.246.177.226/openapi/param2/1/gateway.unionpub/xt.entry.json?" +
  789. $"t={t}&_tb_token_={_tb_token}&floorId={_floorId}&refpid={_refpid}&variableMap={variableMap}";
  790. client.Headers["Host"] = "pub.alimama.com";
  791. #endif
  792. client.Timeout = GetRequestTimeout(result.elapsedTime2);
  793. //var response = client.Request(url);
  794. var response = client.Request(url);
  795. stopwatch.Stop();
  796. result.elapsedTime3 = (int)stopwatch.ElapsedMilliseconds;
  797. var body = string.Empty;
  798. try
  799. {
  800. if (!response.Successed)
  801. {
  802. result.channel = TkChannelEnum.tb;
  803. result.accountId = _accountId;
  804. result.accountName = _accountName;
  805. result.link_type = LinkTypeEnum.unknown;
  806. result.success = false;
  807. result.message = "fail";
  808. if (response.ResponseException != null)
  809. {
  810. _ = new LoggerLibrary("api_error", "fail")
  811. .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
  812. .SaveAsync();
  813. throw response.ResponseException;
  814. }
  815. return result;
  816. }
  817. body = response.Body();
  818. //{"code":601,"info":{"ok":false,"message":"nologin"}}
  819. JsonElement root = body.Convert2JsonElement();
  820. bool success = root.Read<bool>("success", false);
  821. string message = root.Read("message", string.Empty);
  822. string info_message = root.PathRead("info.message", string.Empty);
  823. if (!string.IsNullOrEmpty(info_message)) message = info_message;
  824. string taoToken = root.PathRead("data.taoToken", string.Empty);
  825. string shortLinkurl = root.PathRead("data.shortLinkurl", string.Empty);
  826. string couponLinkTaoToken = root.PathRead("data.couponLinkTaoToken", string.Empty);
  827. string couponShortLinkUrl = root.PathRead("data.couponShortLinkUrl", string.Empty);
  828. decimal couponAmount = root.PathRead<decimal>("data.couponAmount", 0);
  829. string couponEffectiveEndTime = root.PathRead("data.couponEffectiveEndTime", string.Empty);
  830. string couponEffectiveStartTime = root.PathRead("data.couponEffectiveStartTime", string.Empty);
  831. string itemId = root.PathRead("data.itemId", string.Empty);
  832. string itemName = root.PathRead("data.itemName", string.Empty);
  833. decimal promotionPrice = root.PathRead<decimal>("data.promotionPrice", 0);
  834. string sellerNickName = root.PathRead("data.sellerNickName", string.Empty);
  835. string shopTitle = root.PathRead("data.shopTitle", string.Empty);
  836. string pic = root.PathRead("data.pic", string.Empty);
  837. string qrCodeUrl = root.PathRead("data.qrCodeUrl", string.Empty);
  838. if (response.ResponseMessage != null)
  839. {
  840. switch (response.ResponseMessage.StatusCode)
  841. {
  842. case System.Net.HttpStatusCode.OK:
  843. {
  844. if (couponAmount > 0 && !string.IsNullOrEmpty(couponLinkTaoToken) && !string.IsNullOrEmpty(couponShortLinkUrl))
  845. {
  846. taoToken = couponLinkTaoToken;
  847. shortLinkurl = couponShortLinkUrl;
  848. }
  849. string shortLink = GetLink(taoToken);
  850. content = ReplaceUrls(content, shortLink);
  851. }
  852. break;
  853. case System.Net.HttpStatusCode.Found:
  854. string location = response.ResponseMessage.Headers.Location.OriginalString;
  855. if (!string.IsNullOrEmpty(location) && location.Contains("www.alimama.com/member/login.htm"))
  856. {
  857. success = false;
  858. message = "nologin";
  859. }
  860. break;
  861. default:
  862. {
  863. success = false;
  864. message = "other";
  865. }
  866. break;
  867. }
  868. }
  869. if (!success)
  870. {
  871. shortLinkurl = GetLink(content);
  872. switch (message)
  873. {
  874. case "该商品已经下架或未加入淘宝客":
  875. case "该链接不支持转化,请更换链接尝试":
  876. case "网络错误":
  877. break;
  878. default:
  879. var _headers = response.ResponseMessage.Headers;
  880. var headers = "";
  881. foreach (var h in _headers)
  882. {
  883. foreach (var Value in h.Value)
  884. {
  885. headers += $"{h.Key}: {Value}\n";
  886. }
  887. }
  888. _ = new LoggerLibrary("api_error", "fail")
  889. .Info(message, content)
  890. .Info(headers, body)
  891. .SaveAsync();
  892. break;
  893. }
  894. }
  895. if (success)
  896. {
  897. if (string.IsNullOrEmpty(itemName))
  898. {
  899. itemName = GetTitle(taoToken);
  900. }
  901. }
  902. else
  903. {
  904. itemName = GetTitle(content);
  905. }
  906. string deeplink_url = GetDeeplink(shortLinkurl);
  907. result.channel = TkChannelEnum.tb;
  908. result.accountId = _accountId;
  909. result.accountName = _accountName;
  910. if (success)
  911. {
  912. switch (result.link_type)
  913. {
  914. case LinkTypeEnum.profile:
  915. case LinkTypeEnum.goods:
  916. case LinkTypeEnum.video:
  917. case LinkTypeEnum.live:
  918. break;
  919. default:
  920. result.link_type = LinkTypeEnum.goods;
  921. break;
  922. }
  923. }
  924. result.success = success;
  925. result.message = message;
  926. result.content = content;
  927. result.couponAmount = couponAmount;
  928. result.couponEffectiveEndTime = couponEffectiveEndTime;
  929. result.couponEffectiveStartTime = couponEffectiveStartTime;
  930. result.taoToken = taoToken;
  931. result.shortLinkurl = shortLinkurl;
  932. result.deeplink_url = deeplink_url;
  933. result.itemId = itemId;
  934. result.itemName = itemName;
  935. result.promotionPrice = promotionPrice;
  936. result.sellerNickName = sellerNickName;
  937. result.shopTitle = shopTitle;
  938. result.pic = pic;
  939. result.qrCodeUrl = qrCodeUrl;
  940. }
  941. catch
  942. {
  943. if (response.ResponseMessage?.StatusCode == System.Net.HttpStatusCode.OK)
  944. {
  945. if (body.Contains("<p>抱歉!页面无法访问……</p>"))
  946. {
  947. throw new APIException("抱歉!页面无法访问……");
  948. }
  949. }
  950. throw;
  951. }
  952. return result;
  953. }
  954. }
  955. }