parse_2.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  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) && long.TryParse(itemId, out long _))
  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 mktId = root.PathRead("data.outputMktId", string.Empty);
  646. string itemName = root.PathRead("data.itemName", string.Empty);
  647. decimal promotionPrice = root.PathRead<decimal>("data.promotionPrice", 0);
  648. string sellerNickName = root.PathRead("data.sellerNickName", string.Empty);
  649. string shopTitle = root.PathRead("data.shopTitle", string.Empty);
  650. string pic = root.PathRead("data.pic", string.Empty);
  651. if (pic.StartsWith("//")) pic = "https:" + pic;
  652. string qrCodeUrl = root.PathRead("data.qrCodeUrl", string.Empty);
  653. if (response.ResponseMessage != null)
  654. {
  655. switch (response.ResponseMessage.StatusCode)
  656. {
  657. case System.Net.HttpStatusCode.OK:
  658. {
  659. if (couponAmount > 0 && !string.IsNullOrEmpty(couponLinkTaoToken) && !string.IsNullOrEmpty(couponShortLinkUrl))
  660. {
  661. taoToken = couponLinkTaoToken;
  662. shortLinkurl = couponShortLinkUrl;
  663. }
  664. string shortLink = GetLink(taoToken);
  665. content = ReplaceUrls(content, shortLink);
  666. }
  667. break;
  668. case System.Net.HttpStatusCode.Found:
  669. string location = response.ResponseMessage.Headers.Location.OriginalString;
  670. if (!string.IsNullOrEmpty(location) && location.Contains("www.alimama.com/member/login.htm"))
  671. {
  672. success = false;
  673. message = "nologin";
  674. }
  675. break;
  676. default:
  677. {
  678. success = false;
  679. message = "other";
  680. }
  681. break;
  682. }
  683. }
  684. if (!success)
  685. {
  686. shortLinkurl = GetLink(content);
  687. switch (message)
  688. {
  689. case "该商品已经下架或未加入淘宝客":
  690. case "该链接不支持转化,请更换链接尝试":
  691. result.subCode = TkSubCodeEnum.NoConvert;
  692. break;
  693. case "网络错误":
  694. result.subCode = TkSubCodeEnum.NetError;
  695. break;
  696. default:
  697. var _headers = response.ResponseMessage.Headers;
  698. var headers = "";
  699. foreach (var h in _headers)
  700. {
  701. foreach (var Value in h.Value)
  702. {
  703. headers += $"{h.Key}: {Value}\n";
  704. }
  705. }
  706. _ = new LoggerLibrary("api_error", "fail")
  707. .Info(message, content)
  708. .Info(headers, body)
  709. .SaveAsync();
  710. break;
  711. }
  712. }
  713. shortLinkurl = GetLink(taoToken);
  714. string deeplink_url = GetDeeplink(shortLinkurl);
  715. result.channel = TkChannelEnum.tb;
  716. if (success)
  717. {
  718. result.subCode = TkSubCodeEnum.Success;
  719. switch (result.link_type)
  720. {
  721. case LinkTypeEnum.profile:
  722. case LinkTypeEnum.goods:
  723. case LinkTypeEnum.video:
  724. case LinkTypeEnum.live:
  725. break;
  726. default:
  727. result.link_type = LinkTypeEnum.goods;
  728. break;
  729. }
  730. }
  731. result.success = success;
  732. result.message = message;
  733. result.reason = string.Empty;
  734. result.content = content;
  735. result.couponAmount = couponAmount;
  736. result.couponEffectiveEndTime = couponEffectiveEndTime;
  737. result.couponEffectiveStartTime = couponEffectiveStartTime;
  738. result.taoToken = taoToken;
  739. result.shortLinkurl = shortLinkurl;
  740. result.deeplink_url = deeplink_url;
  741. result.mktId = mktId;
  742. result.itemId = itemId;
  743. result.itemName = itemName;
  744. result.promotionPrice = promotionPrice;
  745. result.sellerNickName = sellerNickName;
  746. result.shopTitle = shopTitle;
  747. result.pic = pic;
  748. result.qrCodeUrl = qrCodeUrl;
  749. }
  750. catch (Exception ex)
  751. {
  752. if (response.ResponseMessage?.StatusCode == System.Net.HttpStatusCode.OK)
  753. {
  754. if (body.Contains("<p>抱歉!页面无法访问……</p>"))
  755. {
  756. throw new APIException("抱歉!页面无法访问……");
  757. }
  758. }
  759. throw;
  760. }
  761. return result;
  762. }
  763. private TkDataDTO alimamaParse(string content, TkDataDTO result)
  764. {
  765. string t = $"{DateTime.Now.Convert2UnixTimestamp(true)}";
  766. Random random = new();
  767. double randomNumber = random.NextDouble();
  768. string randomString = randomNumber.ToString()[2..];
  769. string cna = _cookies.GetContentPart("cna=", ";");
  770. string firstFiveCharacters = cna[..Math.Min(5, cna.Length)];
  771. var variableMap = new
  772. {
  773. url = content,
  774. union_lens = $"b_pvid:a219t._portal_v2_tool_links_page_home_index_htm_{t}_{randomString}_{firstFiveCharacters}",
  775. lensScene = "PUB",
  776. spmB = "_portal_v2_tool_links_page_home_index_htm"
  777. }.Convert2Json(true).UrlEncode();
  778. variableMap = variableMap.Replace(" ", "%20");
  779. string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/xt.entry.json?" +
  780. $"t={t}&_tb_token_={_tb_token}&floorId={_floorId}&refpid={_refpid}&variableMap={variableMap}";
  781. Stopwatch stopwatch = Stopwatch.StartNew();
  782. stopwatch.Start();
  783. var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
  784. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  785. .AddHeaders("Cookie", _cookies);
  786. client.Proxy = _proxy;
  787. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  788. #if DEBUG
  789. client.Proxy = null;
  790. url = "https://47.246.177.226/openapi/param2/1/gateway.unionpub/xt.entry.json?" +
  791. $"t={t}&_tb_token_={_tb_token}&floorId={_floorId}&refpid={_refpid}&variableMap={variableMap}";
  792. client.Headers["Host"] = "pub.alimama.com";
  793. #endif
  794. client.Timeout = GetRequestTimeout(result.elapsedTime2);
  795. //var response = client.Request(url);
  796. var response = client.Request(url);
  797. stopwatch.Stop();
  798. result.elapsedTime3 = (int)stopwatch.ElapsedMilliseconds;
  799. var body = string.Empty;
  800. try
  801. {
  802. if (!response.Successed)
  803. {
  804. result.channel = TkChannelEnum.tb;
  805. result.accountId = _accountId;
  806. result.accountName = _accountName;
  807. result.link_type = LinkTypeEnum.unknown;
  808. result.success = false;
  809. result.message = "fail";
  810. if (response.ResponseException != null)
  811. {
  812. _ = new LoggerLibrary("api_error", "fail")
  813. .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
  814. .SaveAsync();
  815. throw response.ResponseException;
  816. }
  817. return result;
  818. }
  819. body = response.Body();
  820. //{"code":601,"info":{"ok":false,"message":"nologin"}}
  821. JsonElement root = body.Convert2JsonElement();
  822. bool success = root.Read<bool>("success", false);
  823. string message = root.Read("message", string.Empty);
  824. string info_message = root.PathRead("info.message", string.Empty);
  825. if (!string.IsNullOrEmpty(info_message)) message = info_message;
  826. string taoToken = root.PathRead("data.taoToken", string.Empty);
  827. string shortLinkurl = root.PathRead("data.shortLinkurl", string.Empty);
  828. string couponLinkTaoToken = root.PathRead("data.couponLinkTaoToken", string.Empty);
  829. string couponShortLinkUrl = root.PathRead("data.couponShortLinkUrl", string.Empty);
  830. decimal couponAmount = root.PathRead<decimal>("data.couponAmount", 0);
  831. string couponEffectiveEndTime = root.PathRead("data.couponEffectiveEndTime", string.Empty);
  832. string couponEffectiveStartTime = root.PathRead("data.couponEffectiveStartTime", string.Empty);
  833. string itemId = root.PathRead("data.itemId", string.Empty);
  834. string itemName = root.PathRead("data.itemName", string.Empty);
  835. decimal promotionPrice = root.PathRead<decimal>("data.promotionPrice", 0);
  836. string sellerNickName = root.PathRead("data.sellerNickName", string.Empty);
  837. string shopTitle = root.PathRead("data.shopTitle", string.Empty);
  838. string pic = root.PathRead("data.pic", string.Empty);
  839. string qrCodeUrl = root.PathRead("data.qrCodeUrl", string.Empty);
  840. if (response.ResponseMessage != null)
  841. {
  842. switch (response.ResponseMessage.StatusCode)
  843. {
  844. case System.Net.HttpStatusCode.OK:
  845. {
  846. if (couponAmount > 0 && !string.IsNullOrEmpty(couponLinkTaoToken) && !string.IsNullOrEmpty(couponShortLinkUrl))
  847. {
  848. taoToken = couponLinkTaoToken;
  849. shortLinkurl = couponShortLinkUrl;
  850. }
  851. string shortLink = GetLink(taoToken);
  852. content = ReplaceUrls(content, shortLink);
  853. }
  854. break;
  855. case System.Net.HttpStatusCode.Found:
  856. string location = response.ResponseMessage.Headers.Location.OriginalString;
  857. if (!string.IsNullOrEmpty(location) && location.Contains("www.alimama.com/member/login.htm"))
  858. {
  859. success = false;
  860. message = "nologin";
  861. }
  862. break;
  863. default:
  864. {
  865. success = false;
  866. message = "other";
  867. }
  868. break;
  869. }
  870. }
  871. if (!success)
  872. {
  873. shortLinkurl = GetLink(content);
  874. switch (message)
  875. {
  876. case "该商品已经下架或未加入淘宝客":
  877. case "该链接不支持转化,请更换链接尝试":
  878. case "网络错误":
  879. break;
  880. default:
  881. var _headers = response.ResponseMessage.Headers;
  882. var headers = "";
  883. foreach (var h in _headers)
  884. {
  885. foreach (var Value in h.Value)
  886. {
  887. headers += $"{h.Key}: {Value}\n";
  888. }
  889. }
  890. _ = new LoggerLibrary("api_error", "fail")
  891. .Info(message, content)
  892. .Info(headers, body)
  893. .SaveAsync();
  894. break;
  895. }
  896. }
  897. if (success)
  898. {
  899. if (string.IsNullOrEmpty(itemName))
  900. {
  901. itemName = GetTitle(taoToken);
  902. }
  903. }
  904. else
  905. {
  906. itemName = GetTitle(content);
  907. }
  908. string deeplink_url = GetDeeplink(shortLinkurl);
  909. result.channel = TkChannelEnum.tb;
  910. result.accountId = _accountId;
  911. result.accountName = _accountName;
  912. if (success)
  913. {
  914. switch (result.link_type)
  915. {
  916. case LinkTypeEnum.profile:
  917. case LinkTypeEnum.goods:
  918. case LinkTypeEnum.video:
  919. case LinkTypeEnum.live:
  920. break;
  921. default:
  922. result.link_type = LinkTypeEnum.goods;
  923. break;
  924. }
  925. }
  926. result.success = success;
  927. result.message = message;
  928. result.content = content;
  929. result.couponAmount = couponAmount;
  930. result.couponEffectiveEndTime = couponEffectiveEndTime;
  931. result.couponEffectiveStartTime = couponEffectiveStartTime;
  932. result.taoToken = taoToken;
  933. result.shortLinkurl = shortLinkurl;
  934. result.deeplink_url = deeplink_url;
  935. result.itemId = itemId;
  936. result.itemName = itemName;
  937. result.promotionPrice = promotionPrice;
  938. result.sellerNickName = sellerNickName;
  939. result.shopTitle = shopTitle;
  940. result.pic = pic;
  941. result.qrCodeUrl = qrCodeUrl;
  942. }
  943. catch
  944. {
  945. if (response.ResponseMessage?.StatusCode == System.Net.HttpStatusCode.OK)
  946. {
  947. if (body.Contains("<p>抱歉!页面无法访问……</p>"))
  948. {
  949. throw new APIException("抱歉!页面无法访问……");
  950. }
  951. }
  952. throw;
  953. }
  954. return result;
  955. }
  956. }
  957. }