| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085 |
- using dodohold.core;
- using System.Text.RegularExpressions;
- using System.Diagnostics;
- using System.Text.Json;
- using TencentCloud.Fmu.V20191213.Models;
- using System;
- using MySqlX.XDevAPI;
- using static dodohold.core.ZTOExpress.CreateOrderArgs;
- using System.Threading;
- using TencentCloud.Tcm.V20210413.Models;
- using COSXML.Network;
- using System.Net;
- namespace molilian.core
- {
- public partial class AlimamaPlus
- {
- public static async Task<TkDataDTO> testTaskAsync(TkDataDTO result, CancellationToken token)
- {
- string url = "https://www.taobao.com";
- try
- {
- WebClientUtility client = new WebClientUtility();
- Thread.Sleep(5000);
- //await Task.Delay(5000, token); // 使用Task.Delay代替Thread.Sleep
- client.Timeout = TimeSpan.FromMilliseconds(3000);
- var response = await client.RequestAsync(url);
- var body = response.Body();
- }
- catch
- {
- result.success = false;
- result.message = "Error";
- }
- return result;
- }
- public void UnionParse2(string content, ref TkDataDTO result)
- {
- if ("veapi".Equals(_api) && _api_id > 0)
- {
- var account = VeapiPoolCore.Get(_api_id);
- if (account != null)
- {
- var core = new VeapiPlus(account.name, account.key, account.sessionKey);
- core.UnionParse(content, ref result);
- return;
- }
- }
- UnionParse(content, ref result);
- }
- public async Task<TkDataDTO> UnionParse2Async(string content, int commerceType, TkDataDTO result,
- CancellationToken cancellationToken = default,
- Dictionary<string, long> swData = null)
- {
- if ("veapi".Equals(_api) && _api_id > 0)
- {
- var account = VeapiPoolCore.Get(_api_id);
- if (account != null)
- {
- var core = new VeapiPlus(account.name, account.key, account.sessionKey);
- result = await core.UnionParseAsync(content, result, cancellationToken);
- return result;
- }
- }
- result = await UnionParseAsync(content, commerceType, result, cancellationToken, swData);
- return result;
- }
- /// <summary>
- /// 提取url里面的id参数
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static string? ExtractItemId(string url)
- {
- Match match = Regex.Match(url, @"(?:\?|&)id=(\d+)");
- if (match.Success)
- {
- return match.Groups[1].Value;
- }
- return null;
- }
- /// <summary>
- /// 是否淘宝链接,如果是商品链接就格式化成https://item.taobao.com/item.htm?id=****
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- private static (bool, string) IsTaobaoUrl(string url)
- {
- if (url.Contains("//a.m.taobao.com/i") ||
- url.Contains("//internal.tt.detail.taobao.com/i"))
- {
- //第一种提取方法
- string itemId = url.GetContentPart(".com/i", ".htm");
- if (!string.IsNullOrEmpty(itemId) && long.TryParse(itemId, out long _))
- {
- string resultUrl = $"https://item.taobao.com/item.htm?id={itemId}";
- return (true, resultUrl);
- }
- }
- //https://pages-g.m.taobao.com/wow/z/app/detail-next/item/index?x-ssr=true&id=753169018016
- if (url.Contains("//item.taobao.com/item.htm?") ||
- url.Contains("//pages-g.m.taobao.com/wow/z/app/detail-next/item/index?") ||
- url.Contains("//main.m.taobao.com/detail/index.html?") ||
- url.Contains("//h5.m.taobao.com/awp/core/detail.htm?") ||
- url.Contains("//new.m.taobao.com/detail.htm?") ||
- url.Contains("//outfliggys.m.taobao.com/app/trip/rx-travel-detail") ||
- url.Contains("//detail.m.tmall.com/item.htm?") ||
- url.Contains("//tmallx.tmall.com/app/tmallx-src/goods-detail") ||
- url.Contains("//detail.tmall.com/item.htm?") ||
- url.Contains("//internal.tt.detail.taobao.com/item.htm?") ||
- url.Contains("//internal.tt.detail.taobao.com/") ||
- url.Contains("//detail.tmall.hk/hk/item.htm?"))
- {
- string? itemId = ExtractItemId(url);
- if (!string.IsNullOrEmpty(itemId))
- {
- string resultUrl = $"https://item.taobao.com/item.htm?id={itemId}";
- return (true, resultUrl);
- }
- }
- return (false, url);
- }
- /// <summary>
- /// 排除已知的淘客链接
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public static bool IsAffLink(string url)
- {
- if (!url.StartsWith("https://") || !url.StartsWith("https://")) url = "https://" + url;
- Uri uri = new(url);
- if (uri.Host.Equals("s.click.taobao.com", StringComparison.OrdinalIgnoreCase) ||
- uri.Host.Equals("uland.taobao.com", StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- return false;
- }
- /// <summary>
- /// 判断淘客的¥羊角符号
- /// </summary>
- /// <param name="content"></param>
- /// <returns></returns>
- static bool ContainsSpecialFormat(string content)
- {
- // 使用正则表达式匹配内容中是否含有特定格式的字符串
- //string pattern = @"¥[a-zA-Z0-9\s]+¥";
- string pattern = @"[$¥🗝₴€₤£₳✔《💰🔑🎵✔️💲🔐📲₡]+[a-zA-Z0-9\s]+[$¥🗝₴€₤£₳✔《💰🔑🎵✔️💲🔐📲₡]*";
- return Regex.IsMatch(content, pattern);
- }
- public TimeSpan GetRequestTimeout(int deduction = 0)
- {
- #if DEBUG
- return TimeSpan.FromMilliseconds(10 * 1000);
- #endif
- int min = (int)(_config.rt_max * 0.3);
- if (_config.rt_max == 0) return TimeSpan.FromMilliseconds(1000);
- int timeout = _config.rt_max;
- if (deduction == 0)
- {
- timeout -= min;
- return TimeSpan.FromMilliseconds(timeout);
- }
- timeout -= deduction;
- if (timeout <= min) return TimeSpan.FromMilliseconds(1);
- return TimeSpan.FromMilliseconds(min);
- }
- /// <summary>
- /// 从http获取跳转的url
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- public async Task<(bool, string)> GetDesiredUrlAsync(WebProxy proxy, string url, CancellationToken cancellationToken = default)
- {
- string result;
- try
- {
- if (!url.Contains("m.tb.cn") &&
- !url.Contains("u.tb.cn") &&
- !url.Contains("e.tb.cn") &&
- !url.Contains("s.tb.cn"))
- return (false, "不是淘宝短网址");
- if (!_account.enable_deep_url) return (true, url);
- string desiredUrlPattern = "var url = '(.*?)'";
- WebClientUtility client = new()
- {
- Proxy = proxy,
- UserAgent = Sayaka.Common.ProviderFakeUserAgent.RandomComputer
- };
- if (url.Contains("u.tb.cn"))
- {
- client.AllowAutoRedirect = false;
- }
- url = url.Replace("http://u.tb.cn", "https://u.tb.cn");
- #if DEBUG
- client.Proxy = null;
- var response = await client.RequestAsync(url, "GET");
- #else
- client.Timeout = GetRequestTimeout(0);
- var response = await client.RequestAsync(url, "GET", cancellationToken);
- #endif
- if (response.ResponseMessage.StatusCode == HttpStatusCode.Found &&
- !string.IsNullOrEmpty(response.ResponseMessage?.Headers?.Location?.OriginalString))
- {
- string redirectUrl = response.ResponseMessage?.Headers?.Location?.OriginalString;
- return (true, redirectUrl);
- }
- var responseBody = response.Body();
- result = responseBody;
- if (response.Successed)
- {
- if (response.ResponseMessage.IsSuccessStatusCode)
- {
- Match match = Regex.Match(responseBody, desiredUrlPattern);
- if (match.Success)
- {
- result = match.Groups[1].Value; // 返回匹配的 URL
- if (string.IsNullOrEmpty(result)) return (false, "没有匹配的URL");
- if (result.StartsWith("//"))
- result = "https:" + result;
- return (true, result);
- }
- }
- else
- {
- result = $"{response.ResponseMessage.StatusCode}\n{responseBody}";
- }
- }
- else
- {
- throw response.ResponseException;
- }
- }
- catch (Exception ex)
- {
- _ = new LoggerLibrary("api_error", "desiredUrl_error").Info(ex.Message, ex.StackTrace).SaveAsync();
- result = "网络异常";
- }
- return (false, result);
- }
- /// <summary>
- /// 从http获取跳转的url
- /// </summary>
- /// <param name="url"></param>
- /// <returns></returns>
- (bool, string) GetDesiredUrl(string url)
- {
- string result;
- try
- {
- if (!url.Contains("m.tb.cn") && !url.Contains("e.tb.cn") && !url.Contains("s.tb.cn"))
- return (false, "不是淘宝短网址");
- string desiredUrlPattern = "var url = '(.*?)'";
- WebClientUtility client = new()
- {
- Proxy = ProxyNodesCore.RandomOne(_account.nodeName),
- UserAgent = Sayaka.Common.ProviderFakeUserAgent.RandomComputer
- };
- #if DEBUG
- client.Proxy = null;
- #endif
- client.Timeout = GetRequestTimeout(0);
- var response = client.Request(url);
- var responseBody = response.Body();
- result = responseBody;
- if (response.Successed)
- {
- if (response.ResponseMessage.IsSuccessStatusCode)
- {
- Match match = Regex.Match(responseBody, desiredUrlPattern);
- if (match.Success)
- {
- result = match.Groups[1].Value; // 返回匹配的 URL
- if (string.IsNullOrEmpty(result)) return (false, "没有匹配的URL");
- return (true, result);
- }
- }
- else
- {
- result = $"{response.ResponseMessage.StatusCode}\n{responseBody}";
- }
- }
- else
- {
- throw response.ResponseException;
- }
- }
- catch (Exception ex)
- {
- result = $"{ex.Message}\n{ex.StackTrace}";
- }
- return (false, result);
- }
- private void InternalTextProcessing(string content, ref TkDataDTO result)
- {
- //(result.success, result.content, result.link_type, result.shortLinkurl) = InternalTextProcessing(content,ref result);
- bool success;
- string resultText;
- LinkTypeEnum link_type = LinkTypeEnum.unknown;
- string url = GetLink(content);
- if (!string.IsNullOrEmpty(url))
- {
- //排除已知的淘客链接
- if (IsAffLink(url))
- {
- result.success = false;
- result.content = "排除淘客链接";
- result.link_type = LinkTypeEnum.other_aff;
- result.shortLinkurl = url;
- return;
- //return (false, "排除淘客链接", LinkTypeEnum.other_aff, url);
- }
- //直接提取
- (success, resultText) = IsTaobaoUrl(url);
- if (success)
- {
- result.success = true;
- result.content = resultText;
- result.link_type = LinkTypeEnum.goods;
- result.shortLinkurl = resultText;
- return;
- //return (true, result, LinkTypeEnum.goods, result);
- }
- //从http获取跳转的url
- Stopwatch stopwatch = Stopwatch.StartNew();
- stopwatch.Start();
- (success, resultText) = GetDesiredUrl(url);
- stopwatch.Stop();
- // 获取执行时间
- result.elapsedTime2 = (int)stopwatch.ElapsedMilliseconds;
- if (success)
- {
- //排除已知的淘客链接
- if (IsAffLink(resultText))
- {
- result.success = false;
- result.content = "排除淘客链接";
- result.link_type = LinkTypeEnum.other_aff;
- result.shortLinkurl = url;
- return;
- //return (false, "排除淘客链接", LinkTypeEnum.other_aff, url);
- }
- (success, resultText) = IsTaobaoUrl(resultText);
- if (success)
- {
- result.success = true;
- result.content = resultText;
- result.link_type = LinkTypeEnum.goods;
- result.shortLinkurl = resultText;
- return;
- //return (true, resultText, LinkTypeEnum.goods, resultText);
- }
- link_type = GetLinkType(resultText);
- }
- else
- {
- link_type = GetLinkType(url);
- }
- result.success = false;
- result.content = resultText;
- result.link_type = link_type;
- result.shortLinkurl = url;
- return;
- //return (false, result, link_type, url);
- }
- //判断淘客的¥羊角符号
- if (ContainsSpecialFormat(content))
- {
- result.success = false;
- result.content = "排除淘口令";
- result.link_type = LinkTypeEnum.other_aff;
- result.shortLinkurl = null;
- return;
- //return (false, "排除淘口令", LinkTypeEnum.other_aff, null);
- }
- //todo 临时应急 0614
- //return (false, "纯口令 没链接", link_type, null);
- result.success = false;
- result.content = "纯口令 没链接";
- result.link_type = LinkTypeEnum.other_aff;
- result.shortLinkurl = null;
- }
- public async Task<TkDataDTO> InternalTextProcessingAsync(string content, TkDataDTO result,
- CancellationToken cancellationToken = default,
- Dictionary<string, long> swData = null)
- {
- bool success;
- string resultText;
- result.link_type = LinkTypeEnum.unknown;
- //============================== 放弃转链-其他推广链接 ==============================
- string url = GetLink(content);
- if (!string.IsNullOrEmpty(url))
- {
- bool is_aff = IsAffLink(url);
- if (is_aff)
- {
- result.success = false;
- result.message = "放弃转链";
- result.reason = "其他推广链接";
- result.subCode = TkSubCodeEnum.OtherPromo;
- result.link_type = LinkTypeEnum.other_aff;
- result.shortLinkurl = url;
- return result;
- }
- (success, resultText) = IsTaobaoUrl(url);
- if (success)
- {
- result.success = true;
- result.content = resultText;
- result.link_type = LinkTypeEnum.goods;
- result.shortLinkurl = resultText;
- return result;
- }
- Stopwatch sw = Stopwatch.StartNew();
- var proxy = ProxyNodesCore.RandomOne(_account.nodeName);
- if (_proxy != null && proxy != null && _proxy.Address != proxy.Address)
- {
- result.proxy_node = proxy?.Address?.Authority;
- }
- (success, resultText) = await GetDesiredUrlAsync(proxy, url, cancellationToken);
- sw.Stop();
- // 获取执行时间
- result.elapsedTime2 = (int)sw.ElapsedMilliseconds;
- swData?.Add("\tGetDesiredUrlAsync", sw.ElapsedMilliseconds);
- //============================== 放弃转链-请求超时 ==============================
- #if DEBUG
- #else
- if (result.elapsedTime2 >= _config.rt_max || (!success && resultText.Contains("was canceled")))
- {
- result.success = false;
- result.message = "放弃转链";
- result.reason = "请求超时";
- result.subCode = TkSubCodeEnum.Other;
- return result;
- }
- #endif
- if (success)
- {
- string desiredUrl = resultText;
- //============================== 放弃转链-其他推广链接 ==============================
- bool is_aff2 = IsAffLink(desiredUrl);
- if (is_aff2)
- {
- result.success = false;
- result.message = "放弃转链";
- result.reason = "其他推广链接";
- result.subCode = TkSubCodeEnum.OtherPromo;
- result.link_type = LinkTypeEnum.other_aff;
- result.shortLinkurl = url;
- return result;
- }
- (success, desiredUrl) = IsTaobaoUrl(desiredUrl);
- if (success)
- {
- result.success = true;
- result.content = desiredUrl;
- result.link_type = LinkTypeEnum.goods;
- result.shortLinkurl = desiredUrl;
- return result;
- }
- result.link_type = GetLinkType(desiredUrl);
- }
- else
- {
- result.link_type = GetLinkType(url);
- if ("网络错误".Equals(resultText))
- {
- result.link_type = LinkTypeEnum.unknown;
- result.content = resultText;
- result.reason = resultText;
- }
- }
- if (result.content.Contains("霸下通用 web 页面-验证码"))
- {
- result.subCode = TkSubCodeEnum.Captcha;
- result.reason = "霸下验证码";
- }
- else
- {
- switch (result.link_type)
- {
- case LinkTypeEnum.profile:
- case LinkTypeEnum.live:
- case LinkTypeEnum.video:
- case LinkTypeEnum.note:
- case LinkTypeEnum.goods:
- case LinkTypeEnum.baseDomain:
- result.reason = string.Empty;
- result.content = content;
- break;
- default:
- result.reason = "非标准链接";
- result.subCode = TkSubCodeEnum.NonStdLink;
- break;
- }
- //if (result.link_type == LinkTypeEnum.baseDomain)
- //{
- // result.content = content;
- //}
- //else
- //{
- // result.reason = "非标准链接";
- // result.subCode = TkSubCodeEnum.NonStdLink;
- //}
- }
- result.success = false;
- result.message = "放弃转链";
- result.content = resultText;
- result.shortLinkurl = url;
- return result;
- //return (false, result, link_type, url);
- }
- //判断淘客的¥羊角符号
- bool is_aff3 = ContainsSpecialFormat(content);
- if (is_aff3)
- {
- result.success = false;
- result.message = "放弃转链";
- result.reason = "排除淘口令";
- result.subCode = TkSubCodeEnum.OtherPromo;
- result.link_type = LinkTypeEnum.other_aff;
- result.shortLinkurl = null;
- return result;
- //return (false, "排除淘口令", LinkTypeEnum.other_aff, null);
- }
- //todo 临时应急 0614
- //return (false, "纯口令 没链接", link_type, null);
- result.success = false;
- result.message = "放弃转链";
- result.reason = "纯口令 没链接";
- result.subCode = TkSubCodeEnum.OtherPromo;
- result.link_type = LinkTypeEnum.other_aff;
- result.shortLinkurl = null;
- return result;
- }
- private LinkTypeEnum GetLinkType(string url)
- {
- if (string.IsNullOrEmpty(url)) return LinkTypeEnum.unknown;
- if (url.Contains("m.tb.cn") || url.Contains("s.tb.cn") || url.Contains("e.tb.cn")) return LinkTypeEnum.baseDomain;
- if (url.StartsWith("https://huodong.m.taobao.com/act/talent/live.html")) return LinkTypeEnum.live;
- if (url.StartsWith("https://web.m.taobao.com/app/tnode/web/index")) return LinkTypeEnum.video;
- if (url.StartsWith("https://shop.m.taobao.com/shop/shopIndex.htm")) return LinkTypeEnum.profile;
- string pattern = @"^https://shop\d+(\.m)*\.taobao\.com";
- if (Regex.IsMatch(url, pattern))
- {
- return LinkTypeEnum.profile;
- }
- //https://shop.m.taobao.com/shop/shopIndex.htm?
- return LinkTypeEnum.unknown;
- }
- public async Task<TkDataDTO> alimamaParseAsync(string content, TkDataDTO result, CancellationToken cancellationToken = default)
- {
- string t = $"{DateTime.Now.Convert2UnixTimestamp(true)}";
- Random random = new();
- double randomNumber = random.NextDouble();
- string randomString = randomNumber.ToString()[2..];
- string cna = _cookies.GetContentPart("cna=", ";");
- string firstFiveCharacters = cna[..Math.Min(5, cna.Length)];
- var variableMap = new
- {
- url = content,
- union_lens = $"b_pvid:a219t._portal_v2_tool_links_page_home_index_htm_{t}_{randomString}_{firstFiveCharacters}",
- lensScene = "PUB",
- spmB = "_portal_v2_tool_links_page_home_index_htm"
- }.Convert2Json(true).UrlEncode();
- variableMap = variableMap.Replace(" ", "%20");
- string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/xt.entry.json?" +
- $"t={t}&_tb_token_={_tb_token}&floorId={_floorId}&refpid={_refpid}&variableMap={variableMap}";
- Stopwatch stopwatch = Stopwatch.StartNew();
- stopwatch.Start();
- var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
- .AddHeaders("X-Requested-With", "XMLHttpRequest")
- .AddHeaders("Cookie", _cookies);
- client.Proxy = _proxy;
- #if DEBUG
- client.Proxy = null;
- #endif
- if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
- client.Timeout = GetRequestTimeout(result.elapsedTime2);
- //var response = client.Request(url);
- #if DEBUG
- var response = await client.RequestAsync(url, "GET");
- #else
- var response = await client.RequestAsync(url, "GET", cancellationToken);
- #endif
- stopwatch.Stop();
- result.elapsedTime3 = (int)stopwatch.ElapsedMilliseconds;
- var body = string.Empty;
- try
- {
- if (!response.Successed)
- {
- result.channel = TkChannelEnum.tb;
- result.link_type = LinkTypeEnum.unknown;
- result.success = false;
- result.message = "fail";
- if (response.ResponseException != null)
- {
- _ = new LoggerLibrary("api_error", "fail")
- .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
- .SaveAsync();
- throw response.ResponseException;
- }
- return result;
- }
- if (response.ResponseMessage.StatusCode == System.Net.HttpStatusCode.Found)
- {
- _ = new LoggerLibrary("api_error", "fail")
- .Info($"302:{response.ResponseMessage.Headers.Location}")
- .SaveAsync();
- throw new Exception("302 Found, was canceled");
- }
- JsonElement root;
- try
- {
- body = response.Body();
- root = body.Convert2JsonElement();
- }
- catch (Exception ex)
- {
- _ = new LoggerLibrary("api_error", "fail")
- .Info(ex.Message, ex.StackTrace)
- .SaveAsync();
- if (body.Contains("https://g.alicdn.com/sd/punish/waf_block.html"))
- {
- result.channel = TkChannelEnum.tb;
- result.link_type = LinkTypeEnum.unknown;
- result.success = false;
- result.message = "waf_block";
- return result;
- }
- throw new Exception(body);
- }
- bool success = root.Read<bool>("success", false);
- string message = root.Read("message", string.Empty);
- string info_message = root.PathRead("info.message", string.Empty);
- if (!string.IsNullOrEmpty(info_message)) message = info_message;
- string taoToken = root.PathRead("data.taoToken", string.Empty);
- string shortLinkurl = root.PathRead("data.shortLinkurl", string.Empty);
- string couponLinkTaoToken = root.PathRead("data.couponLinkTaoToken", string.Empty);
- string couponShortLinkUrl = root.PathRead("data.couponShortLinkUrl", string.Empty);
- decimal couponAmount = root.PathRead<decimal>("data.couponAmount", 0);
- string couponEffectiveEndTime = root.PathRead("data.couponEffectiveEndTime", string.Empty);
- string couponEffectiveStartTime = root.PathRead("data.couponEffectiveStartTime", string.Empty);
- string itemId = root.PathRead("data.itemId", string.Empty);
- string mktId = root.PathRead("data.outputMktId", string.Empty);
- string itemName = root.PathRead("data.itemName", string.Empty);
- decimal promotionPrice = root.PathRead<decimal>("data.promotionPrice", 0);
- string sellerNickName = root.PathRead("data.sellerNickName", string.Empty);
- string shopTitle = root.PathRead("data.shopTitle", string.Empty);
- string pic = root.PathRead("data.pic", string.Empty);
- if (pic.StartsWith("//")) pic = "https:" + pic;
- string qrCodeUrl = root.PathRead("data.qrCodeUrl", string.Empty);
- if (response.ResponseMessage != null)
- {
- switch (response.ResponseMessage.StatusCode)
- {
- case System.Net.HttpStatusCode.OK:
- {
- if (couponAmount > 0 && !string.IsNullOrEmpty(couponLinkTaoToken) && !string.IsNullOrEmpty(couponShortLinkUrl))
- {
- taoToken = couponLinkTaoToken;
- shortLinkurl = couponShortLinkUrl;
- }
- string shortLink = GetLink(taoToken);
- content = ReplaceUrls(content, shortLink);
- }
- break;
- case System.Net.HttpStatusCode.Found:
- string location = response.ResponseMessage.Headers.Location.OriginalString;
- if (!string.IsNullOrEmpty(location) && location.Contains("www.alimama.com/member/login.htm"))
- {
- success = false;
- message = "nologin";
- }
- break;
- default:
- {
- success = false;
- message = "other";
- }
- break;
- }
- }
- if (!success)
- {
- shortLinkurl = GetLink(content);
- switch (message)
- {
- case "该商品已经下架或未加入淘宝客":
- case "该链接不支持转化,请更换链接尝试":
- result.subCode = TkSubCodeEnum.NoConvert;
- break;
- case "网络错误":
- result.subCode = TkSubCodeEnum.NetError;
- break;
- default:
- var _headers = response.ResponseMessage.Headers;
- var headers = "";
- foreach (var h in _headers)
- {
- foreach (var Value in h.Value)
- {
- headers += $"{h.Key}: {Value}\n";
- }
- }
- _ = new LoggerLibrary("api_error", "fail")
- .Info(message, content)
- .Info(headers, body)
- .SaveAsync();
- break;
- }
- }
- shortLinkurl = GetLink(taoToken);
- string deeplink_url = GetDeeplink(shortLinkurl);
- result.channel = TkChannelEnum.tb;
- if (success)
- {
- result.subCode = TkSubCodeEnum.Success;
- switch (result.link_type)
- {
- case LinkTypeEnum.profile:
- case LinkTypeEnum.goods:
- case LinkTypeEnum.video:
- case LinkTypeEnum.live:
- break;
- default:
- result.link_type = LinkTypeEnum.goods;
- break;
- }
- }
- result.success = success;
- result.message = message;
- result.reason = string.Empty;
- result.content = content;
- result.couponAmount = couponAmount;
- result.couponEffectiveEndTime = couponEffectiveEndTime;
- result.couponEffectiveStartTime = couponEffectiveStartTime;
- result.taoToken = taoToken;
- result.shortLinkurl = shortLinkurl;
- result.deeplink_url = deeplink_url;
- result.mktId = mktId;
- result.itemId = itemId;
- result.itemName = itemName;
- result.promotionPrice = promotionPrice;
- result.sellerNickName = sellerNickName;
- result.shopTitle = shopTitle;
- result.pic = pic;
- result.qrCodeUrl = qrCodeUrl;
- }
- catch (Exception ex)
- {
- if (response.ResponseMessage?.StatusCode == System.Net.HttpStatusCode.OK)
- {
- if (body.Contains("<p>抱歉!页面无法访问……</p>"))
- {
- throw new APIException("抱歉!页面无法访问……");
- }
- }
- throw;
- }
- return result;
- }
- private TkDataDTO alimamaParse(string content, TkDataDTO result)
- {
- string t = $"{DateTime.Now.Convert2UnixTimestamp(true)}";
- Random random = new();
- double randomNumber = random.NextDouble();
- string randomString = randomNumber.ToString()[2..];
- string cna = _cookies.GetContentPart("cna=", ";");
- string firstFiveCharacters = cna[..Math.Min(5, cna.Length)];
- var variableMap = new
- {
- url = content,
- union_lens = $"b_pvid:a219t._portal_v2_tool_links_page_home_index_htm_{t}_{randomString}_{firstFiveCharacters}",
- lensScene = "PUB",
- spmB = "_portal_v2_tool_links_page_home_index_htm"
- }.Convert2Json(true).UrlEncode();
- variableMap = variableMap.Replace(" ", "%20");
- string url = "https://pub.alimama.com/openapi/param2/1/gateway.unionpub/xt.entry.json?" +
- $"t={t}&_tb_token_={_tb_token}&floorId={_floorId}&refpid={_refpid}&variableMap={variableMap}";
- Stopwatch stopwatch = Stopwatch.StartNew();
- stopwatch.Start();
- var client = new WebClientUtility().SetContentType("application/json;charset=utf-8")
- .AddHeaders("X-Requested-With", "XMLHttpRequest")
- .AddHeaders("Cookie", _cookies);
- client.Proxy = _proxy;
- if (!string.IsNullOrEmpty(_user_agent)) client.UserAgent = _user_agent;
- #if DEBUG
- client.Proxy = null;
- url = "https://47.246.177.226/openapi/param2/1/gateway.unionpub/xt.entry.json?" +
- $"t={t}&_tb_token_={_tb_token}&floorId={_floorId}&refpid={_refpid}&variableMap={variableMap}";
- client.Headers["Host"] = "pub.alimama.com";
- #endif
- client.Timeout = GetRequestTimeout(result.elapsedTime2);
- //var response = client.Request(url);
- var response = client.Request(url);
- stopwatch.Stop();
- result.elapsedTime3 = (int)stopwatch.ElapsedMilliseconds;
- var body = string.Empty;
- try
- {
- if (!response.Successed)
- {
- result.channel = TkChannelEnum.tb;
- result.accountId = _accountId;
- result.accountName = _accountName;
- result.link_type = LinkTypeEnum.unknown;
- result.success = false;
- result.message = "fail";
- if (response.ResponseException != null)
- {
- _ = new LoggerLibrary("api_error", "fail")
- .Info(response.ResponseException.Message, response.ResponseException.StackTrace)
- .SaveAsync();
- throw response.ResponseException;
- }
- return result;
- }
- body = response.Body();
- //{"code":601,"info":{"ok":false,"message":"nologin"}}
- JsonElement root = body.Convert2JsonElement();
- bool success = root.Read<bool>("success", false);
- string message = root.Read("message", string.Empty);
- string info_message = root.PathRead("info.message", string.Empty);
- if (!string.IsNullOrEmpty(info_message)) message = info_message;
- string taoToken = root.PathRead("data.taoToken", string.Empty);
- string shortLinkurl = root.PathRead("data.shortLinkurl", string.Empty);
- string couponLinkTaoToken = root.PathRead("data.couponLinkTaoToken", string.Empty);
- string couponShortLinkUrl = root.PathRead("data.couponShortLinkUrl", string.Empty);
- decimal couponAmount = root.PathRead<decimal>("data.couponAmount", 0);
- string couponEffectiveEndTime = root.PathRead("data.couponEffectiveEndTime", string.Empty);
- string couponEffectiveStartTime = root.PathRead("data.couponEffectiveStartTime", string.Empty);
- string itemId = root.PathRead("data.itemId", string.Empty);
- string itemName = root.PathRead("data.itemName", string.Empty);
- decimal promotionPrice = root.PathRead<decimal>("data.promotionPrice", 0);
- string sellerNickName = root.PathRead("data.sellerNickName", string.Empty);
- string shopTitle = root.PathRead("data.shopTitle", string.Empty);
- string pic = root.PathRead("data.pic", string.Empty);
- string qrCodeUrl = root.PathRead("data.qrCodeUrl", string.Empty);
- if (response.ResponseMessage != null)
- {
- switch (response.ResponseMessage.StatusCode)
- {
- case System.Net.HttpStatusCode.OK:
- {
- if (couponAmount > 0 && !string.IsNullOrEmpty(couponLinkTaoToken) && !string.IsNullOrEmpty(couponShortLinkUrl))
- {
- taoToken = couponLinkTaoToken;
- shortLinkurl = couponShortLinkUrl;
- }
- string shortLink = GetLink(taoToken);
- content = ReplaceUrls(content, shortLink);
- }
- break;
- case System.Net.HttpStatusCode.Found:
- string location = response.ResponseMessage.Headers.Location.OriginalString;
- if (!string.IsNullOrEmpty(location) && location.Contains("www.alimama.com/member/login.htm"))
- {
- success = false;
- message = "nologin";
- }
- break;
- default:
- {
- success = false;
- message = "other";
- }
- break;
- }
- }
- if (!success)
- {
- shortLinkurl = GetLink(content);
- switch (message)
- {
- case "该商品已经下架或未加入淘宝客":
- case "该链接不支持转化,请更换链接尝试":
- case "网络错误":
- break;
- default:
- var _headers = response.ResponseMessage.Headers;
- var headers = "";
- foreach (var h in _headers)
- {
- foreach (var Value in h.Value)
- {
- headers += $"{h.Key}: {Value}\n";
- }
- }
- _ = new LoggerLibrary("api_error", "fail")
- .Info(message, content)
- .Info(headers, body)
- .SaveAsync();
- break;
- }
- }
- if (success)
- {
- if (string.IsNullOrEmpty(itemName))
- {
- itemName = GetTitle(taoToken);
- }
- }
- else
- {
- itemName = GetTitle(content);
- }
- string deeplink_url = GetDeeplink(shortLinkurl);
- result.channel = TkChannelEnum.tb;
- result.accountId = _accountId;
- result.accountName = _accountName;
- if (success)
- {
- switch (result.link_type)
- {
- case LinkTypeEnum.profile:
- case LinkTypeEnum.goods:
- case LinkTypeEnum.video:
- case LinkTypeEnum.live:
- break;
- default:
- result.link_type = LinkTypeEnum.goods;
- break;
- }
- }
- result.success = success;
- result.message = message;
- result.content = content;
- result.couponAmount = couponAmount;
- result.couponEffectiveEndTime = couponEffectiveEndTime;
- result.couponEffectiveStartTime = couponEffectiveStartTime;
- result.taoToken = taoToken;
- result.shortLinkurl = shortLinkurl;
- result.deeplink_url = deeplink_url;
- result.itemId = itemId;
- result.itemName = itemName;
- result.promotionPrice = promotionPrice;
- result.sellerNickName = sellerNickName;
- result.shopTitle = shopTitle;
- result.pic = pic;
- result.qrCodeUrl = qrCodeUrl;
- }
- catch
- {
- if (response.ResponseMessage?.StatusCode == System.Net.HttpStatusCode.OK)
- {
- if (body.Contains("<p>抱歉!页面无法访问……</p>"))
- {
- throw new APIException("抱歉!页面无法访问……");
- }
- }
- throw;
- }
- return result;
- }
- }
- }
|