using Api.Framework; using Api.Framework.Cps; using Api.Framework.Enums; using Api.Framework.Model; using Api.Framework.SDK; using Api.Framework.Tools; using Chat.Framework.WXSdk; using Chat.Framework.WXSdk.Implement; using CsharpHttpHelper; using ProductClient.Entitys; using ProductClient.Properties; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using static Api.Framework.Tools.TBHelper.TbAnalysis; namespace ProductClient { class MonitorThread : TimerTask { private long count; private bool IsRun = false; public override void Run(object state, bool timedOut) { try { count++; #region web接口检测 if (count % 5 == 0) { if (IsRun) return; IsRun = true; try { var http = new HttpHelper(); //http://item.sync.api.52cmg.cn/task.do?method=getCircle&lastId=@lastid&r=@r var text = string.Empty; Dictionary result = null; try { if (Class1.Config.historyId.Count >= 100) { Class1.Config.historyId.RemoveRange(0, Class1.Config.historyId.Count - 20); Util.Save(Class1.Config); } if (!Class1.Config.historyId.Contains(Class1.Config.SignId)) { text = http.GetHtml(HttpExtend.GetItem(http, Resources.ProductApi.Replace("@lastid", Class1.Config.SignId.ToString()).Replace("@r", HttpExtend.GetTimeStamp()))).Html; result = HttpExtend.JsonToDictionary(text); } } catch (Exception) { return; } if (result != null && result.ContainsKey("Code")) { var code = result["Code"].ToString(); //if (code == "-1") return; //正常数据 if (code == "0") { //检测是否在线 var clients = Chat.Framework.ChatClient.WXClient.Values.ToList().Where(f => (f.WeixinType == WeixinType.Grpc微信 || f.WeixinType == WeixinType.Hook微信) && f.Status == WxStatus.在线).ToList(); if (clients.Count == 0) return; if (result.ContainsKey("Message")) { var message = result["Message"] as Dictionary; if (message.ContainsKey("lastId")) { Class1.Config.historyId.Add(Class1.Config.SignId); Class1.Config.SignId = long.Parse(message["lastId"].ToString()); Util.Save(Class1.Config); } string convertLink = string.Empty; //转链后 string compositeQRCode = string.Empty;//合成的二维码图片 string objectDesc = string.Empty; //正文 string comment = string.Empty; //评语 string quanUrl = string.Empty; //券链接 string itemUrl = string.Empty; //商品连接 var appendQrcode = false; //是否合成优惠券图片 CpsType cps = CpsType.京东联盟; #region 获取正文内容并删除正文中的地址 if (message.ContainsKey("circle")) { objectDesc = message["circle"].ToString();//主内容部分 if (string.IsNullOrWhiteSpace(objectDesc)) { EventClient.OnEvent(this, $"未检测到要转发的正文数据,操作终止"); return; } //处理用户朋友圈中的地址信息(有就删除) var reg = Regex.Match(objectDesc, @"(?<地址信息>\)"); if (reg.Success) objectDesc = objectDesc.Replace(reg.Groups["地址信息"].Value, string.Empty); } #endregion #region 获取评语 if (message.ContainsKey("comment")) comment = message["comment"].ToString(); //评论内容 #endregion var isItem = message.ContainsKey("isItem") && message["isItem"].ToString().ToLower() == "true"; //是否为商品 //为商品获取去商品连接和优惠券链接 if (isItem) { if (Class1.Config.Monitor_Interval != 0) { if (Class1.Config.LastSendTime == DateTime.MinValue || (Class1.Config.LastSendTime.AddMinutes(Class1.Config.Monitor_Interval) <= DateTime.Now)) { } else return; } appendQrcode = message.ContainsKey("appendQrcode") && message["appendQrcode"].ToString().ToLower() == "true"; if (message.ContainsKey("itemUrl"))//获取宝贝连接 itemUrl = message["itemUrl"].ToString(); if (message.ContainsKey("quanUrl"))//获取优惠券链接 quanUrl = message["quanUrl"].ToString(); } else { Class1.Config.LastSendTime = DateTime.MinValue; } #region 评语不为空,判断评语中是否包含变量 if (isItem && (appendQrcode || (!string.IsNullOrWhiteSpace(comment) && comment.Contains(Resources.BuyAddress)) || !string.IsNullOrWhiteSpace(comment))) { bool isTB = false; try { convertLink = AlimamaConvertLink(itemUrl, quanUrl, appendQrcode, out compositeQRCode);//阿里妈妈 isTB = true; } catch (Exception ex) { if (!ex.Message.StartsWith("@")) throw ex; try { convertLink = PinDuoDuoConvertLink(itemUrl, appendQrcode, out compositeQRCode);//多多进宝 } catch (Exception ex_) { if (!ex_.Message.StartsWith("@")) throw ex_; try { convertLink = JingDongConvertLink(itemUrl, appendQrcode, out compositeQRCode);//京东联盟 } catch (Exception) { } } } if (string.IsNullOrWhiteSpace(convertLink)) return; //处理转链,替换变量 { #region 朋友圈内容中追加图片 if (!string.IsNullOrWhiteSpace(compositeQRCode)) { StringBuilder sb = new StringBuilder(); sb.Append(""); sb.Append("" + Tools.GenerateRandomCode(20) + ""); sb.Append("2"); sb.Append(""); sb.Append(""); sb.Append("0"); sb.Append("[图片=" + compositeQRCode + "]"); sb.Append("[图片=" + compositeQRCode + "]"); sb.Append(""); sb.Append(""); var index = objectDesc.IndexOf(""); if (index != -1) objectDesc = objectDesc.Insert(index, sb.ToString()); } #endregion string address = string.Copy(convertLink); if (isTB == true && !Class1.Config.isPyTkl && comment.Contains(Resources.BuyAddress)) { convertLink = ZJYUrl; } comment = comment.Replace(Resources.BuyAddress, convertLink).Replace(Resources.TKLBuyAddress, address); } } #endregion _ExecuteSend(objectDesc, comment); } } } } catch (Exception ex) { EventClient.OnEvent(this, $"代运营朋友圈 - web接口:{ex.Message}"); } finally { IsRun = false; } } #endregion } catch (Exception ex) { EventClient.OnEvent(this, $"代运营朋友圈:{ex.Message}\r\n{ex.StackTrace}"); } } private string ZJYUrl = string.Empty; /// /// 阿里妈妈转连接 /// /// private string AlimamaConvertLink(string itemUrl, string quanUrl, bool appendQrcode, out string compositeQRCode) { compositeQRCode = string.Empty; ZJYUrl = string.Empty; var session = ApiClient.GetSession(); if (string.IsNullOrWhiteSpace(Class1.Config.tbPid)) throw new Exception("@未设置淘宝推广位,终止操作"); var reg = Regex.Match(Class1.Config.tbPid, @"mm_(?\d+)_(?\d+)_(?\d+)"); if (!reg.Success) throw new Exception($@"阿里妈妈推广位格式不正确"); var cpsname = reg.Groups["cpsname"].Value; var pid1 = reg.Groups["pid1"].Value; var pid2 = reg.Groups["pid2"].Value; var cps = new fl_cps_member() { username = cpsname, cpstype = CpsType.阿里妈妈, cookies = string.Empty, is_download = SwitchType.关闭, abnormal_tip = SwitchType.关闭, online = true, usernick = string.Empty }; AlimamaApi api = CpsClient.CreateAlimamaRequest(cps); if (api == null) throw new Exception("@创建阿里妈妈API请求失败,终止操作"); var tbAnalysis = new TBHelper.TbAnalysis(); var item_id = string.Empty; try { item_id = tbAnalysis.FindItemIdByUrlAndTklAndMkl(itemUrl, api, Class1.Config.tbPid.Split('_')); } catch (Exception) { throw new Exception($"@解析淘宝商品Id失败:{itemUrl}"); } //标题搜索和商品id搜索 if (string.IsNullOrEmpty(item_id)) throw new Exception($"@解析淘宝商品Id失败:{itemUrl}"); var title = string.Empty;//商品标题 #region 检测连接中是否包含优惠券信息 var activityId = string.Empty; if (quanUrl.Contains("uland.taobao")) { var _reg = Regex.Match(quanUrl, @"activityId=(?<活动ID>[A-Za-z0-9]+)"); if (_reg.Success) activityId = _reg.Groups["活动ID"].Value; } #endregion var turnItem = api.TurnItemId(item_id, activityId, pid2, pid1, "2", "", true); //淘口令的前/后符号有没有设置.有设置将替换掉 var tkl = tbAnalysis.ReplaceTklModifier(turnItem.BuyPass); ZJYUrl = api.ComposeTbClick(item_id, turnItem.ImageUrl, tkl, turnItem.BuyUrl, true, Class1.Config.tbPid, ApiClient.Setting.SystemConfig.ZjyComposeType == ComposeType.有推荐商品, (int)Class1.Config.dwzType, isCircleZjy: true); if (string.IsNullOrWhiteSpace(ZJYUrl)) throw new Exception("生成防屏蔽连接为空,终止操作"); if (appendQrcode) { compositeQRCode = ApiClient.GetQRImage(title, turnItem.Price.ToString("0.00"), turnItem.CouponPrice.ToString("0"), turnItem.UseCouponPrice.ToString("0.00"), turnItem.ImageUrl, ZJYUrl, Class1.Config.qrImageType); } return tkl; } /// /// 多多进宝转连接 /// /// private string PinDuoDuoConvertLink(string itemUrl, bool appendQrcode, out string compositeQRCode) { var goods_id = PDDHelper.GetPddGoodsID(itemUrl); if (string.IsNullOrWhiteSpace(goods_id)) throw new Exception("@解析拼多多商品Id失败,操作终止"); var session = ApiClient.GetSession(); if (string.IsNullOrWhiteSpace(Class1.Config.pddPid)) throw new Exception("未设置拼多多推广位,终止操作"); var reg = Regex.Match(Class1.Config.pddPid, @"(?\d+)_(\d+)"); if (!reg.Success) throw new Exception("拼多多推广位不符合格式,终止操作"); var cpsname = reg.Groups["cpsname"].ToString(); var adzone_pid = Class1.Config.pddPid; var cps = new fl_cps_member() { username = cpsname, usernick = string.Empty, cookies = string.Empty, cpstype = CpsType.多多进宝, abnormal_tip = SwitchType.关闭, is_download = SwitchType.关闭, online = true }; PinduoduoApi api = CpsClient.CreatePinduoduoRequest(cps); if (api == null) throw new Exception("创建多多进宝API请求失败,终止操作"); ArrayList goods_details = null; var isBind = false; var result = api.SendPinduoduo("pdd.ddk.oauth.member.authority.query", new { pid = adzone_pid }); if (result.ContainsKey("authority_query_response")) { var authority_query_response = result["authority_query_response"] as Dictionary; if (authority_query_response != null && authority_query_response.Count != 0) isBind = int.Parse(authority_query_response["bind"].ToString()) == 1;//1-已绑定;0-未绑定 } goods_details = PDDHelper.FindSendGuideGoodsInfo(api, adzone_pid, goods_id, isBind); //没有查到返利提示 if (goods_details == null || goods_details.Count == 0) throw new Exception("该商品无返利,操作终止"); foreach (var item in goods_details) { var temp = item as Dictionary; string mall_id = string.Empty; if (temp.ContainsKey("mall_id")) mall_id = temp["mall_id"].ToString(); var goods_sign = temp["goods_sign"].ToString(); var goods_name = (temp["goods_name"] ?? string.Empty).ToString().Replace("‮", "").Replace("<", "<").Replace(">", ">").Replace("&", "&").Replace(""", "\"").Replace(" ©", "©"); //获取商品标签 var goods_desc = (temp["goods_desc"] ?? string.Empty).ToString(); //商品描述 var goods_thumbnail_url = (temp["goods_thumbnail_url"] ?? string.Empty).ToString(); //商品主图 var min_group_price = Math.Round(temp["min_group_price"] == null ? 0 : (double.Parse(temp["min_group_price"].ToString()) / 100.00), 2); //最低价sku的拼团价,单位为分 //var min_normal_price = Math.Round(temp["min_normal_price"] == null ? 0 : (double.Parse(temp["min_normal_price"].ToString()) / 100.00), 2); //最低价sku的单买价,单位为分 var _coupon_discount = double.Parse((temp["coupon_discount"] ?? 0).ToString()); var coupon_discount = _coupon_discount == 0 ? 0 : Math.Round(_coupon_discount / 100.00, 2); //优惠券面额,单位为分 var pddHelper = new PDDHelper(); var manyShoppingUrl = pddHelper.GetShoppingUrl(api, new { p_id = adzone_pid, goods_sign_list = $"[\"{goods_sign}\"]", multi_group = true, generate_short_url = true, generate_weapp_webview = true, force_duo_id = true, generate_authority_url = !isBind, generate_schema_url = true }); if (appendQrcode) compositeQRCode = ApiClient.GetQRImage(goods_name, min_group_price.ToString(), coupon_discount.ToString(), ((decimal)min_group_price - (decimal)coupon_discount).ToString(), goods_thumbnail_url, manyShoppingUrl, Class1.Config.qrImageType, CpsType.多多进宝, goods_desc); else compositeQRCode = string.Empty; return manyShoppingUrl; } //EventClient.OnEvent(this, $"朋友圈代运营拼多多转链异常:{ex.Message} - {ex.StackTrace}"); compositeQRCode = string.Empty; return string.Empty; } /// /// 京东联盟转连接 /// /// private string JingDongConvertLink(string itemUrl, bool appendQrcode, out string compositeQRCode) { var itemId = JDHelper.GetJingdongItemId(itemUrl);//匹配京东链接获取京东宝贝ID if (string.IsNullOrEmpty(itemId)) throw new Exception($"@解析京东商品Id失败:{itemUrl}"); var session = ApiClient.GetSession(); //var adzone = session.FindAdzoneInfos().FirstOrDefault(f => f.custom_type == Resources.SoftwareType && f.alliance_id == (int)CpsType.京东联盟); //if (adzone == null) throw new Exception("未设置京东推广位,终止操作"); if (string.IsNullOrWhiteSpace(Class1.Config.jdPid)) throw new Exception("未设置京东推广位,终止操作"); var reg = Regex.Match(Class1.Config.jdPid, @"(?(?\d+)_\d+_(?\d+))_(?.+)"); if (!reg.Success) throw new Exception("推广位格式不正确"); var cpsname = reg.Groups["cpsname"].ToString(); var key = reg.Groups["key"].ToString(); //var pid = reg.Groups["pid"].ToString(); var positionId = reg.Groups["positionId"].ToString(); var cps = new fl_cps_member() { username = key, usernick = cpsname, cpstype = CpsType.京东联盟, online = true, cookies = string.Empty, abnormal_tip = SwitchType.关闭, is_download = SwitchType.关闭 }; //var cps = CpsClient.Members.FirstOrDefault(f => f.cpstype == CpsType.京东联盟 && f.username == adzone.adzone_pid_cps_name); //if (cps == null) throw new Exception("京东账号异常,终止操作"); var api = new JingdongApi(cps); if (api == null) throw new Exception("创建京东联盟API请求失败,终止操作"); var goodInfoResult = api.SendJingdong("jd.union.open.goods.query", new { goodsReqDTO = new { skuIds = new string[] { itemId } } }); var goodData = goodInfoResult.ConvertToObj(); if (goodData.data == null) throw new Exception("京东无返利信息"); foreach (Dictionary _goodinfo in goodData.data) { var goodinfo = _goodinfo.ConvertToObj(); goodinfo.skuName = goodinfo.skuName.Replace("‮", "").Replace("<", "<").Replace(">", ">").Replace("&", "&").Replace(""", "\"").Replace(" ©", "©"); if (goodinfo.commissionInfo.Count != 0)//有佣金 { var isJdSale = goodinfo.isJdSale == 0 ? false : true;//是否已是京东自营 double price = double.Parse(goodinfo.priceInfo["price"].ToString()); //商品价格 var commissionshare = decimal.Parse(goodinfo.commissionInfo["commissionShare"].ToString()) / 100m;//普通用户佣金比例 ,通用接口中的佣金比例 #region 这里主要是获取改商品的实际佣金比例,上面的佣金比例是通用的佣金比例,会不准一些 try { var goodResult = api.SendJingdong("jd.union.open.goods.promotiongoodsinfo.query", new { skuIds = itemId }); if (goodResult != null && goodResult.ContainsKey("data")) { var _goodData = goodResult["data"] as ArrayList; if (_goodData != null && _goodData.Count != 0) { foreach (Dictionary data in _goodData) { if (data.ContainsKey("commisionRatioWl")) { commissionshare = decimal.Parse(data["commisionRatioWl"].ToString()) / 100m; //接口中该商品的实际佣金,比较准一些, break; } } } } } catch (Exception) { } #endregion ItemPoint usecoupon_commfee = null;//普通用户 用优惠券后积分信息 //ItemPoint usecoupon_commfee_plus = null;//plus用户 用优惠券后积分信息 string couponlike = string.Empty; //优惠券链接 double discount = 0; //优惠券金额 if (goodinfo.couponInfo.Count != 0) { //goodinfo.couponInfo[0].couponList[0]; var couponList = goodinfo.couponInfo["couponList"] as ArrayList; if (couponList.Count != 0)//有优惠券 { foreach (Dictionary coupon in couponList) { var quota = double.Parse(coupon["quota"].ToString()); //券消费限额 if (quota > price) break;//优惠券面额大于商品单价时终止 discount = double.Parse(coupon["discount"].ToString()); couponlike = coupon["link"].ToString(); //优惠券链接 break;//TODO 这里难道有多个优惠券?先不管,直接获取第一个 } } } var buyshorturl = string.Empty; //转连后的地址 #region 转连(生成自己推广的链接 [有券链接(二合一)或无券链接]) Dictionary conversionlinkresult = null; //查询到的转换链接对象 //var positionId = adzone.adzone_pid.Substring(adzone.adzone_pid.LastIndexOf("_") + 1); if (string.IsNullOrWhiteSpace(couponlike)) { conversionlinkresult = api.SendJingdong("jd.union.open.promotion.byunionid.get", new { promotionCodeReq = new { materialId = $@"https://item.m.jd.com/product/{itemId}.html", positionId = positionId, unionId = cps.usernick } });//宝贝id 和 用户的目标推客的联盟id } else { try { conversionlinkresult = api.SendJingdong("jd.union.open.promotion.byunionid.get", new { promotionCodeReq = new { materialId = $@"https://item.m.jd.com/product/{itemId}.html", positionId = positionId, unionId = cps.usernick, couponUrl = couponlike } }); } catch (Exception) { conversionlinkresult = api.SendJingdong("jd.union.open.promotion.byunionid.get", new { promotionCodeReq = new { materialId = $@"https://item.m.jd.com/product/{itemId}.html", positionId = positionId, unionId = cps.usernick } });//宝贝id 和 用户的目标推客的联盟id couponlike = string.Empty; } } if (conversionlinkresult != null) { if (conversionlinkresult["code"].ToString() != "200") throw new Exception($"京东查询接口调用失败:{conversionlinkresult["message"].ToString()}");//抛出错误信息 if (conversionlinkresult.ContainsKey("data")) { var data = conversionlinkresult["data"] as Dictionary; if (data.ContainsKey("shortURL")) buyshorturl = data["shortURL"].ToString();//购买短连接 } if (string.IsNullOrWhiteSpace(buyshorturl)) throw new Exception("京东转链失败,请稍后重试"); } #endregion var imageList = goodinfo.imageInfo["imageList"] as ArrayList; string imageUrl = string.Empty; if (imageList.Count > 0) imageUrl = (imageList[0] as Dictionary)["url"].ToString(); //宝贝主图 if (appendQrcode) compositeQRCode = ApiClient.GetQRImage(goodinfo.skuName, price.ToString(), discount.ToString(), ((decimal)price - (decimal)discount).ToString(), imageUrl, buyshorturl, Class1.Config.qrImageType, CpsType.京东联盟); else compositeQRCode = string.Empty; return buyshorturl; } } //EventClient.OnEvent(this, $"朋友圈代运营京东转链异常:{ex.Message} - {ex.StackTrace}"); compositeQRCode = string.Empty; return string.Empty; } /// /// 执行发送任务 /// private void _ExecuteSend(string objectDesc, string comment) { try { if (string.IsNullOrWhiteSpace(objectDesc)) return; var clients = Chat.Framework.ChatClient.WXClient.Values.ToList().Where(f => (f.WeixinType == WeixinType.Grpc微信 || f.WeixinType == WeixinType.Hook微信) && f.Status == WxStatus.在线).ToList(); if (clients.Count != 0) { foreach (var _item in clients) { var item = _item; //Task.Run(() => //{ try { //objectDesc = Regex.Replace(objectDesc, @"videomd5=""(.{32})""", @"videomd5=""" + Util.GetMD5Hash(Guid.NewGuid().ToByteArray()) + @""""); //objectDesc = Regex.Replace(objectDesc, @"md5=""(.{32})""", @"md5=""" + Util.GetMD5Hash(Guid.NewGuid().ToByteArray()) + @""""); objectDesc = objectDesc.Replace("[活动口令]", Class1.Config.actionLink); var json = item.SendCircle(objectDesc);//发送朋友圈的主内容 if (string.IsNullOrWhiteSpace(json)) EventClient.OnEvent(this, $"【代运营朋友圈】 => {item.WeixinHao},转发失败"); else EventClient.OnEvent(this, $"【代运营朋友圈】 => {item.WeixinHao},转发成功"); if (!Class1.Config.isPl) { var reg = Regex.Match(json.Replace("", ""), @"(?\d{15,})");//获取返回的朋友圈id if (reg.Success && !string.IsNullOrWhiteSpace(comment)) { var id = reg.Groups["id"].Value; var commentStr = string.Empty; if (string.IsNullOrWhiteSpace(Class1.Config.appendComment)) commentStr = string.Join("[分段]", comment); else commentStr = string.Join("[分段]", comment, Class1.Config.appendComment); if (!string.IsNullOrWhiteSpace(commentStr)) item.SendCircleComment(item.User.Username, id, commentStr.Replace("[活动口令]", Class1.Config.actionLink)); } } } catch (Exception ex) { EventClient.OnEvent(this, $"【代运营朋友圈】 发送异常:{ex.Message} - {ex.StackTrace}"); } //}); } if (Class1.Config.Monitor_Interval != 0) { Class1.Config.LastSendTime = DateTime.Now; Util.Save(Class1.Config); } EventClient.OnEvent(this, $"【代运营朋友圈】 所有账号发送完毕"); } } catch (Exception ex) { EventClient.OnEvent(this, $"【代运营朋友圈】 发送失败:{ex.Message} - {ex.StackTrace}"); } } } }