parse_2.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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. namespace molilian.core
  9. {
  10. public partial class AlimamaPlus
  11. {
  12. public void UnionParse2(string content, ref TkDataDTO result)
  13. {
  14. if ("veapi".Equals(_api) && _api_id > 0)
  15. {
  16. var account = VeapiPoolCore.Get(_api_id);
  17. if (account != null)
  18. {
  19. var core = new VeapiPlus(account.name, account.key, account.sessionKey);
  20. core.UnionParse(content, ref result);
  21. return;
  22. }
  23. }
  24. UnionParse(content, ref result);
  25. }
  26. public async Task<TkDataDTO> UnionParse2Async(string content, TkDataDTO result)
  27. {
  28. if ("veapi".Equals(_api) && _api_id > 0)
  29. {
  30. var account = VeapiPoolCore.Get(_api_id);
  31. if (account != null)
  32. {
  33. var core = new VeapiPlus(account.name, account.key, account.sessionKey);
  34. result = await core.UnionParseAsync(content, result);
  35. return result;
  36. }
  37. }
  38. result = await UnionParseAsync(content, result);
  39. return result;
  40. }
  41. /// <summary>
  42. /// 提取url里面的id参数
  43. /// </summary>
  44. /// <param name="url"></param>
  45. /// <returns></returns>
  46. static string? ExtractItemId(string url)
  47. {
  48. Match match = Regex.Match(url, @"(?:\?|&)id=(\d+)");
  49. if (match.Success)
  50. {
  51. return match.Groups[1].Value;
  52. }
  53. return null;
  54. }
  55. /// <summary>
  56. /// 是否淘宝链接
  57. /// </summary>
  58. /// <param name="url"></param>
  59. /// <returns></returns>
  60. private static (bool, string) IsTaobaoUrl(string url)
  61. {
  62. if (url.Contains("//a.m.taobao.com/i"))
  63. {
  64. //第一种提取方法
  65. string itemId = url.GetContentPart("//a.m.taobao.com/i", ".htm");
  66. if (!string.IsNullOrEmpty(itemId))
  67. {
  68. string resultUrl = $"https://item.taobao.com/item.htm?id={itemId}";
  69. return (true, resultUrl);
  70. }
  71. }
  72. if (url.Contains("//item.taobao.com/item.htm?") ||
  73. url.Contains("//h5.m.taobao.com/awp/core/detail.htm?") ||
  74. url.Contains("//new.m.taobao.com/detail.htm?") ||
  75. url.Contains("//outfliggys.m.taobao.com/app/trip/rx-travel-detail") ||
  76. url.Contains("//detail.m.tmall.com/item.htm?") ||
  77. url.Contains("//tmallx.tmall.com/app/tmallx-src/goods-detail") ||
  78. url.Contains("//detail.tmall.com/item.htm?") ||
  79. url.Contains("//detail.tmall.hk/hk/item.htm?"))
  80. {
  81. string? itemId = ExtractItemId(url);
  82. if (!string.IsNullOrEmpty(itemId))
  83. {
  84. string resultUrl = $"https://item.taobao.com/item.htm?id={itemId}";
  85. return (true, resultUrl);
  86. }
  87. }
  88. return (false, url);
  89. }
  90. /// <summary>
  91. /// 排除已知的淘客链接
  92. /// </summary>
  93. /// <param name="url"></param>
  94. /// <returns></returns>
  95. static bool IsAffLink(string url)
  96. {
  97. if (!url.StartsWith("https://") || !url.StartsWith("https://")) url = "https://" + url;
  98. Uri uri = new(url);
  99. if (uri.Host.Equals("s.click.taobao.com", StringComparison.OrdinalIgnoreCase) ||
  100. uri.Host.Equals("uland.taobao.com", StringComparison.OrdinalIgnoreCase))
  101. {
  102. return true;
  103. }
  104. //if (uri.Host.Equals("m.tb.cn", StringComparison.OrdinalIgnoreCase) &&
  105. // uri.AbsolutePath.StartsWith("/h.") &&
  106. // string.IsNullOrEmpty(uri.Query) && // No query parameters
  107. // !url.Contains("?tk=")) // No "tk" parameter
  108. //{
  109. // return true;
  110. //}
  111. return false;
  112. }
  113. /// <summary>
  114. /// 判断淘客的¥羊角符号
  115. /// </summary>
  116. /// <param name="content"></param>
  117. /// <returns></returns>
  118. static bool ContainsSpecialFormat(string content)
  119. {
  120. // 使用正则表达式匹配内容中是否含有特定格式的字符串
  121. //string pattern = @"¥[a-zA-Z0-9\s]+¥";
  122. string pattern = @"[$¥🗝₴€₤£₳✔《💰🔑🎵✔️💲🔐📲₡]+[a-zA-Z0-9\s]+[$¥🗝₴€₤£₳✔《💰🔑🎵✔️💲🔐📲₡]*";
  123. return Regex.IsMatch(content, pattern);
  124. }
  125. public TimeSpan GetRequestTimeout(int deduction = 0)
  126. {
  127. #if DEBUG
  128. return TimeSpan.FromMilliseconds(10 * 1000);
  129. #endif
  130. if (_config.rt_max == 0) return TimeSpan.FromMilliseconds(1000);
  131. int timeout = _config.rt_max;
  132. if (deduction == 0) return TimeSpan.FromMilliseconds(timeout);
  133. timeout = timeout - deduction;
  134. if (timeout < 0) return TimeSpan.FromMilliseconds(200);
  135. return TimeSpan.FromMilliseconds(timeout);
  136. }
  137. /// <summary>
  138. /// 从http获取跳转的url
  139. /// </summary>
  140. /// <param name="url"></param>
  141. /// <returns></returns>
  142. (bool, string) GetDesiredUrl(string url)
  143. {
  144. string result;
  145. try
  146. {
  147. Uri uri = new(url);
  148. if (!uri.Host.Equals("m.tb.cn", StringComparison.OrdinalIgnoreCase)) return (false, "不是淘宝短网址");
  149. string desiredUrlPattern = "var url = '(.*?)'";
  150. WebClientUtility client = new()
  151. {
  152. Proxy = _proxy,
  153. UserAgent = Sayaka.Common.ProviderFakeUserAgent.RandomComputer
  154. };
  155. #if DEBUG
  156. client.Proxy = null;
  157. #endif
  158. client.Timeout = GetRequestTimeout(0);
  159. var response = client.Request(url);
  160. var responseBody = response.Body();
  161. result = responseBody;
  162. if (response.Successed)
  163. {
  164. if (response.ResponseMessage.IsSuccessStatusCode)
  165. {
  166. Match match = Regex.Match(responseBody, desiredUrlPattern);
  167. if (match.Success)
  168. {
  169. result = match.Groups[1].Value; // 返回匹配的 URL
  170. if (string.IsNullOrEmpty(result)) return (false, "没有匹配的URL");
  171. return (true, result);
  172. }
  173. }
  174. else
  175. {
  176. result = $"{response.ResponseMessage.StatusCode}\n{responseBody}";
  177. }
  178. }
  179. else
  180. {
  181. throw response.ResponseException;
  182. }
  183. }
  184. catch (Exception ex)
  185. {
  186. result = $"{ex.Message}\n{ex.StackTrace}";
  187. }
  188. return (false, result);
  189. }
  190. private void InternalTextProcessing(string content, ref TkDataDTO result)
  191. {
  192. //(result.success, result.content, result.link_type, result.shortLinkurl) = InternalTextProcessing(content,ref result);
  193. bool success;
  194. string resultText;
  195. LinkTypeEnum link_type = LinkTypeEnum.unknown;
  196. string url = GetLink(content);
  197. if (!string.IsNullOrEmpty(url))
  198. {
  199. //排除已知的淘客链接
  200. if (IsAffLink(url))
  201. {
  202. result.success = false;
  203. result.content = "排除淘客链接";
  204. result.link_type = LinkTypeEnum.other_aff;
  205. result.shortLinkurl = url;
  206. return;
  207. //return (false, "排除淘客链接", LinkTypeEnum.other_aff, url);
  208. }
  209. //直接提取
  210. (success, resultText) = IsTaobaoUrl(url);
  211. if (success)
  212. {
  213. result.success = true;
  214. result.content = resultText;
  215. result.link_type = LinkTypeEnum.goods;
  216. result.shortLinkurl = resultText;
  217. return;
  218. //return (true, result, LinkTypeEnum.goods, result);
  219. }
  220. //从http获取跳转的url
  221. Stopwatch stopwatch = Stopwatch.StartNew();
  222. stopwatch.Start();
  223. (success, resultText) = GetDesiredUrl(url);
  224. stopwatch.Stop();
  225. // 获取执行时间
  226. result.elapsedTime2 = (int)stopwatch.ElapsedMilliseconds;
  227. if (success)
  228. {
  229. //排除已知的淘客链接
  230. if (IsAffLink(resultText))
  231. {
  232. result.success = false;
  233. result.content = "排除淘客链接";
  234. result.link_type = LinkTypeEnum.other_aff;
  235. result.shortLinkurl = url;
  236. return;
  237. //return (false, "排除淘客链接", LinkTypeEnum.other_aff, url);
  238. }
  239. (success, resultText) = IsTaobaoUrl(resultText);
  240. if (success)
  241. {
  242. result.success = true;
  243. result.content = resultText;
  244. result.link_type = LinkTypeEnum.goods;
  245. result.shortLinkurl = resultText;
  246. return;
  247. //return (true, resultText, LinkTypeEnum.goods, resultText);
  248. }
  249. link_type = GetLinkType(resultText);
  250. }
  251. else
  252. {
  253. link_type = GetLinkType(url);
  254. }
  255. result.success = false;
  256. result.content = resultText;
  257. result.link_type = link_type;
  258. result.shortLinkurl = url;
  259. return;
  260. //return (false, result, link_type, url);
  261. }
  262. //判断淘客的¥羊角符号
  263. if (ContainsSpecialFormat(content))
  264. {
  265. result.success = false;
  266. result.content = "排除淘口令";
  267. result.link_type = LinkTypeEnum.other_aff;
  268. result.shortLinkurl = null;
  269. return;
  270. //return (false, "排除淘口令", LinkTypeEnum.other_aff, null);
  271. }
  272. //todo 临时应急 0614
  273. //return (false, "纯口令 没链接", link_type, null);
  274. result.success = false;
  275. result.content = "纯口令 没链接";
  276. result.link_type = LinkTypeEnum.other_aff;
  277. result.shortLinkurl = null;
  278. }
  279. private (bool, string, LinkTypeEnum, string) InternalTextProcessing222(string content)
  280. {
  281. bool success;
  282. string result;
  283. LinkTypeEnum link_type = LinkTypeEnum.unknown;
  284. string url = GetLink(content);
  285. if (!string.IsNullOrEmpty(url))
  286. {
  287. //排除已知的淘客链接
  288. if (IsAffLink(url)) return (false, "排除淘客链接", LinkTypeEnum.other_aff, url);
  289. //直接提取
  290. (success, result) = IsTaobaoUrl(url);
  291. if (success) return (true, result, LinkTypeEnum.goods, result);
  292. //https://uland.taobao.com/coupon/edetail?af=4&e=%2B0aTAvEt16MoRnbUfHBdCarU9683KT3AsB67n92UtFJMmdsrkidbOWBzzpT26idJbwZX%2BHY%2B8QD9zJXNeOSc1euXSPKeLUBBWr02LqsxPV8Bf6pSMNy5GSw6iqMObXLLk3toOSlQXmUUcLJJYP0Uq5lvDADUDTeHRiuxU0i9W%2BtrC8Oh6piEfdwyUIuKQbeM8rUgQejRG616MoRnbUfHBdCarU9683KT3AsB67n92UtFv6uIFQszbmWWPZ8ka7%2BkV5xXydLt%2FcnuZ4%2BBFYnwwiUaCWC3TckcCwMW8xe3XqOGsb8uv9wbhxdkKJ0hxTrTkj7DNgliTXDluAYBRglsbQ%3D%3D&traceId=212cbaa417178512249145009e05a8&union_lens=lensId%3APUB%401717851219%402103c04a_0c89_18ff7e96612_9d39%40031w5YJSc7jl3U7gYjdvuCMM%40eyJmbG9vcklkIjo4NTAvEt16MoRnbUfHBdCarU9683JDaxNfPy83okP3kLScwCkGiuMcyC4PcynGV0YWlsX2h0bSIsInNyY0Zsb29ySWQiiOiiI4MDY3NCIsImNyZWF0aXZpdHlHcm91cElkIjowfQieie%3BtkScm%3AselectionPlaza_site_4358%3Bscm%3A1007.30148.329090.pub_search-item_c02df4bb-631f-4cc1-a9d5-abe802b8e134_&un=bfc196d23e155d289f2917200ca32a93&share_crt_v=1&un_site=0&ut_sk=1.utdid_null_1717851225204.TaoPassword-Outside.lianmeng-app&spm=a2159r.13376465.0.0&sp_tk=d2hLeFdDNHpKb3Y%3D&cpp=1&shareurl=true&short_name=h.gVx6mvI
  293. //从http获取跳转的url
  294. (success, result) = GetDesiredUrl(url);
  295. if (success)
  296. {
  297. //排除已知的淘客链接
  298. if (IsAffLink(result)) return (false, "排除淘客链接", LinkTypeEnum.other_aff, url);
  299. (success, result) = IsTaobaoUrl(result);
  300. if (success) return (true, result, LinkTypeEnum.goods, result);
  301. link_type = GetLinkType(result);
  302. }
  303. else
  304. {
  305. link_type = GetLinkType(url);
  306. }
  307. return (false, result, link_type, url);
  308. }
  309. //判断淘客的¥羊角符号
  310. if (ContainsSpecialFormat(content)) return (false, "排除淘口令", LinkTypeEnum.other_aff, null);
  311. //todo 临时应急 0614
  312. //return (false, "纯口令 没链接", link_type, null);
  313. return (false, "纯口令 没链接", LinkTypeEnum.other_aff, null);
  314. }
  315. private LinkTypeEnum GetLinkType(string url)
  316. {
  317. if (string.IsNullOrEmpty(url)) return LinkTypeEnum.unknown;
  318. if (url.StartsWith("https://huodong.m.taobao.com/act/talent/live.html")) return LinkTypeEnum.live;
  319. if (url.StartsWith("https://web.m.taobao.com/app/tnode/web/index")) return LinkTypeEnum.video;
  320. string pattern = @"^https://shop\d+\.m\.taobao\.com";
  321. if (Regex.IsMatch(url, pattern))
  322. {
  323. return LinkTypeEnum.profile;
  324. }
  325. return LinkTypeEnum.unknown;
  326. }
  327. private void alimamaParse(string content, ref TkDataDTO result)
  328. {
  329. string t = $"{DateTime.Now.Convert2UnixTimestamp(true)}";
  330. Random random = new();
  331. double randomNumber = random.NextDouble();
  332. string randomString = randomNumber.ToString()[2..];
  333. string cna = _cookies.GetContentPart("cna=", ";");
  334. string firstFiveCharacters = cna[..Math.Min(5, cna.Length)];
  335. var variableMap = new
  336. {
  337. url = content,
  338. union_lens = $"b_pvid:a219t._portal_v2_tool_links_page_home_index_htm_{t}_{randomString}_{firstFiveCharacters}",
  339. lensScene = "PUB",
  340. spmB = "_portal_v2_tool_links_page_home_index_htm"
  341. }.Convert2Json(true).UrlEncode();
  342. variableMap = variableMap.Replace(" ", "%20");
  343. string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/xt.entry.json?" +
  344. $"t={t}&_tb_token_={_tb_token}&floorId={_floorId}&refpid={_refpid}&variableMap={variableMap}";
  345. var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
  346. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  347. .AddHeaders("Cookie", _cookies);
  348. client.Proxy = _proxy;
  349. #if DEBUG
  350. client.Proxy = null;
  351. #endif
  352. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  353. client.Timeout = GetRequestTimeout(result.elapsedTime2);
  354. var response = client.Request(url);
  355. var body = string.Empty;
  356. try
  357. {
  358. if (!response.Successed)
  359. {
  360. result.channel = TkChannelEnum.tb;
  361. result.accountId = _accountId;
  362. result.accountName = _accountName;
  363. result.link_type = LinkTypeEnum.unknown;
  364. result.success = false;
  365. result.message = "fail";
  366. if (response.ResponseException != null)
  367. {
  368. _ = new LoggerLibrary("api_error", "fail")
  369. .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
  370. .SaveAsync();
  371. throw response.ResponseException;
  372. }
  373. return;
  374. }
  375. body = response.Body();
  376. JsonElement root = body.Convert2JsonElement();
  377. bool success = root.Read<bool>("success", false);
  378. string message = root.Read("message", string.Empty);
  379. string info_message = root.PathRead("info.message", string.Empty);
  380. if (!string.IsNullOrEmpty(info_message)) message = info_message;
  381. string taoToken = root.PathRead("data.taoToken", string.Empty);
  382. string shortLinkurl = root.PathRead("data.shortLinkurl", string.Empty);
  383. string couponLinkTaoToken = root.PathRead("data.couponLinkTaoToken", string.Empty);
  384. string couponShortLinkUrl = root.PathRead("data.couponShortLinkUrl", string.Empty);
  385. decimal couponAmount = root.PathRead<decimal>("data.couponAmount", 0);
  386. string itemId = root.PathRead("data.itemId", string.Empty);
  387. string itemName = root.PathRead("data.itemName", string.Empty);
  388. decimal promotionPrice = root.PathRead<decimal>("data.promotionPrice", 0);
  389. string sellerNickName = root.PathRead("data.sellerNickName", string.Empty);
  390. string shopTitle = root.PathRead("data.shopTitle", string.Empty);
  391. string pic = root.PathRead("data.pic", string.Empty);
  392. string qrCodeUrl = root.PathRead("data.qrCodeUrl", string.Empty);
  393. if (response.ResponseMessage != null)
  394. {
  395. switch (response.ResponseMessage.StatusCode)
  396. {
  397. case System.Net.HttpStatusCode.OK:
  398. {
  399. if (couponAmount > 0 && !string.IsNullOrEmpty(couponLinkTaoToken) && !string.IsNullOrEmpty(couponShortLinkUrl))
  400. {
  401. taoToken = couponLinkTaoToken;
  402. shortLinkurl = couponShortLinkUrl;
  403. }
  404. string shortLink = GetLink(taoToken);
  405. content = ReplaceUrls(content, shortLink);
  406. }
  407. break;
  408. case System.Net.HttpStatusCode.Found:
  409. string location = response.ResponseMessage.Headers.Location.OriginalString;
  410. if (!string.IsNullOrEmpty(location) && location.Contains("www.alimama.com/member/login.htm"))
  411. {
  412. success = false;
  413. message = "nologin";
  414. }
  415. break;
  416. default:
  417. {
  418. success = false;
  419. message = "other";
  420. }
  421. break;
  422. }
  423. }
  424. if (!success)
  425. {
  426. shortLinkurl = GetLink(content);
  427. switch (message)
  428. {
  429. case "该链接不支持转化,请更换链接尝试":
  430. case "网络错误":
  431. break;
  432. default:
  433. var _headers = response.ResponseMessage.Headers;
  434. var headers = "";
  435. foreach (var h in _headers)
  436. {
  437. foreach (var Value in h.Value)
  438. {
  439. headers += $"{h.Key}: {Value}\n";
  440. }
  441. }
  442. _ = new LoggerLibrary("api_error", "fail")
  443. .Info(message, content)
  444. .Info(headers, body)
  445. .SaveAsync();
  446. break;
  447. }
  448. }
  449. string deeplink_url = GetDeeplink(shortLinkurl);
  450. result.channel = TkChannelEnum.tb;
  451. result.accountId = _accountId;
  452. result.accountName = _accountName;
  453. result.link_type = success ? LinkTypeEnum.goods : result.link_type;
  454. result.success = success;
  455. result.message = message;
  456. result.content = content;
  457. result.couponAmount = couponAmount;
  458. result.taoToken = taoToken;
  459. result.shortLinkurl = shortLinkurl;
  460. result.deeplink_url = deeplink_url;
  461. result.itemId = itemId;
  462. result.itemName = itemName;
  463. result.promotionPrice = promotionPrice;
  464. result.sellerNickName = sellerNickName;
  465. result.shopTitle = shopTitle;
  466. result.pic = pic;
  467. result.qrCodeUrl = qrCodeUrl;
  468. }
  469. catch
  470. {
  471. if (response.ResponseMessage?.StatusCode == System.Net.HttpStatusCode.OK)
  472. {
  473. if (body.Contains("<p>抱歉!页面无法访问……</p>"))
  474. {
  475. throw new APIException("抱歉!页面无法访问……");
  476. }
  477. }
  478. throw;
  479. }
  480. }
  481. private async Task<TkDataDTO> alimamaParseAsync(string content, TkDataDTO result)
  482. {
  483. string t = $"{DateTime.Now.Convert2UnixTimestamp(true)}";
  484. Random random = new();
  485. double randomNumber = random.NextDouble();
  486. string randomString = randomNumber.ToString()[2..];
  487. string cna = _cookies.GetContentPart("cna=", ";");
  488. string firstFiveCharacters = cna[..Math.Min(5, cna.Length)];
  489. var variableMap = new
  490. {
  491. url = content,
  492. union_lens = $"b_pvid:a219t._portal_v2_tool_links_page_home_index_htm_{t}_{randomString}_{firstFiveCharacters}",
  493. lensScene = "PUB",
  494. spmB = "_portal_v2_tool_links_page_home_index_htm"
  495. }.Convert2Json(true).UrlEncode();
  496. variableMap = variableMap.Replace(" ", "%20");
  497. string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/xt.entry.json?" +
  498. $"t={t}&_tb_token_={_tb_token}&floorId={_floorId}&refpid={_refpid}&variableMap={variableMap}";
  499. Stopwatch stopwatch = Stopwatch.StartNew();
  500. stopwatch.Start();
  501. var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
  502. .AddHeaders("X-Requested-With", "XMLHttpRequest")
  503. .AddHeaders("Cookie", _cookies);
  504. client.Proxy = _proxy;
  505. if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
  506. #if DEBUG
  507. client.Proxy = null;
  508. #endif
  509. client.Timeout = GetRequestTimeout(result.elapsedTime2);
  510. var response = client.Request(url);
  511. stopwatch.Stop();
  512. result.elapsedTime3 = (int)stopwatch.ElapsedMilliseconds;
  513. var body = string.Empty;
  514. try
  515. {
  516. if (!response.Successed)
  517. {
  518. result.channel = TkChannelEnum.tb;
  519. result.accountId = _accountId;
  520. result.accountName = _accountName;
  521. result.link_type = LinkTypeEnum.unknown;
  522. result.success = false;
  523. result.message = "fail";
  524. if (response.ResponseException != null)
  525. {
  526. _ = new LoggerLibrary("api_error", "fail")
  527. .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
  528. .SaveAsync();
  529. throw response.ResponseException;
  530. }
  531. return result;
  532. }
  533. body = response.Body();
  534. //{"code":601,"info":{"ok":false,"message":"nologin"}}
  535. JsonElement root = body.Convert2JsonElement();
  536. bool success = root.Read<bool>("success", false);
  537. string message = root.Read("message", string.Empty);
  538. string info_message = root.PathRead("info.message", string.Empty);
  539. if (!string.IsNullOrEmpty(info_message)) message = info_message;
  540. string taoToken = root.PathRead("data.taoToken", string.Empty);
  541. string shortLinkurl = root.PathRead("data.shortLinkurl", string.Empty);
  542. string couponLinkTaoToken = root.PathRead("data.couponLinkTaoToken", string.Empty);
  543. string couponShortLinkUrl = root.PathRead("data.couponShortLinkUrl", string.Empty);
  544. decimal couponAmount = root.PathRead<decimal>("data.couponAmount", 0);
  545. string couponEffectiveEndTime = root.PathRead("data.couponEffectiveEndTime", string.Empty);
  546. string couponEffectiveStartTime = root.PathRead("data.couponEffectiveStartTime", string.Empty);
  547. string itemId = root.PathRead("data.itemId", string.Empty);
  548. string itemName = root.PathRead("data.itemName", string.Empty);
  549. decimal promotionPrice = root.PathRead<decimal>("data.promotionPrice", 0);
  550. string sellerNickName = root.PathRead("data.sellerNickName", string.Empty);
  551. string shopTitle = root.PathRead("data.shopTitle", string.Empty);
  552. string pic = root.PathRead("data.pic", string.Empty);
  553. string qrCodeUrl = root.PathRead("data.qrCodeUrl", string.Empty);
  554. if (response.ResponseMessage != null)
  555. {
  556. switch (response.ResponseMessage.StatusCode)
  557. {
  558. case System.Net.HttpStatusCode.OK:
  559. {
  560. if (couponAmount > 0 && !string.IsNullOrEmpty(couponLinkTaoToken) && !string.IsNullOrEmpty(couponShortLinkUrl))
  561. {
  562. taoToken = couponLinkTaoToken;
  563. shortLinkurl = couponShortLinkUrl;
  564. }
  565. string shortLink = GetLink(taoToken);
  566. content = ReplaceUrls(content, shortLink);
  567. }
  568. break;
  569. case System.Net.HttpStatusCode.Found:
  570. string location = response.ResponseMessage.Headers.Location.OriginalString;
  571. if (!string.IsNullOrEmpty(location) && location.Contains("www.alimama.com/member/login.htm"))
  572. {
  573. success = false;
  574. message = "nologin";
  575. }
  576. break;
  577. default:
  578. {
  579. success = false;
  580. message = "other";
  581. }
  582. break;
  583. }
  584. }
  585. if (!success)
  586. {
  587. shortLinkurl = GetLink(content);
  588. switch (message)
  589. {
  590. case "该链接不支持转化,请更换链接尝试":
  591. case "网络错误":
  592. break;
  593. default:
  594. var _headers = response.ResponseMessage.Headers;
  595. var headers = "";
  596. foreach (var h in _headers)
  597. {
  598. foreach (var Value in h.Value)
  599. {
  600. headers += $"{h.Key}: {Value}\n";
  601. }
  602. }
  603. _ = new LoggerLibrary("api_error", "fail")
  604. .Info(message, content)
  605. .Info(headers, body)
  606. .SaveAsync();
  607. break;
  608. }
  609. }
  610. if (success)
  611. {
  612. if (string.IsNullOrEmpty(itemName))
  613. {
  614. itemName = GetTitle(taoToken);
  615. }
  616. }
  617. else
  618. {
  619. itemName = GetTitle(content);
  620. }
  621. string deeplink_url = GetDeeplink(shortLinkurl);
  622. result.channel = TkChannelEnum.tb;
  623. result.accountId = _accountId;
  624. result.accountName = _accountName;
  625. if (success)
  626. {
  627. switch (result.link_type)
  628. {
  629. case LinkTypeEnum.profile:
  630. case LinkTypeEnum.goods:
  631. break;
  632. default:
  633. result.link_type = LinkTypeEnum.goods;
  634. break;
  635. }
  636. }
  637. result.success = success;
  638. result.message = message;
  639. result.content = content;
  640. result.couponAmount = couponAmount;
  641. result.couponEffectiveEndTime = couponEffectiveEndTime;
  642. result.couponEffectiveStartTime = couponEffectiveStartTime;
  643. result.taoToken = taoToken;
  644. result.shortLinkurl = shortLinkurl;
  645. result.deeplink_url = deeplink_url;
  646. result.itemId = itemId;
  647. result.itemName = itemName;
  648. result.promotionPrice = promotionPrice;
  649. result.sellerNickName = sellerNickName;
  650. result.shopTitle = shopTitle;
  651. result.pic = pic;
  652. result.qrCodeUrl = qrCodeUrl;
  653. }
  654. catch
  655. {
  656. if (response.ResponseMessage?.StatusCode == System.Net.HttpStatusCode.OK)
  657. {
  658. if (body.Contains("<p>抱歉!页面无法访问……</p>"))
  659. {
  660. throw new APIException("抱歉!页面无法访问……");
  661. }
  662. }
  663. throw;
  664. }
  665. return result;
  666. }
  667. }
  668. }