parse_2.cs 24 KB

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