using AllBase; using AllBase.Extension; using AllBase.Helper; using AllBase.Model.Param.ProductManage; using AllBase.Model.Result; using NaiBa.Util.Extension; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Net; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using Work.Api; using Work.BLL.Product; using Work.CollectClass; using Work.DouyinApiClass; namespace Work.BLL.Upload { public class UploadProductBLL { public static bool IsUseGlobalQualifications = false; public static List sGlobalPropList = new List(); public static List sGlobalQualifications = new List(); //[{"quality_number":null,"quality_key":"6966228537426575660","quality_name":"包装标签图","quality_attachments":[{"media_type":1,"url":"https://img1.deifei.com/j/529/e949c8676f77d.png"}]}] /// /// sku及sku属性的违规词列表: /// 商品创建失败: 商品规格值描述“灭火器”不符合平台要求,请重新填写\\n^非法的参数^商品创建失败: 发布诊断失败 /// public static List ViolationSkuWords = new List() { "灭火器", "保护帽", }; public string Name; ShopLoginInfo Shop; public static bool isEdit = false; public static int ShopThreadCount = 20; public static bool IsNoToken = false; public static decimal addMultiple; // 加价倍数 public static decimal addMultiple2; // 数据分裂加价范围 public static decimal postage; // 单独加价(元) public static decimal postage2; // 数据分裂加价范围 public static decimal beforPrice; // 市场价倍数 public static int MaxSingleShopUploadCount = 99999; // 单店上传最大个数 public static bool isStockLessThan = false; // 库存小于 public static decimal StockLessThanCount; // 库存小于多少不上货 public static bool isWaiting = false; // 上货暂停 public static bool isLitterSku; // 低于3个sku不上传 public static bool JustFree; public static bool isLogistics; public static int isLogistHour; public static string phone = ""; // 库存小于 public static decimal LowPricePercent; // 最低价sku倍数 public static decimal LowPriceAdd; // 最低价单独加价 public static bool LowPriceSku; // 勾选最低价sku public static string recommend_remark; // 商品评价 public static List ids = new List(); public ProductCollectBase p = new ProductCollectBase(); public static List ProductTemp = new List(); public static List ProductStock = new List(); public static List ProductStockTemp = new List(); public static List ShopTemp = new List(); public static List FilterTitleWordList = new List(); // 过滤标题违规词 public static List FilterSkuWordList = new List(); // 过滤sku违规词 public static List FilterBrandWordList = new List(); // 过滤品牌违规词 public static List FilterRemoveTitleWordList = new List(); // 消除标题违规词 // 界面显示商品对象 public delegate void ProductHandler(TaobaoProductBase p); public ProductHandler productHandler; // 日志提示信息 public delegate void NoticeHandler(string notice); public NoticeHandler noticeHandler; // 剩余个数信息 public delegate void RemainderHandler(); public RemainderHandler remainHandler; public static int maxCount; public static string PreFixTitle = ""; public static string fixName = "前缀"; public static bool isDraft; public static bool isCustomStock; public static int skuCustomStock; /// /// 多店数据分裂上货的剩余未上货数量 /// public static int MultiUploadRestCount; public static bool isMinSkuStock; public static int minSkuStock; /// /// 上货时使用代理获取拼多多上家商品 /// public static bool IsUseProxyCollectUp = true; /// /// 0现货发货 1预售发货 2阶梯发货 3现货-预售 4新预售 /// public static string delayType = "0"; // 发货类型 public static string preEndTime = ""; // 预售结束时间 public static string endDay = ""; // 几天后发货 public static string sendDay = ""; // 多少天发货 public static bool IsFilterTitleWord = false; // 过滤标题违规词 public static bool IsFilterRemoveTitleWord = false; // 去除标题违规词 public static bool IsFilterSkuWord = false; // 过滤Sku违规词 public static bool IsFilterBrandWord = false; // 过滤品牌违规词 public static bool IsFilterTMChaoShi = false; // 过滤天猫超市 public static bool IsSetCommission = false; // 上货后设置佣金 public static int CommissionRatio = 10; // 佣金比例 public static byte[] img; public static string baseImageUrl; public static bool isMultiUpload = false; public static bool isShopFissionUpload = false; // 单店裂变 public static string supply_7day_return = "2"; // 七天无理由类型 /// /// 新版预售时效发货时间 /// public static string newPreTime = "5天内发货"; /// /// 新版预售现货-预售模式现货发货时间 /// public static string newPreSendDayString = "24小时内发货"; /// /// 随机主图 /// public static bool isRandomMainImage = false; public static bool isSaveToOffLine = false; /// /// 云违规排查 /// public static bool isViolateCheck = false; /// /// 价格是否取整到元 /// public static bool isRoundPrice = false; /// /// 上货时指定的品牌,若未指定为空字符串 /// public static string productBrand = ""; /// /// 是否删除主图 /// public static bool IsDelMainPic = false; /// /// 删除指定主图 /// public static int DelMainPicId = 1; /// /// 是否删除第一张详情图 /// public static bool IsDelFirstContentPic = false; public UploadProductBLL(string Name, ShopLoginInfo Shop) { this.Name = Name; this.Shop = Shop; } public void UploadProduct() { try { int waitTimes = 0; int maxCount = 0; int loopPrexCount = 0; while (Shop.CanUpload) { TaobaoProductBase t = UploadProductBLL.ProductStock.Find(s => !s.Uped); if (t == null) { waitTimes++; if (waitTimes > 100 && UploadProductBLL.ProductStock.Count == 0) return; Thread.Sleep(1000); LogSave.Add(Name, Shop.ShopAccount + " 等待数据中..."); continue; } t.Uped = true; UploadProductBLL.ProductStock.Remove(t); Delete(t.guid); remainHandler(); if (Shop.ExpressId == 0) { Shop.ExpressId = GetFreightTemplate(); if (Shop.ExpressId == 0) { Thread.Sleep(1 * 5000); Shop.ExpressId = GetFreightTemplate(); } if (Shop.ExpressId == 0) { LogSave.Add(Name, "运费模板未找到"); LogSave.AddFile(Shop.ShopAccount + "运费模板未找到"); noticeHandler(Shop.ShopAccount + "运费模板未找到"); Shop.Message = "请设置运费模板"; UploadProductBLL.ShopTemp.Add(Shop); return; } } //去除括号 try { if (t.Titlte.Contains("【"))//移除【】和之间的数据 { string delStr = BaseRegex.GetMatchRegexString(ref t.Titlte, @"(【[\w\W]+?】)"); t.Titlte = t.Titlte.Replace(delStr, ""); } if (t.Titlte.Contains("["))//移除【】和之间的数据 { string delStr = BaseRegex.GetMatchRegexString(ref t.Titlte, @"([[\w\W]+?])"); t.Titlte = t.Titlte.Replace(delStr, ""); } } catch { continue; } //前缀 后缀 try { string[] l = PreFixTitle.Split('\n'); if (!string.IsNullOrEmpty(PreFixTitle)) { if (loopPrexCount >= l.Length) { loopPrexCount = 0; } if (!t.Titlte.Contains(l[loopPrexCount]) && fixName == "前缀") { t.Titlte = l[loopPrexCount].Replace("\r", "").Trim() + t.Titlte; if (BaseClass.GetCharLength(t.Titlte) > 60) t.Titlte = BaseClass.SubCharLength(t.Titlte, 60); } if (!t.Titlte.Contains(l[loopPrexCount]) && fixName == "后缀") { t.Titlte = t.Titlte + l[loopPrexCount].Replace("\r", "").Trim(); if (BaseClass.GetCharLength(t.Titlte) > 60) t.Titlte = BaseClass.SubCharLength(t.Titlte, 60); } } loopPrexCount++; } catch { continue; } t.Titlte = t.Titlte.Replace("//", "").Replace("\\", "");//Replace("/", "") maxCount++; if (maxCount > UploadProductBLL.MaxSingleShopUploadCount) return; var product = Set(t); if (product == null) continue; ProductTemp.Add(product); productHandler(product); } } catch (Exception ex) { } return; } public void UploadProductMulti() { List ProductStockMulti = new List(); for (int i = 0; i < UploadProductBLL.ProductStockTemp.Count; i++) { ProductStockMulti.Add(UploadProductBLL.ProductStockTemp[i].Clone()); } try { int waitTimes = 0; int maxCount = 0; int loopPrexCount = 0; while (Shop.CanUpload) { TaobaoProductBase t = ProductStockMulti.Find(s => !s.Uped); if (t == null) { waitTimes++; if (waitTimes > 100 && ProductStockMulti.Count == 0) return; Thread.Sleep(1000); LogSave.Add(Name, Shop.ShopAccount + " 等待数据中..."); continue; } t.Uped = true; if (ProductStock.Contains(t)) ProductStock.Remove(t); ProductStockMulti.Remove(t); MultiUploadRestCount = ProductStockMulti.Count; Delete(t.guid); remainHandler(); if (Shop.ExpressId == 0) { Shop.ExpressId = GetFreightTemplate(); if (Shop.ExpressId == 0) { Thread.Sleep(1 * 5000); Shop.ExpressId = GetFreightTemplate(); } if (Shop.ExpressId == 0) { LogSave.Add(Name, "运费模板未找到"); LogSave.AddFile(Shop.ShopAccount + "运费模板未找到"); noticeHandler(Shop.ShopAccount + "运费模板未找到"); Shop.Message = "请设置运费模板"; UploadProductBLL.ShopTemp.Add(Shop); return; } } //去除括号 try { if (t.Titlte.Contains("【"))//移除【】和之间的数据 { string delStr = BaseRegex.GetMatchRegexString(ref t.Titlte, @"(【[\w\W]+?】)"); t.Titlte = t.Titlte.Replace(delStr, ""); } if (t.Titlte.Contains("["))//移除【】和之间的数据 { string delStr = BaseRegex.GetMatchRegexString(ref t.Titlte, @"([[\w\W]+?])"); t.Titlte = t.Titlte.Replace(delStr, ""); } } catch { continue; } //前缀 后缀 try { string[] l = PreFixTitle.Split('\n'); if (!string.IsNullOrEmpty(PreFixTitle)) { if (loopPrexCount >= l.Length) { loopPrexCount = 0; } if (!t.Titlte.Contains(l[loopPrexCount]) && fixName == "前缀") { t.Titlte = l[loopPrexCount].Replace("\r", "").Trim() + t.Titlte; if (BaseClass.GetCharLength(t.Titlte) > 60) t.Titlte = BaseClass.SubCharLength(t.Titlte, 60); } if (!t.Titlte.Contains(l[loopPrexCount]) && fixName == "后缀") { t.Titlte = t.Titlte + l[loopPrexCount].Replace("\r", "").Trim(); if (BaseClass.GetCharLength(t.Titlte) > 60) t.Titlte = BaseClass.SubCharLength(t.Titlte, 60); } } loopPrexCount++; } catch { continue; } t.Titlte = t.Titlte.Replace("//", "").Replace("\\", "");//Replace("/", "") maxCount++; if (maxCount > UploadProductBLL.MaxSingleShopUploadCount) return; var product = Set(t); if (product == null) continue; ProductTemp.Add(product); productHandler(product); } } catch (Exception ex) { } return; } public static void Delete(string id) { string sql = "DELETE FROM Product WHERE fromid = '" + id + "' "; if (string.IsNullOrEmpty(id)) sql = "DELETE FROM Product "; try { SqliteHelper.ExecuteNonQuery(sql); } catch { } } public TaobaoProductBase Set(TaobaoProductBase t) { try { return AddGoods(t); } catch (Exception ex) { LogSave.AddFile(t.FromId + ex.Message); noticeHandler(t.FromId + ":" + ex.Message); t.ShopName = Shop.ShopAccount; t.Message = ex.Message; return t; } } /// /// 获取运费模板 /// public long GetFreightTemplate() { DouyinApi api = new DouyinApi(Shop); api.JsonData = new Dictionary(); api.JsonData.Add("page", "0"); api.JsonData.Add("size", "10"); string template = api.GetFreightTemplateList(); long tid = 0; var mt = BaseRegex.GetMatchRegex(ref template, @"""id"":[\s]*([\d]+)"); for (int i = 0; mt != null && i < mt.Count; i++) { var s = mt[i].ToString(); long j = long.Parse(mt[i].Groups[1].Value); if (j > 0) { tid = j; break; } } return tid; } public void GetProperty() { DouyinApi api = new DouyinApi(Shop); api.JsonData = new Dictionary(); api.JsonData.Add("category_leaf_id", "26623"); string html = api.GetCateProperty(); long tid = BaseRegex.GetLongJson(ref html, "id"); } public static long GetCat(string title, out string msg, out string fullCatInfo, ShopLoginInfo dShop) { msg = ""; fullCatInfo = ""; if (title != null && title.Contains("【") && title.Contains("】"))//移除【和】之间的数据 { string delStr = BaseRegex.GetMatchRegexString(ref title, @"(【[\w\W]+?】)"); title = title.Replace(delStr, ""); } if (title != null && title.Contains("[") && title.Contains("]"))//移除[和]之间的数据 { string delStr = BaseRegex.GetMatchRegexString(ref title, @"([[\w\W]+?])"); title = title.Replace(delStr, ""); } var cookieShops = GlobalConfig.ShopLoginList.Where(s => s.LoginStatus == "登录成功" && s.ShopId == dShop.ShopId).ToList(); if (cookieShops.Count == 0) { msg = "店铺未登录"; return 0; } while (cookieShops.Count > 0) { //retry: var cookieShop = cookieShops[Randomx.GetId(cookieShops.Count)]; string url = "https://fxg.jinritemai.com/product/tproduct/searchCategoryN?key=" + GetHtml.UrlEncodeUtf8(title) + "&appid=1&__token=" + cookieShop.ShopToken + "&_bid=ffa_goods&_lid=631352353727&_signature=" + cookieShop.Signature + ""; string refere = "https://fxg.jinritemai.com/ffa/g/create"; string html = GetPostTaobaoHtml.UploadTaobao(url, refere, true, cookieShop.Cookies); int total = BaseRegex.GetIntJson(ref html, "total"); if (!string.IsNullOrEmpty(html)) msg = BaseRegex.GetStringJson(ref html, "msg"); //int retryCount = 0; //if (total==0&&retryCount<6&&!string.IsNullOrEmpty(msg)&&!msg.Contains("关键词为空")) //{ // Thread.Sleep(Randomx.GetId(2000,5000)); // retryCount++; // goto retry; //} if (msg.Contains("系统繁忙")) { } if (html.Contains("登录信息已失效")) { msg = "店铺未登录"; cookieShop.LoginStatus = "未登录"; return 0; //cookieShops = GlobalConfig.DouShopLoginList.Where(s => s.LoginStatus == "登录成功" && s.ShopId == dShop.ShopId).ToList(); } else { if (html.Contains("data")) { JObject jObj = JObject.Parse(html); JArray jArr = jObj["data"] as JArray; if (jArr != null && jArr.Count > 0) fullCatInfo = JsonHelper.SerializeObject(jArr); } long catId = BaseRegex.GetLongJson(ref html, "id"); return catId; } } return 0; } public string GetProp(List propList, params string[] prev) { string result = ""; for (int i = 0; i < propList.Count; i++) { var propValue = propList[i].Replace("(", "(").Replace(")", ")").Replace(" ", ""); bool ishas = false; for (int j = 0; j < prev.Length; j++) { if (propValue.Contains(prev[j])) ishas = true; } if (ishas) continue; result = propValue; break; } return result; } public TaobaoProductBase AddGoods(TaobaoProductBase t) { while (isWaiting) Thread.Sleep(100); if (Shop.PayStatus != 1 && Shop.TrialUploadCount > 100) { t.Message = "当前为试用版,请购买专业版"; t.ShopName = Shop.ShopAccount; return t; } if (isViolateCheck && Shop.PayStatus != 1) { t.Message = "当前为试用版,无法使用云违规排查,请购买专业版"; t.ShopName = Shop.ShopAccount; return t; } if (isViolateCheck) { //https://yangkeduo.com/goods.html?goods_id=294943246187 string prev = GetPrev(t.FromType); ViolateParam violateParam = new ViolateParam() { DataFrom = 1, UpId = prev + t.FromId }; var violateHtml = ViolateBLL.GetViolate(violateParam.UpId, violateParam.UpIdNumber); if (violateHtml == "none") // 没有违规信息 { } else // 有违规信息 { if (ViolateRuleParam.LstViolateRuleNameSelect.Any(v => ("^" + violateHtml + "^").Contains("^" + v + "^"))) { violateParam.CheckTime = DateTime.Now; violateParam.RuleNames = violateHtml; t.Message = "当前商品违规:" + violateHtml; t.ShopName = Shop.ShopAccount; return t; } } } ProductCollectBase p = new ProductCollectBase(); t.FromType = t.FromType.Replace("\"", ""); if (t.FromType.Contains("搜款网") && t.FromId > 10) { char[] idc = t.FromId.ToString().ToCharArray(); if (t.FromId.ToString().Length < t.TolerantFormId.Length) idc = t.TolerantFormId.ToString().ToCharArray(); string ld = idc[idc.Length - 1].ToString(); for (int i = 1; i < idc.Length - 1; i++) { ld += idc[i]; } ld += idc[0]; t.FromIdBak = t.FromId; t.FromId = long.Parse(ld); p.from_site_id = 2; } //if (t.pcb != null) //{ // if (t.pcb.IsPreSale) // { // t.Message = "预售商品,跳过"; // noticeHandler("采集失败,跳过:" + t.FromId + ":" + t.Message); // return t; // } //} //else if (t.FromType == "拼多多" || t.FromType == "内部数据" || t.FromType == "搜款网" || t.FromType == "搜款网净化") { retryTokenGet: if (!IsUseProxyCollectUp) { //while (PinduoduoProductCollect.PinDuoDuoTokenList.Where(to => to.ProductDetailStatus == 1).ToList().Count == 0) //{ // IsNoToken = true; // Thread.Sleep(500); //} IsNoToken = false; } PinduoduoProductCollect pp = new PinduoduoProductCollect(Name, t, true); pp.Get(); if (pp.pb.before_price == -1) { pp.Get(); } if (!TaobaoMobileCollect.ProductTemp.ContainsKey(t.FromId)) { if (pp.IsAdvance || pp.pb.IsPreSale) { t.Message = "预售商品,跳过"; } else if (!pp.OnSale) { t.Message = pp.message; } else { t.Message = pp.message; // "IP或买手号被限制,请更换IP或检查买手号是否能正常浏览商品"; if (pp.IsNoToken) { goto retryTokenGet; } } if (string.IsNullOrEmpty(t.Message)) t.Message = "采集失败,跳过"; noticeHandler("采集失败,跳过:" + t.FromId + ":" + t.Message); return t; } } else if (t.FromType == "抖音") { try { p.from_id = t.FromId; CollectDoyin cd = new CollectDoyin(p); cd.GetProduct(); if (!cd.GetSuccess) { t.Message = "商品采集失败"; noticeHandler("采集失败,跳过:" + t.FromId + ":" + t.Message); return t; } if (cd.Product?.IsOnSale == false) { t.Message = "商品已下架"; noticeHandler("商品已下架,跳过:" + t.FromId + ":" + t.Message); return t; } } catch (Exception ex) { LogSave.AddFile(t.FromId + "抖音商品采集错误" + ex.Message); noticeHandler(t.FromId + ":抖音商品采集错误" + ex.Message); t.Message = "抖音商品采集错误"; return t; } } else if (t.FromType == "阿里巴巴") { p.from_url = "https://detail.1688.com/offer/" + t.FromId + ".html"; p.from_id = t.FromId; AlibabaProductGet alibbProInfo = new AlibabaProductGet(p); alibbProInfo.Get(); //GetCatIdForPdd(proInfo); //finalProductInfo = alibbProInfo.Product; } else // 淘宝 { p.from_url = "https://item.taobao.com/item.htm?id=" + t.FromId; p.from_id = t.FromId; TaobaoMobileCollect tm = new TaobaoMobileCollect(p); tm.Pinduoduo = true; tm.Name = Name; tm.Get(); if (!tm.GetSuccess) { t.Message = "商品采集失败"; if (tm.IsDown) t.Message = "商品已下架"; if (!string.IsNullOrEmpty(tm.pbMessage)) t.Message = tm.pbMessage; if (tm.hasCookies) t.Message = "请登录淘宝,获取数据"; noticeHandler("采集失败,跳过:" + t.FromId + ":" + t.Message); return t; } if (tm.IsPreSale || tm.Product.IsPreSale) { t.Message = "预售商品,跳过"; noticeHandler("采集失败,跳过:" + t.FromId + ":" + t.Message); return t; } } if (t.pcb != null) { // 从服务端获取产品数据库商品的详情 if (t.pcb.isFission && t.pcb.Images.Count == 0) { var fissionTemp = new FissionDataBaseBLL().GetFessionDetailById(t.pcb.fissionDataBaseId.ParseToInt()); if (fissionTemp == null) { Thread.Sleep(1000); fissionTemp = new FissionDataBaseBLL().GetFessionDetailById(t.pcb.fissionDataBaseId.ParseToInt()); } if (fissionTemp == null || string.IsNullOrEmpty(fissionTemp.main_pic)) { t.Message = "产品数据库产品已失效"; return t; } try { t.pcb.name = fissionTemp.fession_title; t.pcb.content = fissionTemp.container_info?.Replace("'>", "'>").Replace("new_group", "
"); t.pcb.Images = fissionTemp.main_pic == null ? new List() : fissionTemp.main_pic.Split(';').ToList(); //Fiss.prop_pic = fissionTemp.prop_pic; t.pcb.Props = JsonHelper.DeserializeJsonToList(fissionTemp.props); //Fiss.mainWord = fissionTemp.mainWord; //Fiss.viceword = fissionTemp.viceword; t.pcb.Prop = JsonHelper.DeserializeJsonToList(fissionTemp.prop); t.pcb.SkuMaps = JsonHelper.DeserializeJsonToList(fissionTemp.skus); //Fiss.from_shop_name = fissionTemp.from_shop_name; if (fissionTemp.qualifications != null) t.pcb.qualifications = JsonHelper.DeserializeJsonToList(fissionTemp.qualifications); } catch (Exception ex) { t.Message = "产品数据库产品格式错误"; return t; } } // 因分词库未保存店铺名称,故从验证上家是否下架的调用中获取上家店铺名称 var from_shop_name = p.from_shop_name; p = t.pcb; p.from_shop_name = from_shop_name; // 标题分词 if (t.pcb.fission_names?.Count > 0 == true) { p.name = t.pcb.fission_names[Randomx.GetId(t.pcb.fission_names.Count)]; } } else if (t.FromType == "阿里巴巴") { } else if (t.FromType == "抖音" && CollectDoyin.ProductTemp.ContainsKey(t.FromId)) p = CollectDoyin.ProductTemp[t.FromId].Clone(); else if (TaobaoMobileCollect.ProductTemp.ContainsKey(t.FromId)) p = TaobaoMobileCollect.ProductTemp[t.FromId].Clone(); else { t.Message = "商品或已下架"; if (!string.IsNullOrEmpty(p.message)) t.Message = p.message; noticeHandler("采集失败,跳过:" + t.FromId + ":" + t.Message); return t; } if (!(p.Images?.Count() >= 3)) { t.Message = "主图小于3张平台限制上传"; noticeHandler("主图小于3张平台限制上传:" + t.FromId + ":" + t.Message); return t; } if (isLitterSku && p.SkuMaps.Count < 3) { t.Message = "低于3个sku的商品不上传"; noticeHandler("低于3个sku的商品不上传:" + t.FromId + ":" + t.Message); return t; } if (JustFree && p.express_price > 0) { t.Message = "跳过非包邮商品"; noticeHandler("跳过非包邮商品:" + t.FromId + ":" + t.Message); return t; } // 抖店不支持标题换行符、tab等进行替换 p.name = p.name.Replace("\\n", " ").Replace("\n", " ").Replace("\\t", " "); // 抖店不支持的特殊符号替换 foreach (var sku in p.SkuMaps) { sku.name = sku.name.Replace("\\", ""); sku.nameLite = sku.nameLite.Replace("\\", ""); } foreach (var pr in p.Props) { foreach (var pv in pr.Values) { pv.name = pv.name.Replace("\\", ""); } } // 消减规格数超3的sku属性 for (int i = p.Props.Count - 1; i >= 0; i--) { if (p.Props.Count <= 3) break; if (p.Props[i].Values.Any(v => !string.IsNullOrEmpty(v.image))) continue; foreach (var pv in p.Props[i].Values) { foreach (var sku in p.SkuMaps) { sku.name = (";" + sku.name.Trim(';') + ";").Replace(";" + p.Props[i].name + ":" + pv.name + ";", ";").Trim(';'); sku.nameLite = (";" + sku.nameLite.Trim(';') + ";").Replace(";" + pv.name + ";", ";").Trim(';'); } } p.Props.Remove(p.Props[i]); } p.SkuMaps = p.SkuMaps.DistinctBy(s => s.name).ToList(); bool ishas = false; string bankname = ""; // 去除标题违规词 if (IsFilterRemoveTitleWord) { for (int i = 0; i < FilterTitleWordList.Count; i++) { p.name = p.name.Replace(FilterTitleWordList[i], ""); } } // 过滤标题 if (IsFilterTitleWord) { for (int i = 0; i < FilterTitleWordList.Count; i++) { if (p.name.Contains(FilterTitleWordList[i])) { ishas = true; bankname = FilterTitleWordList[i]; break; } } if (ishas) { t.Message = "标题发现违规词(" + bankname + "),跳过"; LogSave.Add(Name, "上货失败,标题发现违规词,跳过:" + t.FromId + ":" + t.Message); Thread.Sleep(1000); return t; } } // 过滤sku if (IsFilterSkuWord) { for (int i = 0; i < FilterSkuWordList.Count; i++) { if (p.SkuMaps.Any(s => s.name.Contains(FilterSkuWordList[i]))) { ishas = true; bankname = FilterSkuWordList[i]; break; } } if (ishas) { t.Message = "sku发现违规词(" + bankname + "),跳过"; LogSave.Add(Name, "上货失败,sku发现违规词,跳过:" + t.FromId + ":" + t.Message); Thread.Sleep(1000); return t; } } // 过滤品牌 if (IsFilterBrandWord) { for (int i = 0; i < FilterBrandWordList.Count; i++) { if (p.Prop.Any(pr => pr.Key == "品牌" && pr.Value.Contains(FilterBrandWordList[i]))) { ishas = true; bankname = FilterBrandWordList[i]; break; } } if (ishas) { t.Message = "品牌发现违规词(" + bankname + "),跳过"; LogSave.Add(Name, "上货失败,品牌发现违规词,跳过:" + t.FromId + ":" + t.Message); Thread.Sleep(1000); return t; } } // 过滤天猫超市 if (IsFilterTMChaoShi) { if (p.from_shop_name == "天猫超市") { t.Message = "天猫超市商品,跳过"; LogSave.Add(Name, "上货失败,天猫超市商品,跳过:" + t.FromId + ":" + t.Message); Thread.Sleep(1000); return t; } } if (!string.IsNullOrEmpty(p.logisticsTime) && isLogistics) { string daystr = BaseRegex.GetMatchRegexString(ref p.logisticsTime, @"([\d]+)"); int day = 0; int.TryParse(daystr, out day); if (p.logisticsTime.Contains("天")) day = day * 24; if (day / 24 > 0) day = day / 24; if (p.logisticsTime.Contains("今天")) day = 1; if (p.logisticsTime.Contains("明天")) day = 2; if (p.logisticsTime.Contains("后天")) day = 3; int paraDay = isLogistHour / 24 + 1; if ((p.logisticsTime.Contains("预售") || day >= paraDay) && isLogistics) { t.Message = "跳过发货超过" + isLogistHour + "小时商品或预售商品"; noticeHandler("跳过发货超过" + isLogistHour + "小时商品或预售商品:" + t.FromId + ":" + t.Message); return t; } } // 去除属性、sku的重复名称(已知拼多多商品可能会有相同sku) foreach (var prop in p.Props) { prop.Values = prop.Values.DistinctBy(kv => kv.name).ToList(); } p.SkuMaps = p.SkuMaps.DistinctBy(s => s.name).ToList(); // 去除sku违规词,后续可放开作为可选参数是否去除 foreach (var prop in p.Props) { prop.Values = prop.Values.Where(kv => !ViolationSkuWords.Any(v => kv.name.Contains(v))).ToList(); } p.SkuMaps = p.SkuMaps.Where(s => !ViolationSkuWords.Any(v => s.name.Contains(v))).ToList(); Dictionary dictionary = new Dictionary(); //0-普通,3-虚拟,6玉石闪购,7云闪购 商品类型 dictionary.Add("product_type", "0"); long catId = 0; string msg = ""; string fullCatInfo = ""; if (p.isFission && p.cat_id != 0) catId = p.cat_id; else if (t.FromType == "抖音" && p.cat_id != 0) catId = p.cat_id; else catId = GetCat(p.name, out msg, out fullCatInfo, Shop); if (catId == 0) { t.Message = "提交失败,类目获取失败" + (string.IsNullOrEmpty(msg) ? "" : "," + msg); t.ShopName = Shop.ShopAccount; return t; } // 叶子类目ID dictionary.Add("category_leaf_id", catId.ToString()); // 20171 22386 // 记录一级类目名称供需要一级类目的操作使用 string first_name = ""; if (!string.IsNullOrEmpty(fullCatInfo)) { first_name = BaseRegex.GetStringJson(ref fullCatInfo, "first_name"); } else { first_name = p.main_cat_name; } // 外部产品Id //string from_name = ""; //if (t.FromType == "拼多多") // from_name = "pd-"; //else if (t.FromType == "淘宝") // from_name = "tb-"; //else if (t.FromType == "阿里") // from_name = "al-"; //else if (t.FromType == "京喜") // from_name = "jx-"; //else if (t.FromType == "抖音") // from_name = "dy-"; //dictionary["outer_product_id"] = from_name + p.from_id.ToString() + "-" + Randomx.GetId(10000, 99999); //3496306606084372244 if (p.from_site_id == 7 || p.from_site_id.ToString().Length > 15) dictionary["outer_product_id"] = p.from_id.ToString(); else dictionary["outer_product_id"] = 9000 + p.from_site_id + p.from_id.ToString(); var apiGetOutIdExist = new DouyinApi(Shop); // 老上货数据判断是否重复铺货 var shopItems = GlobalConfig.SameProductCheckParamList.Find(sit => sit.ShopId == Shop.ShopId); var productIdExist = shopItems?.ShopSamePrpductItemList.Find(it => it.outer_product_id.Contains(p.from_id.ToString())); if (productIdExist != null) apiGetOutIdExist.JsonData.Add("product_id", productIdExist.product_id.ToString()); // 20220425之后的新商品判断是否重复铺货 else apiGetOutIdExist.JsonData.Add("out_product_id", dictionary["outer_product_id"]); var getOutIdExistResult = apiGetOutIdExist.GetProductDetail(); if (getOutIdExistResult != null && getOutIdExistResult.Contains("\"code\":10000")) { var status = JObject.Parse(getOutIdExistResult)["data"]?["status"]; var checkStatus = BaseRegex.GetIntJson(ref getOutIdExistResult, "check_status"); var productId = BaseRegex.GetLongJson(ref getOutIdExistResult, "product_id"); if (status != null && status.ParseToInt() == 2) // 回收站商品直接跳过不处理 { // do nothing } else if (checkStatus == 4) // 审核驳回商品重新上传 { var pid = BaseRegex.GetLongJson(ref getOutIdExistResult, "product_id"); DouyinApi dApi = new DouyinApi(Shop); dApi.JsonData = new Dictionary(); dApi.JsonData["product_id"] = pid.ToString(); var result = dApi.DeleteProduct(); } else if (checkStatus == 5) // 封禁商品拦截 { t.Message = "店铺已上传过此商品且被封禁,请勿再次上传"; t.ShopName = Shop.ShopAccount; return t; } else // 重复铺货商品拦截 { t.Message = "店铺已上传过此商品,请勿重复铺货"; t.ShopName = Shop.ShopAccount; t.GoodsId = productId; return t; } } // 启用全局资质和属性,按指定的资质上传 if (IsUseGlobalQualifications) { if (sGlobalQualifications.Count > 0) { if (p.qualifications == null) { p.qualifications = new List(); } foreach (var qu in sGlobalQualifications) { p.qualifications.RemoveAll(q => q.quality_name == qu.quality_name); p.qualifications.Add(qu); } } foreach (var pr in sGlobalPropList) { if (pr.Key == "品牌") { p.Prop.RemoveAll(pr1 => pr1.Key == "品牌" || pr1.Key == "品牌编号"); p.Prop.Add(pr); if (pr.Value == "无品牌") p.Prop.Add(new KeyValueBase("品牌编号", "596120136")); else { var apiBrand = new DouyinApi(Shop); apiBrand.JsonData["category_id"] = catId.ToString(); var textQuery = pr.Value.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault(); apiBrand.JsonData["query"] = textQuery == null ? "" : textQuery; // "JIXIN/积鑫"; var brandResult = apiBrand.cateBrandList(); var brand_id = BaseRegex.GetLongJson(ref brandResult, "brand_id"); var brand_name_cn = BaseRegex.GetStringJson(ref brandResult, "name_cn"); var brand_name_en = BaseRegex.GetStringJson(ref brandResult, "name_en"); if ((brand_name_cn == textQuery || brand_name_en == textQuery) && brand_id > 0) p.Prop.Add(new KeyValueBase("品牌编号", brand_id.ToString())); } } else { p.Prop.RemoveAll(pr1 => pr1.Key == pr.Key); p.Prop.Add(pr); } } } // 获取尺码表 if (first_name.Contains("女装") || first_name.Contains("男装") || first_name.Contains("内衣裤袜") || first_name.Contains("童装/婴儿装/亲子装") || first_name.Contains("女鞋") || first_name.Contains("男鞋")) { string urlComponent = "https://fxg.jinritemai.com/product/tproduct/getAvailableTemplate?category_id=" + catId + "&appid=1&__token=" + Shop.ShopToken + "&_bid=ffa_goods&_lid=847509501715&_signature=" + Shop.Signature + ""; string refereComponent = "https://fxg.jinritemai.com/ffa/g/create"; string htmlComponent = GetPostTaobaoHtml.UploadTaobao(urlComponent, refereComponent, true, Shop.Cookies); if (htmlComponent.Contains("\"available_component_template_info\":[]")) { t.Message = "请去店铺后台创建产品尺码表!"; t.ShopName = Shop.ShopAccount; return t; } var templateId = BaseRegex.GetStringJson(ref htmlComponent, "template_id"); if (!string.IsNullOrEmpty(templateId)) { dictionary["size_info_template_id"] = templateId; } } //商品属性"product_format": "货号|8888^上市年份季节|2018年秋季^", 属性名称|属性值 之间用|分隔, 多组之间用^分开 CatePropertyResponseInfo propResult = new UploadPropertyBLL().getCatePropertyInterfaceV2(catId.ToString(), Shop); if (Shop.ApiAuthStatus != "授权成功") { t.Message = "授权过期,请重新授权!"; t.ShopName = Shop.ShopAccount; return t; } for (int i = 0; i < 3 && propResult.message != "success"; i++) { Thread.Sleep(500); propResult = new UploadPropertyBLL().getCatePropertyInterfaceV2(catId.ToString(), Shop); } if (propResult.message != "success") { t.Message = "类目属性规则获取失败"; t.ShopName = Shop.ShopAccount; return t; } string property = new UploadPropertyBLL().GetCatePropertyAnalysis(propResult, Shop, p); if (!string.IsNullOrEmpty(property)) { //dictionary.Add("product_format", property); dictionary.Add("product_format_new", property); } else { t.Message = "商品属性生成失败"; t.ShopName = Shop.ShopAccount; return t; } //dictionary.Add("product_format_new", property.Replace("\"","\\\""));//"{\\\"1687\\\":[{\\\"value\\\":2147202834,\\\"name\\\":\\\"女汉将\\\"}]}" //商品名称 if (!string.IsNullOrEmpty(t.Titlte) && fixName == "前缀") p.name = t.Titlte + p.name; if (!string.IsNullOrEmpty(t.Titlte) && fixName == "后缀") p.name = p.name + t.Titlte; if (BaseClass.GetCharLength(p.name) > 60) p.name = BaseClass.SubCharLength(p.name, 60); // 商品如果生鲜必须包含净含量 if ((p.main_cat_name.Contains("水果") || p.main_cat_name.Contains("生鲜")) && !p.name.Contains("g") && !p.name.Contains("斤") && !p.name.Contains("克")) { if (BaseClass.GetCharLength(p.name) > 55) p.name = BaseClass.SubCharLength(p.name, 55); p.name = p.name + "1000g"; } dictionary.Add("name", p.name); if (Shop.LstBrand == null) { Shop.LstBrand = GetBrandList(Shop); } //DouyinApi apix = new DouyinApi(Shop); //apix.JsonData["category_id"] = p.cat_id.ToString(); //apix.JsonData["query"] = "JIXIN/积鑫"; //var rx = apix.cateBrandList(); if (Shop.LstBrand?.Count > 0) { if (Shop.ShopAccount == "权益服务齐全的专营店") { dictionary.Add("brand_id", "2122428529"); } else { dictionary.Add("brand_id", Shop.LstBrand[0].id.ToString()); } } else dictionary.Add("standard_brand_id", "596120136"); // 对应产品后台无品牌选项 if (p.Prop.Any(pr => pr.Key == "品牌编号")) dictionary["standard_brand_id"] = p.Prop.FirstOrDefault(pr => pr.Key == "品牌编号").Value; // 根据商品编辑里的指定品牌设置品牌编号 if (!string.IsNullOrEmpty(productBrand) && (Shop.ShopAccount.Contains("旗舰店") || Shop.ShopAccount.Contains("专营店") || Shop.ShopAccount.Contains("专卖店"))) { var brandApi = new DouyinApi(Shop); brandApi.JsonData["category_id"] = catId.ToString(); var textQuery = productBrand; brandApi.JsonData["query"] = textQuery; var result = brandApi.cateBrandList(); if (!result.Contains("brand_list")) { Thread.Sleep(1000); result = brandApi.cateBrandList(); } try { var jArr = JObject.Parse(result)["data"]["brand_list"] as JArray; if (jArr == null) jArr = JObject.Parse(result)["data"]["auth_brand_list"] as JArray; var brand_cn = jArr[0]["name_cn"].ToString(); var brand_en = jArr[0]["name_en"].ToString(); var brand_id = jArr[0]["brand_id"].ParseToLong(); if (brand_cn == textQuery || brand_en == textQuery) { dictionary["standard_brand_id"] = brand_id.ToString(); } else { t.Message = "指定品牌不存在"; t.ShopName = Shop.ShopAccount; return t; } } catch (Exception ex) { t.Message = "指定品牌获取失败"; t.ShopName = Shop.ShopAccount; return t; } } string searchFolderResult = SearchFolder(Shop); if (!searchFolderResult.Contains("\"code\":10000")) searchFolderResult = SearchFolder(Shop); int total = BaseRegex.GetIntJson(ref searchFolderResult, "total"); string folderId = BaseRegex.GetStringJson(ref searchFolderResult, "folder_id"); if (total == 0 || string.IsNullOrEmpty(folderId)) { string folder = CreateImageFolder(Shop); folderId = BaseRegex.GetStringJson(ref folder, "folder_id"); } // 单张图片上传 //string tid = Md5Base.GetMd5(p.name).Substring(8, 16) + Randomx.GetId(2000); //string byte_url = UploadImageSync(Shop, folderId, "http://gw.alicdn.com/bao/uploaded/i4/O1CN010Uo1SF22kPm5WRwkD_!!0-rate.jpg", tid); // 主轮播图 主图 if (p.Images == null || p.Images.Count == 0 || string.IsNullOrEmpty(p.Images[0])) { } noticeHandler(p.from_id + ":正在上传轮播图片"); Thread.Sleep(Randomx.GetId(500, 1500) + UploadProductBLL.ids.Count * 100); // 删除指定主图 if (IsDelMainPic) { for (int i = 1; i <= p.Images.Count; i++) { if (i == DelMainPicId) { p.Images.RemoveAt(i - 1); break; } } if (!(p.Images?.Count() >= 3)) { t.Message = "主图小于3张平台限制上传"; noticeHandler("主图小于3张平台限制上传:" + t.FromId + ":" + t.Message); return t; } } string mainImages = ""; int picCount = 0; var images = p.Images.Distinct().ToList(); //主图大于十张,随机挑选其中十张 if (images.Count > 10) GetTenImages(images); if (isRandomMainImage) images = GetRandomMainImage(string.Join("|", images)).Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries).ToList(); string imagePic = ""; List request_id_List = new List(); for (int i = 0; i < images.Count; i++) { string urlImage = images[i]; if (!urlImage.Contains("http")) { urlImage = "https:" + images[i]; } if (!string.IsNullOrEmpty(imagePic)) { imagePic += ","; } string tid = Md5Base.GetMd5(p.name).Substring(8, 16) + Randomx.GetId(2000); long rquest_id = Randomx.GetId(2000000000); request_id_List.Add(rquest_id); imagePic += "{\\\"request_id\\\":" + rquest_id + ",\\\"folder_id\\\":\\\"" + folderId + "\\\",\\\"material_type\\\":\\\"photo\\\",\\\"name\\\":\\\"" + tid + "\\\",\\\"url\\\":\\\"" + urlImage + "\\\"}"; if (i >= 9) break; } int imageMapsRetryTimes = 0; imageMapsRetry: string imageMaps = BatchUploadImageSync(Shop, "[" + imagePic + "]"); if (imageMaps.Contains("access_token已过期")) { t.Message = "授权过期,请重新授权!"; t.ShopName = Shop.ShopAccount; return t; } if (!imageMaps.Contains("\"code\":10000")) imageMaps = BatchUploadImageSync(Shop, "[" + imagePic + "]"); if (imageMaps != null && imageMaps.Contains("素材库容量不足")) { if (imageMapsRetryTimes < 5) { var folderResult = new UploadMaterialBLL().DelOldestApiMaterialFolder(Shop); if (folderResult) { imageMapsRetryTimes++; goto imageMapsRetry; } } t.Message = "素材库容量不足"; t.ShopName = Shop.ShopAccount; return t; } var imageMapsObj = JsonHelper.JObjectParse(imageMaps)?["data"]; if (imageMapsObj == null || imageMapsObj["success_map"] == null) { t.Message = "轮播图Json格式错误"; t.ShopName = Shop.ShopAccount; return t; } // 处理上传失败图片 var failedMapStr = imageMapsObj["failed_map"]?.ToString(); if (!string.IsNullOrEmpty(failedMapStr) && failedMapStr != "{}" && imageMapsRetryTimes < 5) { Thread.Sleep(1000); imageMapsRetryTimes++; goto imageMapsRetry; } for (int i = 0; i < request_id_List.Count(); i++) { string urlImage = imageMapsObj["success_map"]?[request_id_List[i].ToString()]?["ByteUrl"]?.ToString(); if (string.IsNullOrEmpty(urlImage)) continue; if (mainImages.Contains(urlImage)) continue; picCount++; if (mainImages.Trim() != "") { mainImages += "|"; } mainImages += urlImage; if (mainImages.Split('|').Count() > 4) break; } //商品轮播图 dictionary.Add("pic", mainImages); if (p.Props.Count == 0) { } string specimg = p.Props[0].Values[0].image; // 支付方式,0货到付款 1在线支付,2,货到付款+在线支付 dictionary.Add("pay_type", "1"); // 规格属性等 string specHtml = ""; if (string.IsNullOrEmpty(specimg)) { for (int i = p.Props.Count - 1; i > -1; i--) { var pitem = p.Props[i]; string proStr = pitem.name + "|"; for (int j = 0; j < pitem.Values.Count; j++) { proStr += pitem.Values[j].name.Replace("|", " ").Replace("丨", " ").Replace("(", "(").Replace(")", ")").Replace(" ", "") + ","; } specHtml += proStr.Substring(0, proStr.Length - 1); if (!string.IsNullOrEmpty(specHtml)) { specHtml += "^"; } } } else { for (int i = 0; i < p.Props.Count; i++) { var pitem = p.Props[i]; string proStr = pitem.name + "|"; for (int j = 0; j < pitem.Values.Count; j++) { proStr += pitem.Values[j].name.Replace("|", " ").Replace("丨", " ").Replace("\t", "").Replace("(", "(").Replace(")", ")").Replace(" ", "") + ","; } specHtml += proStr.Substring(0, proStr.Length - 1); if (!string.IsNullOrEmpty(specHtml)) { specHtml += "^"; } } } // 店铺通用规格 // 根据类目查询商品发布规则,如支持的发货模式、发货时效等 (时效sku) bool isNormalRuleCanUse = true, isTimeSkuWithNormalCanUse = true, isTimeSkuCanUse = true; string updateRule = ""; try { updateRule = getProductUpdateRule(catId.ToString(), Shop); var jObj = JObject.Parse(updateRule); isNormalRuleCanUse = jObj["data"]?["fulfillment_rule"]?["normal_rule"]?["support"]?.ToString()?.ToLower() != "false"; isTimeSkuWithNormalCanUse = jObj["data"]?["fulfillment_rule"]?["time_sku_presell_with_normal_rule"]?["support"]?.ToString()?.ToLower() == "true"; isTimeSkuCanUse = jObj["data"]?["fulfillment_rule"]?["time_sku_pure_presell_rule"]?["support"]?.ToString()?.ToLower() == "true"; } catch { } var productDelayType = UploadProductBLL.delayType; // 普通模式不支持发货但可以时效发货,则改为时效发货模式 if (UploadProductBLL.delayType == "0" && isNormalRuleCanUse == false && isTimeSkuWithNormalCanUse == true) { productDelayType = "3"; newPreSendDayString = "48小时内发货"; var specHtmlList = specHtml.Split(new string[] { "^" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (specHtmlList.Count == 3) specHtmlList.RemoveAt(2); specHtmlList.Add("发货时效|" + newPreSendDayString + "," + newPreTime); specHtml = string.Join("^", specHtmlList); } // 现货+时效sku设置 if (UploadProductBLL.delayType == "3") { newPreSendDayString = "48小时内发货"; //if (UploadProductBLL.sendDay == "2") // newPreSendDayString = "48小时内发货"; var specHtmlList = specHtml.Split(new string[] { "^" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (specHtmlList.Count == 3) specHtmlList.RemoveAt(2); specHtmlList.Add("发货时效|" + newPreSendDayString + "," + newPreTime); specHtml = string.Join("^", specHtmlList); } // 时效sku设置 if (UploadProductBLL.delayType == "4") { var specHtmlList = specHtml.Split(new string[] { "^" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (specHtmlList.Count == 3) specHtmlList.RemoveAt(2); specHtmlList.Add("发货时效|" + newPreTime); specHtml = string.Join("^", specHtmlList); } dictionary.Add("specs", specHtml); // 运费模板id,传0表示包邮 dictionary.Add("freight_id", Shop.ExpressId.ToString()); decimal maxPriceNew = 0M; decimal minPriceNew = 0M; decimal expressPrcie = p.express_price; SkuMapBase skuMin = null; decimal lastAddMultiple = UploadProductBLL.addMultiple; decimal lastAddPostage = UploadProductBLL.postage; // 勾选分裂上货价格随机计算 if (isMultiUpload) { var deltaAddMultiple = addMultiple2 - addMultiple; if (deltaAddMultiple > 0) { var deltaAddMultipleInt = (int)deltaAddMultiple; lastAddMultiple = addMultiple + Randomx.GetId(deltaAddMultipleInt + 1); } var deltaAddPostage = postage2 - postage; if (deltaAddPostage > 0) { var deltaAddPostageInt = (int)deltaAddPostage; lastAddPostage = postage + Randomx.GetId(deltaAddPostageInt + 1); } } // 数据净化数据勾选了单独加价的选项后 if (p.is_changeprice.ToLower() == "true") { lastAddMultiple = p.addPricePercent; lastAddPostage = p.baseAddPrice; } if (p.SkuMaps.Count > 0) { maxPriceNew = WhitePriceBuild(p.SkuMaps[0].price, lastAddMultiple, lastAddPostage, expressPrcie); minPriceNew = WhitePriceBuild(p.SkuMaps[0].price, lastAddMultiple, lastAddPostage, expressPrcie); } else { t.Message = "不支持上传无sku商品。"; t.ShopName = Shop.ShopAccount; return t; } if (isRoundPrice) { maxPriceNew = Math.Ceiling(maxPriceNew / 100m) * 100; minPriceNew = Math.Ceiling(minPriceNew / 100m) * 100; } // 生成新的价格 for (int i = 0; i < p.SkuMaps.Count; i++) { p.SkuMaps[i].new_price = WhitePriceBuild(p.SkuMaps[i].price, lastAddMultiple, lastAddPostage, expressPrcie); if (isRoundPrice) p.SkuMaps[i].new_price = (int)(Math.Ceiling(p.SkuMaps[i].new_price / 100m) * 100); if (maxPriceNew < p.SkuMaps[i].new_price) maxPriceNew = p.SkuMaps[i].new_price; if (minPriceNew > p.SkuMaps[i].new_price) minPriceNew = p.SkuMaps[i].new_price; if (skuMin == null || skuMin.new_price > p.SkuMaps[i].new_price) skuMin = p.SkuMaps[i]; } if (LowPriceSku && p.SkuMaps.Count > 1 && skuMin != null) { skuMin.new_price = (int)((skuMin.price * LowPricePercent + LowPriceAdd + expressPrcie) * 100); if (isRoundPrice) skuMin.new_price = (int)(Math.Ceiling(skuMin.new_price / 100m) * 100); } if (UploadProductBLL.isMinSkuStock) { skuMin.number = UploadProductBLL.minSkuStock; } if (UploadProductBLL.isStockLessThan) { for (int i = 0; i < p.SkuMaps.Count; i++) { if (p.SkuMaps[i].number < UploadProductBLL.StockLessThanCount) { p.SkuMaps[i].number = 0; } } } List speclist = new List(); for (int i = 0; i < p.SkuMaps.Count; i++) { var sku = p.SkuMaps[i]; spec_prices spec_prices = new spec_prices(); spec_prices.code = ""; spec_prices.price = (long)sku.new_price; spec_prices.stock_num = sku.number; if (UploadProductBLL.isCustomStock) spec_prices.stock_num = UploadProductBLL.skuCustomStock; spec_prices.outer_sku_id = ""; spec_prices.picurl = sku.prop_image; string[] specs = sku.nameLite.Replace("(", "(").Replace("|", " ").Replace("丨", " ").Replace("\t", "").Replace(")", ")") .Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries); if (specs.Length > 0) spec_prices.spec_detail_name1 = specs[0]; if (specs.Length > 1) spec_prices.spec_detail_name2 = specs[1]; if (specs.Length > 2) spec_prices.spec_detail_name3 = specs[2]; if (string.IsNullOrEmpty(specimg) && specs.Length > 1) { if (!string.IsNullOrEmpty(specs[1])) { spec_prices.spec_detail_name1 = specs[1]; spec_prices.spec_detail_name2 = specs[0]; sku.name = p.Props[1].name + ":" + specs[1] + ";" + p.Props[0].name + ":" + specs[0]; } } if (!speclist.Any(sp => sp.spec_detail_name1 + sp.spec_detail_name2 + sp.spec_detail_name3 == spec_prices.spec_detail_name1 + spec_prices.spec_detail_name2 + spec_prices.spec_detail_name3)) speclist.Add(spec_prices); } foreach (var spec in speclist) { if (spec.stock_num < 0) spec.stock_num = 0; } // 处理抖音总库存1000000限制 var totalStock = speclist.Sum(s => s.stock_num); while (totalStock > 1000000) { foreach (var spec in speclist) { if (spec.stock_num > 1) spec.stock_num = spec.stock_num - 1; } totalStock = speclist.Sum(s => s.stock_num); } //规格图片 获取规格图片 if (p.Props.Count == 0) { } noticeHandler(p.from_id + ":正在上传规格图片"); Thread.Sleep(Randomx.GetId(500, 1500) + UploadProductBLL.ids.Count * 100); string picStr = ""; int pCount = 0; string imageSpec = ""; List specStrList = new List(); List requestList = new List(); for (int i = 0; i < p.Props.Count; i++) { var props = p.Props[i]; // 跳过无图片属性分组 if (!props.Values.Any(v => !string.IsNullOrEmpty(v.image))) continue; // 已获取到一组属性有图片,跳过其他分组 if (i > 0 && !string.IsNullOrEmpty(imageSpec)) break; for (int j = 0; j < props.Values.Count; j++) { var pic = props.Values[j].image; long requestid = Randomx.GetId(2000000000); string tid = Md5Base.GetMd5(p.name).Substring(8, 16) + Randomx.GetId(2000); if (string.IsNullOrEmpty(pic)) pic = p.image; if (string.IsNullOrEmpty(pic)) continue; if (!(pic.Contains("https:") || pic.Contains("http:"))) { pic = "https:" + pic; } if (!string.IsNullOrEmpty(imageSpec)) { imageSpec += ","; } imageSpec += "{\\\"request_id\\\":" + requestid + ",\\\"folder_id\\\":\\\"" + folderId + "\\\",\\\"material_type\\\":\\\"photo\\\",\\\"name\\\":\\\"" + tid + "\\\",\\\"url\\\":\\\"" + pic + "\\\"}"; specStrList.Add(pic); requestList.Add(requestid); } } int imageSpecMapsRetryTimes = 0; imageSpecMapsRetry: string imageSpecMaps = ""; if (!string.IsNullOrEmpty(imageSpec)) imageSpecMaps = BatchUploadImageSync(Shop, "[" + imageSpec + "]"); if (imageSpecMaps != null && imageSpecMaps.Contains("素材库容量不足")) { if (imageSpecMapsRetryTimes < 5) { var folderResult = new UploadMaterialBLL().DelOldestApiMaterialFolder(Shop); if (folderResult) { imageSpecMapsRetryTimes++; goto imageSpecMapsRetry; } } t.Message = "素材库容量不足"; t.ShopName = Shop.ShopAccount; return t; } var imageSpecMapsObj = JsonHelper.JObjectParse(imageSpecMaps)?["data"]; if (!string.IsNullOrEmpty(imageSpec) && imageSpecMapsObj?["success_map"] == null) { t.Message = "SKU图Json格式错误"; t.ShopName = Shop.ShopAccount; return t; } // 处理上传失败图片 var failedSpecMapsStr = imageSpecMapsObj?["failed_map"]?.ToString(); if (!string.IsNullOrEmpty(failedSpecMapsStr) && failedSpecMapsStr != "{}" && imageSpecMapsRetryTimes < 5) { Thread.Sleep(1000); imageSpecMapsRetryTimes++; goto imageSpecMapsRetry; } var specStrx = BaseRegex.GetMatchMaxRegexString(ref imageSpecMaps, @"""success_map"":({[\w\W]+?})}"); var specmaps = BaseRegex.GetMatchRegex(ref specStrx, @"""([\w\W]+?)"":\{""AuditStatus""[\w\W]+?\}"); Dictionary specDic = new Dictionary(); for (int i = 0; specmaps != null && i < specmaps.Count; i++) { string imageItem = specmaps[i].Groups[0].Value; string rId = specmaps[i].Groups[1].Value; string urlImage = BaseRegex.GetStringJson(ref imageItem, "ByteUrl"); string oriImage = BaseRegex.GetStringJson(ref imageItem, "OriginUrl"); int index = requestList.FindIndex(s => s == long.Parse(rId)); if (!specDic.ContainsKey(index)) specDic.Add(index, urlImage); } var speclst = specDic.OrderBy(o => o.Key).ToList(); for (int i = 0; i < speclst.Count; i++) { string urlImage = speclst[i].Value; picCount++; pCount++; picStr += urlImage + ","; } if (!string.IsNullOrEmpty(picStr)) dictionary["spec_pic"] = picStr.Trim(','); //if (pCount> 44) // 50张图-5主图-1张详情图 //{ // dictionary.Remove("spec_pic"); // picCount = picCount - pCount; //} List propList = new List(); int sum = 1; if (string.IsNullOrEmpty(specimg)) { for (int i = p.Props.Count - 1; i > -1; i--) { for (int j = 0; j < p.Props[i].Values.Count; j++) { propList.Add(p.Props[i].name + ":" + p.Props[i].Values[j].name.Replace("(", "(").Replace(")", ")")); } sum = sum * p.Props[i].Values.Count; } } else { for (int i = 0; i < p.Props.Count; i++) { for (int j = 0; j < p.Props[i].Values.Count; j++) { propList.Add(p.Props[i].name + ":" + p.Props[i].Values[j].name.Replace("(", "(").Replace(")", ")")); } sum = sum * p.Props[i].Values.Count; } } if (speclist.Count < sum) { int maxCount = p.Props.Count; List arr = new List(); string standardPropName1 = p.Props[0].name; if (string.IsNullOrEmpty(specimg)) standardPropName1 = p.Props[1].name; string standardPropName2 = ""; string standardPropName3 = ""; List specSkuList = new List(); for (int i = 0; i < propList.Count; i++) { arr.Clear(); var propItem1 = propList[i].Replace("(", "(").Replace(")", ")").Replace(" ", ""); string propName1 = propItem1.Split(':')[0]; if (propName1 != standardPropName1) continue; if (p.Props.Count == 1) { specSkuList.Add(propItem1); } for (int j = 0; p.Props.Count > 1 && j < propList.Count; j++) { var propItem2 = propList[j].Replace("(", "(").Replace(")", ")").Replace(" ", ""); string propName2 = propItem2.Split(':')[0]; if (propName2 == standardPropName1) continue; if (standardPropName2 == "") standardPropName2 = propName2; if (propName2 != standardPropName2) continue; if (p.Props.Count == 2) { specSkuList.Add(propItem1 + ";" + propItem2); } for (int k = 0; p.Props.Count > 2 && k < propList.Count; k++) { var propItem3 = propList[k].Replace("(", "(").Replace(")", ")").Replace(" ", ""); string propName3 = propItem3.Split(':')[0]; if (propName3 == standardPropName1 || propName3 == standardPropName2) continue; if (standardPropName3 == "") standardPropName3 = propName3; if (propName3 != standardPropName3) continue; specSkuList.Add(propItem1 + ";" + propItem2 + ";" + propItem3); } } } foreach (var specname in specSkuList) { bool hasValue = p.SkuMaps.Exists(r => r.name.Replace("(", "(").Replace(")", ")").Replace(" ", "").Trim(';') == specname); if (hasValue) continue; spec_prices spec_prices = new spec_prices(); spec_prices.code = ""; spec_prices.price = (long)maxPriceNew; spec_prices.stock_num = 0; spec_prices.outer_sku_id = ""; spec_prices.picurl = ""; string[] specs = specname.Split(';'); spec_prices.spec_detail_name1 = specs[0].Split(':')[1]; if (specs.Length > 1) spec_prices.spec_detail_name2 = specs[1].Split(':')[1]; if (specs.Length > 2) spec_prices.spec_detail_name3 = specs[2].Split(':')[1]; speclist.Add(spec_prices); } } if (productDelayType == "3" || productDelayType == "4") { List specListTemp = new List(); foreach (var spec in speclist) { // 现货发货规格 if (productDelayType == "3") { var specx = new spec_prices() { code = spec.code, outer_sku_id = spec.outer_sku_id == "" ? "" : spec.outer_sku_id + "1", picurl = spec.picurl, price = spec.price, spec_detail_name1 = spec.spec_detail_name1, spec_detail_name2 = spec.spec_detail_name2, spec_detail_name3 = spec.spec_detail_name3, step_stock_num = spec.step_stock_num, stock_num = spec.stock_num, }; if (string.IsNullOrEmpty(specx.spec_detail_name2)) specx.spec_detail_name2 = newPreSendDayString; else specx.spec_detail_name3 = newPreSendDayString; if (!specListTemp.Any(s => s.spec_detail_name1 == specx.spec_detail_name1 && s.spec_detail_name2 == specx.spec_detail_name2 && s.spec_detail_name3 == specx.spec_detail_name3)) { specListTemp.Add(specx); } } // 新预售发货规格 if (string.IsNullOrEmpty(spec.spec_detail_name2)) spec.spec_detail_name2 = newPreTime; else spec.spec_detail_name3 = newPreTime; if (!specListTemp.Any(s => s.spec_detail_name1 == spec.spec_detail_name1 && s.spec_detail_name2 == spec.spec_detail_name2 && s.spec_detail_name3 == spec.spec_detail_name3)) { specListTemp.Add(spec); } } speclist = specListTemp; } string specStr = ""; StringBuilder stringBuilder = null; List> dicList = new List>(); for (int i = 0; i < speclist.Count; i++) { var specItem = speclist[i]; IDictionary dictionary2 = new Dictionary(); dictionary2.Add("spec_detail_name1", specItem.spec_detail_name1); dictionary2.Add("spec_detail_name2", specItem.spec_detail_name2 == null ? "" : specItem.spec_detail_name2); dictionary2.Add("spec_detail_name3", specItem.spec_detail_name3 == null ? "" : specItem.spec_detail_name3); dictionary2.Add("stock_num", specItem.stock_num.ToString()); dictionary2.Add("price", specItem.price.ToString()); dictionary2.Add("code", specItem.code); dictionary2.Add("step_stock_num", "0"); //dictionary2.Add("step_stock_num", (specItem.stock_num-1).ToString()); dicList.Add(dictionary2); stringBuilder = new StringBuilder(); foreach (string current in dictionary2.Keys) { if (current.ToString().Trim() == "stock_num" || current.ToString().Trim() == "price" || current.ToString().Trim() == "step_stock_num") { stringBuilder.AppendFormat((stringBuilder.Length > 0) ? ",\\\"{0}\\\":{1}" : "\\\"{0}\\\":{1}", current, dictionary2[current].ToString().Replace(" ", "")); } else { stringBuilder.AppendFormat((stringBuilder.Length > 0) ? ",\\\"{0}\\\":\\\"{1}\\\"" : "\\\"{0}\\\":\\\"{1}\\\"", current, dictionary2[current].ToString().Replace(" ", "")); } } string str = "{" + stringBuilder.ToString() + "}"; if (specStr.Trim() != "") { specStr += ","; } specStr += str; } specStr = "[" + specStr + "]"; var specStr1 = JsonHelper.SerializeObject(dicList); //sku详情 dictionary.Add("spec_prices", specStr); // 详情图 内容图 if (string.IsNullOrEmpty(p.content)) { } noticeHandler(p.from_id + ":正在上传内容图片"); Thread.Sleep(Randomx.GetId(500, 1500) + UploadProductBLL.ids.Count * 100); List contentTempList = p.content.Split(new string[] { "
" }, StringSplitOptions.RemoveEmptyEntries)?.ToList(); var contentTemp = ""; if (contentTempList.Count > 0) contentTemp = contentTempList[Randomx.GetId(contentTempList.Count)]; string contentImage = ""; var m = BaseRegex.GetMatchRegex(ref contentTemp, @"]*?src=[""'](.*?)[""']"); if (m.Count == 0) m = BaseRegex.GetMatchRegex(ref contentTemp, @"]*?>(.*?)"); if (m.Count == 0) m = BaseRegex.GetMatchRegex(ref contentTemp, @"]+?>(.*?)"); string imageDesPic = ""; List desc_request_id_List = new List(); for (int j = 0; j < m.Count; j++) { // 删除第一张详情图 内容图 if (j == 0 && IsDelFirstContentPic) { if (m.Count == 1) { t.Message = "至少需要1张内容图"; noticeHandler("至少需要1张内容图:" + t.FromId + ":" + t.Message); return t; } continue; } string urlImg = m[j].Groups[1].Value.Replace(".src", ""); if (picCount >= 50) break; if (string.IsNullOrEmpty(urlImg)) { urlImg = m[j].Groups[1].Value.Replace(".src", ""); } if (!string.IsNullOrEmpty(imageDesPic)) { imageDesPic += ","; } string tid = Md5Base.GetMd5(p.name).Substring(8, 16) + Randomx.GetId(2000); long request_id = Randomx.GetId(2000000000); desc_request_id_List.Add(request_id); imageDesPic += "{\\\"request_id\\\":" + request_id + ",\\\"folder_id\\\":\\\"" + folderId + "\\\",\\\"material_type\\\":\\\"photo\\\",\\\"name\\\":\\\"" + tid + "\\\",\\\"url\\\":\\\"" + urlImg + "\\\"}"; } int imageDesMapsRetryTimes = 0; imageDesMapsRetry: string imageDesMaps = BatchUploadImageSync(Shop, "[" + imageDesPic + "]"); if (imageDesMaps != null && imageDesMaps.Contains("素材库容量不足") && imageDesMapsRetryTimes < 5) { var folderResult = new UploadMaterialBLL().DelOldestApiMaterialFolder(Shop); if (folderResult) { imageDesMapsRetryTimes++; goto imageDesMapsRetry; } t.Message = "素材库容量不足"; t.ShopName = Shop.ShopAccount; return t; } var imageDesMapsObj = JsonHelper.JObjectParse(imageDesMaps)?["data"]; if (imageDesMapsObj == null || imageDesMapsObj["success_map"] == null) { t.Message = "内容图Json格式错误"; t.ShopName = Shop.ShopAccount; return t; } // todo 处理上传失败图片 var failedDesMapStr = imageDesMapsObj["failed_map"]?.ToString(); if (!string.IsNullOrEmpty(failedDesMapStr) && failedDesMapStr != "{}" && imageDesMapsRetryTimes < 5) { Thread.Sleep(1000); imageDesMapsRetryTimes++; goto imageDesMapsRetry; } for (int i = 0; i < desc_request_id_List.Count(); i++) { string urlImage = imageDesMapsObj["success_map"]?[desc_request_id_List[i].ToString()]?["ByteUrl"]?.ToString(); if (string.IsNullOrEmpty(urlImage)) continue; if (picCount >= 50) break; picCount++; if (contentImage.Trim() != "") { contentImage += "|"; } contentImage += urlImage; } //商品描述,目前只支持图片。多张图片用 "|" 分开 dictionary.Add("description", contentImage); if (beforPrice == 0) beforPrice = 2; //划线价 市场价 dictionary.Add("market_price", (maxPriceNew * beforPrice).ToString()); //售价,单位分 dictionary.Add("discount_price", (minPriceNew).ToString()); //减库存类型:1-拍下减库存 2-付款减库存 dictionary.Add("reduce_type", "2"); //重量 dictionary.Add("weight", "1"); //重量单位,0-kg, 1-g dictionary.Add("weight_unit", "1"); dictionary.Add("maximum_per_order", "5"); dictionary.Add("limit_per_buyer", "99"); dictionary.Add("minimum_per_order", "1"); //dictionary.Add("remark", "您好kkkkkkkkkkkkk"); dictionary["presell_type"] = productDelayType; if (productDelayType == "1") { dictionary["presell_delay"] = UploadProductBLL.endDay; dictionary["presell_end_time"] = UploadProductBLL.preEndTime; dictionary["delivery_delay_day"] = UploadProductBLL.sendDay; } else { dictionary["delivery_delay_day"] = UploadProductBLL.sendDay; //dictionary.Add("presell_delay", UploadProductBLL.endDay); //商品时效SKU GTM对接方案20220222 presell_config_level 2 现货+预售 3 新预售 if (productDelayType == "3") { dictionary["presell_config_level"] = "2"; dictionary["presell_type"] = "1"; } else if (productDelayType == "4") { dictionary["presell_config_level"] = "3"; dictionary["presell_type"] = "1"; } } // 商家推荐语 //dictionary.Add("recommend_remark", "78888"); dictionary.Add("recommend_remark", recommend_remark); // 是否支持7天无理由,0不支持,1支持,2支持(拆封后不支持) dictionary.Add("supply_7day_return", supply_7day_return); // 客服电话号码 if (!string.IsNullOrEmpty(UploadProductBLL.phone)) dictionary.Add("mobile", UploadProductBLL.phone); // 品牌资质 //dictionary.Add("brand_id", "0"); //dictionary.Add("brand_id", "596120136"); // 相关资质文件 在净化数据中获取并填写系统资质列表 //"quality_list": "[{\"quality_key\":\"1\",\"quality_name\":\"进货凭证1\",\"quality_attachments\":[{\"media_type\":1,\"url\":\"http://img.alicdn.com/imgextra/i1/729*****3055/TB2FG*****uNjy0FdXXbDnVXa_!!729*****3055.jpg\"},{\"media_type\":1,\"url\":\"http://img.alicdn.com/imgextra/i1/72*****63055/TB2FG*****dXXbDnVXa_!!72*****3055.jpg\"}]},{\"quality_key\":\"2\",\"quality_name\":\"进货凭证2\",\"quality_attachments\":[{\"media_type\":1,\"url\":\"http://img.alicdn.com/imgextra/i1/72*****863055/TB2FG49iuO*****0FdXXbDnVXa_!!7298*****3055.jpg\"}]}]", if (p != null && p.qualifications != null && p.qualifications.Count > 0) { List quality_list = new List(); foreach (var q in p.qualifications) { var quality_attachments = new List(); foreach (var qa in q.quality_attachments) { var newQA = new quality_attachment() { media_type = qa.media_type, url = qa.url.Replace("https:", "http:") }; if (!string.IsNullOrEmpty(newQA.url) && qa.media_type == 1) { // 资质图片上传 暂时不需要使用,抖音会自己抓取外网图片 //string tid = Md5Base.GetMd5(p.name).Substring(8, 16) + Randomx.GetId(2000); //string byte_url = UploadImageSync(Shop, folderId, newQA.url, tid); //if (!byte_url.Contains("\"code\":10000")) //{ // byte_url = UploadImageSync(Shop, folderId, newQA.url, tid); //} //if (byte_url.Contains("\"code\":10000")) //{ // newQA.url = BaseRegex.GetStringJson(ref byte_url, "byte_url"); //} } quality_attachments.Add(newQA); } quality_list.Add(new quality { quality_attachments = quality_attachments, quality_key = q.quality_key, quality_name = q.quality_name }); } dictionary["quality_list"] = JsonHelper.SerializeObject(quality_list).Replace("\"", "\\\""); } // false仅保存,true保存+提审 if (UploadProductBLL.isDraft) dictionary.Add("commit", "false"); else dictionary.Add("commit", "true"); if (UploadProductBLL.isSaveToOffLine) dictionary["start_sale_type"] = "1"; // 重试及异常 //\"message\":\"商品创建失败: 发货模式暂不支持阶梯发货\",\"msg\":\"其他异常\" bool isRetry_图片转链失败 = false; bool isRetry_请上传生产企业名称 = false; bool isRetry_包装标签图 = false; bool isRetry_图片长宽比 = false; bool isRetry_创建审核任务失败 = false; bool isRetry_7天无理由 = false; bool isRetry_系统繁忙 = false; bool isRetry_Empty = false; retry: Thread.Sleep(1000); DouyinApi api = new DouyinApi(Shop); if (Shop.ShopAccount == "权益服务齐全的专营店") { dictionary.Remove("brand_id"); // = "2122428529"; dictionary["standard_brand_id"] = "2122428529"; } //api.JsonData["product_format_new"] = "{\\\"1687\\\":[{\\\"value\\\":596120136,\\\"name\\\":\\\"无品牌\\\"}],\\\"2592\\\":[{\\\"value\\\":2022,\\\"name\\\":\\\"韩版\\\"}],\\\"539\\\":[{\\\"value\\\":11942,\\\"name\\\":\\\"圆头\\\"}],\\\"883\\\":[{\\\"value\\\":18537,\\\"name\\\":\\\"猪皮(革)\\\"}],\\\"1239\\\":[{\\\"value\\\":38467,\\\"name\\\":\\\"低跟\\\"}],\\\"3029\\\":[{\\\"value\\\":13142,\\\"name\\\":\\\"EVA\\\"}],\\\"2313\\\":[{\\\"value\\\":0,\\\"name\\\":\\\"1\\\"}],\\\"1869\\\":[{\\\"value\\\":10089,\\\"name\\\":\\\"纯色\\\"}],\\\"1766\\\":[{\\\"value\\\":19637,\\\"name\\\":\\\"交叉绑带\\\"}],\\\"1244\\\":[{\\\"value\\\":29717,\\\"name\\\":\\\"松糕底\\\"}],\\\"1865\\\":[{\\\"value\\\":32022,\\\"name\\\":\\\"短筒\\\"}],\\\"2182\\\":[{\\\"value\\\":7340,\\\"name\\\":\\\"前系带\\\"}]}"; string html = ""; if (isEdit) { dictionary["product_id"] = "3548157790335946701"; noticeHandler(p.from_id + ":正在编辑商品"); api.JsonData = dictionary; html = api.GetProductEdit(); } else { noticeHandler(p.from_id + ":正在上传商品"); api.JsonData = dictionary; var jsonStr = JsonHelper.SerializeObject(api.JsonData); html = api.GetAdd(); } if (html.Contains("图片转链失败") && !isRetry_图片转链失败) { isRetry_图片转链失败 = true; goto retry; } if (html.Contains("请上传生产企业名称") && !isRetry_请上传生产企业名称) { Thread.Sleep(1000); isRetry_请上传生产企业名称 = true; //var productFormat = ""; //if (dictionary.Keys.Contains("product_format")) // productFormat = dictionary["product_format"]; //productFormat += "^生产企业名称|" + (string.IsNullOrEmpty(p.from_shop_name) ? "工厂店" : p.from_shop_name); //dictionary["product_format"] = productFormat.Trim('^'); var cateProp = propResult.data.data.Find(pr => pr.property_name == "生产企业名称"); if (cateProp != null) { cateProp.required = true; property = new UploadPropertyBLL().GetCatePropertyAnalysis(propResult, Shop, p); if (!string.IsNullOrEmpty(property)) { dictionary["product_format_new"] = property; } } goto retry; } if (html.Contains("包装标签图") && !isRetry_包装标签图) { isRetry_包装标签图 = true; api.JsonData.Add("quality_list", "[{\\\"quality_key\\\":\\\"6966228537426575660\\\",\\\"quality_name\\\":\\\"包装标签图\\\",\\\"quality_attachments\\\":[{\\\"media_type\\\":1,\\\"url\\\":\\\"" + baseImageUrl + "\\\"}]}]"); goto retry; } if ((html.Contains("商品创建失败: 运费模板权限错误") || html.Contains("运费模板不存在")) && Shop.ExpressId != 0) { Shop.ExpressId = 0; dictionary["freight_id"] = "0"; goto retry; } if (html.Contains("图片长宽比非1:1") && !isRetry_图片长宽比) { isRetry_图片长宽比 = true; dictionary.Remove("pic"); mainImages = ""; var images1 = p.Images.Distinct().ToList(); for (int i = 0; i < images1.Count; i++) { string urlImage = images1[i]; if (!urlImage.Contains("http")) { urlImage = "https:" + images1[i]; } if (i > 4) { break; } byte[] img; GetPostTaobaoHtml.DownLoadImage(urlImage, out img); ImageCut.HandleImage(ref img, false); ImageBuild ib = new ImageBuild(img); img = ib.BuildNewSize(640, 640, 100); string fileName = urlImage.Substring(urlImage.LastIndexOf("/") + 1); string url = "https://fxg.jinritemai.com/common/img/batchupload"; string refere = "https://fxg.jinritemai.com/ffa/g/create"; string upImage = GetPostTaobaoHtml.HttpPostData(url, fileName, img, refere, Shop.Cookies); urlImage = BaseRegex.GetMatchRegexString(upImage, "\"data\":\\[\"([\\w\\W]+?)\"\\],"); if (mainImages.Trim() != "") { mainImages += "|"; } mainImages += urlImage; } if (isRandomMainImage) mainImages = GetRandomMainImage(mainImages); //商品轮播图 dictionary.Add("pic", mainImages); goto retry; } if (html.Contains("创建审核任务失败") && !isRetry_创建审核任务失败) { isRetry_创建审核任务失败 = true; Thread.Sleep(3000); goto retry; } if (html.Contains("天无理由")) { isRetry_7天无理由 = true; // 是否支持7天无理由,0不支持,1支持,2支持(拆封后不支持) dictionary["supply_7day_return"] = "1"; Thread.Sleep(3000); goto retry; } if (html.Contains("系统繁忙") && !isRetry_系统繁忙) { isRetry_系统繁忙 = true; Thread.Sleep(15000); goto retry; } if (string.IsNullOrEmpty(html) && !isRetry_Empty) { isRetry_Empty = true; Thread.Sleep(5000); goto retry; } long product_id = BaseRegex.GetLongJson(ref html, "product_id"); string message = BaseRegex.GetStringJson(ref html, "msg"); string sub_msg = BaseRegex.GetStringJson(ref html, "sub_msg"); if (product_id > 0) // 保存上家、产品ID到数据表中 { noticeHandler(p.from_id + ":正在编辑其他信息"); string prev = GetPrev(t.FromType); SetUpProduct(product_id, prev + t.FromId.ToString(), true); t.GoodsId = product_id; t.Titlte = p.name; t.Price = minPriceNew; t.ShopName = Shop.ShopAccount; t.Message = "提交成功"; noticeHandler(t.GoodsId + ":" + t.Message + " 来源Id:" + p.from_id); Shop.UploadCount++; if (Shop.PayStatus != 1) { Shop.TrialUploadCount++; NaiBa.Util.ConcurrentList shopLoginListCopy = JsonHelper.DeserializeJsonToObject>(JsonHelper.SerializeObject(GlobalConfig.ShopLoginList)); shopLoginListCopy.AddRange(GlobalConfig.DouShopLoginOtherUserShopList); // 替换掉密码,cookie等敏感参数 foreach (var shop in shopLoginListCopy) { shop.Password = ""; shop.Cookies = ""; } NaiBa.Util.Helper.ConfigHelper.SaveConfig("dou_shop_login", shopLoginListCopy); } return t; } else { if (t.Message != null && (message.Contains("因为店铺受到处罚,限制发品") || message.Contains("当前店铺已停业整顿,恢复营业后可支持创建商品"))) Shop.CanUpload = false; t.ShopName = Shop.ShopAccount; noticeHandler(p.from_id + ":提交失败,请查看提交状态"); // 将提交失败信息添加到服务器 string url = BaseClass.LoginApiUrl + "?obj=douyin/upload&act=add_upload_log"; string data = "&product_id=" + t.FromId + "&source_id=" + GetPrev(t.FromType).Trim('-') + "&cat_id=" + catId + "&message=" + HttpUtility.UrlEncode((message + "^" + sub_msg).Trim('^'), Encoding.UTF8); string param = UserLogin.GetSignaturex(Shop.ShopId, Shop.ShopAccount) + data; string result = GetHtml.PostUtf8(url, param); } if (!string.IsNullOrEmpty(sub_msg)) t.Message = sub_msg; else if (!string.IsNullOrEmpty(message)) t.Message = message; else t.Message = "提交失败"; return t; //UploadProductBLL.ProductTemp.Add(t); } public string GetPrev(string fromType) { string prev = ""; if (fromType == "拼多多") { prev = "pdd-"; } if (fromType == "淘宝") { prev = "tb-"; } if (fromType == "阿里") { prev = "al-"; } if (fromType == "抖音") { prev = "dy-"; } if (fromType == "京喜") { prev = "jx-"; } return prev; } public List GetTenImages(List imageList) { while (imageList.Count > 10) { imageList.RemoveAt(Randomx.GetId(imageList.Count)); } return imageList; } public string GetRandomMainImage(string imageStrOld) { string imageNew = ""; if (imageStrOld == null) imageStrOld = ""; List imageList = imageStrOld.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (imageList != null && imageList.Count > 1) { int num = Randomx.GetId(imageList.Count); var imageStr = imageList[num]; imageList.RemoveAt(num); imageList.Insert(0, imageStr); imageNew = string.Join("|", imageList); } return imageNew; } public bool GetUpProduct(long product_id) { string urlx = BaseClass.LoginApiUrl + "?obj=upshopid/upid_dd&act=get"; string datax = "&pid=" + product_id + "&table=" + (product_id % 1024); string htmlx = GetHtml.PostUtf8(urlx, UserLogin.GetSignaturex(Shop.ShopId, Shop.ShopAccount) + datax); if (!string.IsNullOrEmpty(htmlx)) return true; else return false; } public bool SetUpProduct(long pid, string upProductId, bool add = false) { string upIdNumber = BaseRegex.GetMatchRegex(ref upProductId, "\\d{5,20}")?[0]?.Groups[0]?.Value; long up_table = 0; if (!string.IsNullOrEmpty(upIdNumber)) { up_table = upIdNumber.ParseToLong(); } string url = BaseClass.LoginApiUrl + "?obj=upshopid/upid_dd&act=insert"; string data = "&pid=" + pid + "&up_id=" + upProductId + "&table=" + (pid % 1024) + "&up_table=" + (up_table % 1024); string param = UserLogin.GetSignaturex(Shop.ShopId, Shop.ShopAccount) + data; string html = GetHtml.PostUtf8(url, param); if (html != "ok") { Thread.Sleep(15 * 1000); html = GetHtml.PostUtf8(url, UserLogin.GetSignaturex(Shop.ShopId, Shop.ShopAccount) + data); } if (html != "ok") { Thread.Sleep(15 * 1000); html = GetHtml.PostUtf8(url, UserLogin.GetSignaturex(Shop.ShopId, Shop.ShopAccount) + data); } if (html != "ok") { Thread.Sleep(15 * 1000); LogSave.Add(Name, "服务器记录" + pid + "上家ID异常,请联系客服"); } return html == "ok"; } public static long GetLong(string url) { if (string.IsNullOrEmpty(url)) return 0; return Convert.ToInt64(BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(Encoding.Default.GetBytes(url)), 4, 8).Replace("-", ""), 16); } public int WhitePriceBuild(decimal price, decimal addPrice, decimal postage, decimal postFree) { bool randPrice = false; decimal addPricex = addPrice; decimal free = postage + postFree; //UploadPinduoduoMain.Postage + postFree; int p = (int)(price * (100 + addPricex) + free * 100); if (randPrice) p -= Randomx.GetId(0, 10); return p; } public static string getProductUpdateRule(string catId, ShopLoginInfo Shop) { DouyinApi api = new DouyinApi(Shop); api.JsonData = new Dictionary(); api.JsonData.Add("category_id", catId.ToString()); string updateRule = api.GetResultUpdateRule(); return updateRule; } public static string CreateImageFolder(ShopLoginInfo shop) { DouyinApi api = new DouyinApi(shop); api.JsonData = new Dictionary(); api.JsonData.Add("name", DateTime.Now.ToString("yyyy-MM-dd")); api.JsonData.Add("type", "0"); string html = api.GetCreateFolder(); return html; } public static string SearchFolder(ShopLoginInfo shop) { DouyinApi api = new DouyinApi(shop); api.JsonData = new Dictionary(); api.JsonData.Add("name", DateTime.Now.ToString("yyyy-MM-dd")); api.JsonData.Add("order_by", "1"); api.JsonData.Add("page_num", "1"); api.JsonData.Add("page_size", "10"); string html = api.GetSearchFolder(); return html; } public static string UploadImageSync(ShopLoginInfo shop, string folder_id, string url, string title) { DouyinApi api = new DouyinApi(shop); api.JsonData = new Dictionary(); api.JsonData.Add("folder_id", folder_id); api.JsonData.Add("url", url); api.JsonData.Add("material_name", title); api.JsonData.Add("need_distinct", "true"); string html = api.GetUploadImageSync(); return html; } public static string BatchUploadImageSync(ShopLoginInfo shop, string materials) { DouyinApi api = new DouyinApi(shop); api.JsonData = new Dictionary(); api.JsonData.Add("materials", materials); api.JsonData.Add("need_distinct", "true"); string html = api.GetBatchUploadImageSync(); return html; } /// /// 获取品牌Id /// public static List GetBrandList(ShopLoginInfo shop) { DouyinApi apiBrand = new DouyinApi(shop); string brandHtml = apiBrand.shopBrandList(); if (brandHtml.Contains("\"code\":10000") && brandHtml.Contains("\"data\":[")) { return JsonHelper.DeserializeJsonToList(JsonHelper.SerializeObject(JObject.Parse(brandHtml)["data"])); } return new List(); } } }