using AllBase; using AllBase.Helper; using AllBase.Model.Result; using CefSharp; using CefSharp.WinForms; using NaiBa.CefHelper; using NaiBa.CefHelper.Handler; using NaiBa.Util.Extension; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Media; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using TemuKJD.BaseForms; using TemuKJD.Helper; using TemuKJD.ToolForms; using TemuKJD.WXForms.TalkForms.TalkHelper; namespace TemuKJD.WXForms.TalkForms { public partial class WxTalkForm : BaseTalkForm { public Dictionary ShopChatCount = new Dictionary(); public delegate void SearchResultReceivedHandler(ShopLoginInfo shop); /// /// 查询结果事件通知 /// public event SearchResultReceivedHandler SearchResultReceived; public delegate void InfomationReceivedHandler(string infomation); /// /// 消息事件通知,比如:异常等通知 /// /// public event InfomationReceivedHandler InfomationReceived; public static ShopLoginInfo currentShop = null; ChromiumWebBrowser mainWebBrowser = null; /// /// 弹出框列表 /// //public static List lstChatMessageForm = new List(); public static Dictionary dicRowColor = new Dictionary(); public int LocationXY = 0; public int LocationSize = 200; public WxTalkForm() { InitializeComponent(); ChatConfig.LoadChatSetting(); } private void WxTalkForm_FormClosed(object sender, FormClosedEventArgs e) { Process.GetCurrentProcess().Kill(); } private void WxTalkForm_Load(object sender, EventArgs e) { if (BaseClass.LogoImage != null) pbLogo.Image = BaseClass.LogoImage; if (BaseClass.Ico != null) this.Icon = BaseClass.Ico; else this.Icon = BaseClass.Ico = ImageBuild.ConvertToIcon(Properties.Resources.icon); //SetTitle(); //this.chkIsAutoReLogin.CheckedChanged -= chkIsAutoReLogin_CheckedChanged; //this.chkIsAutoReply.CheckedChanged -= chkIsAutoReply_CheckedChanged; //this.txtAutoReplyText.TextChanged -= txtAutoReplyText_TextChanged; //this.cmbMessage.SelectedIndexChanged -= cmbMessage_SelectedIndexChanged; if (this.cmbMessage.Items.Contains(ChatConfig.ChatSettingConfig.MessageSound)) this.cmbMessage.SelectedItem = ChatConfig.ChatSettingConfig.MessageSound; else this.cmbMessage.SelectedIndex = 0; this.chkIsAutoReply.Checked = ChatConfig.ChatSettingConfig.IsAutoReply; this.txtAutoReplyText.Text = ChatConfig.ChatSettingConfig.AutoReplayText; this.chkIsAutoReLogin.CheckedChanged += chkIsAutoReLogin_CheckedChanged; this.chkIsAutoReply.CheckedChanged += chkIsAutoReply_CheckedChanged; this.txtAutoReplyText.TextChanged += txtAutoReplyText_TextChanged; this.cmbMessage.SelectedIndexChanged += cmbMessage_SelectedIndexChanged; SearchResultReceived += Chat_SearchResultReceived; InfomationReceived += Collect_InfomationReceived; if (mainWebBrowser == null) { mainWebBrowser = CEFBrowser.CreateChromiumWebBrowser("about:blank", false); mainWebBrowser.KeyboardHandler = new KeyboardHandler(); mainWebBrowser.Dock = DockStyle.Fill; var lifeSpanHandler = new LifeSpanHandlerLocal(PopWindowType.NewTitleWindow); lifeSpanHandler.parent = mainWebBrowser; lifeSpanHandler.OnPop += MainLifeHandler_OnPop; mainWebBrowser.LifeSpanHandler = lifeSpanHandler; //mainWebBrowser.AddressChanged += mainWebBrowser_UrlChanged; mainWebBrowser.FrameLoadEnd += cefWebBrowser1_FrameLoadEnd; mainPanel.Controls.Add(mainWebBrowser); } Task.Run(() => { // 直到店铺加载完后再加载客服内容 while (!StartUp.IsShopInit) Thread.Sleep(100); SetMainBrowserUrl(GlobalConfig.ShopLoginList.FirstOrDefault()); LoadShop(); InitAutoExecute(); }); } private void cefWebBrowser1_FrameLoadEnd(object sender, CefSharp.FrameLoadEndEventArgs e) { //ChromiumWebBrowser cefWebBrowser1 = (ChromiumWebBrowser)sender; //string url = cefWebBrowser1.Address; //if (url.Contains("/mallcenter/info/basic") && cefWebBrowser3.IsBrowserInitialized) //{ // Thread.Sleep(5000); // var shop = GetShopLoginInfo.Shops.Find(s => s != null && s.ShopName == ShopName); // string code = "document.getElementsByClassName('new-part')[1].innerHTML=\"
" + shop.Name + "?

当前状态不支持修改店铺名,您可一键开新店铺

\""; // cefWebBrowser3.GetBrowser().MainFrame.ExecuteJavaScriptAsync(code); //} } [DllImport("winmm.dll")] public static extern uint mciSendString(string lpstrCommand, string lpstrReturnString, uint uReturnLength, uint hWndCallback); /// /// 播放提示音 /// public void playSound() { string musicname = "默认提示音"; if (!string.IsNullOrEmpty(ChatConfig.ChatSettingConfig.MessageSound)) musicname = ChatConfig.ChatSettingConfig.MessageSound; if (musicname == "无") return; if (musicname == "默认提示音") musicname = "9527.wav"; else musicname = musicname + ".mp3"; if (musicname.Contains("wav")) { try { SoundPlayer sound = new SoundPlayer("temp/" + musicname); sound.Play(); } catch { } } if (musicname.Contains("mp3")) { try { mciSendString(@"close ""temp/" + musicname + @"""", null, 0, 0); mciSendString(@"open ""temp/" + musicname + @"""", null, 0, 0); mciSendString(@"play ""temp/" + musicname + @"""", null, 0, 0); } catch { } } } public void ShowChat(ShopLoginInfo shop) { while (shop.Chat?.IsBrowserInitialized != true) { Thread.Sleep(50); } // 设置cef cookie if (shop.Chat != null && shop.Chat.IsBrowserInitialized) { var cookieManager = shop.Chat.RequestContext.GetCookieManager(null); var cookieLst = JsonHelper.DeserializeJsonToList(shop.Cookies.ParseToString()); if (cookieLst == null) cookieLst = new List(); cookieManager.DeleteCookies("qq.com", null); foreach (var cook in cookieLst) { var t = CEFBrowser.SetCookieAsync(cook.Domain, cook.Name + "=" + cook.Value + ";", cookieManager); t.Wait(5000); } if (shop.LoginStatus == "登录成功") shop.Chat.Load("https://store.weixin.qq.com/shop/kf"); } } public void LoadShop(List shopList = null) { if (shopList == null) shopList = new List(); if (shopList.Count == 0) shopList.AddRange(GlobalConfig.ShopLoginList); for (int i = 0; i < shopList.Count; i++) { var shop = shopList[i]; ShopLoginInfo result = new ShopLoginInfo(); result.ShopId = shop.ShopId; result.ShopAccount = shop.ShopAccount; result.LoginStatus = shop.LoginStatus; var r = dgvShop.Rows.Cast().FirstOrDefault(x => x.Cells["colShopId"].Value.ToString() == shop.ShopId); this.Invoke(new Action(() => { int iGrid = 0; if (r == null) iGrid = dgvShop.Rows.Add(); else iGrid = r.Index; dgvShop.Rows[iGrid].Cells["colShopId"].Value = shop.ShopId; // 店铺ID dgvShop.Rows[iGrid].Cells["colShopName"].Value = shop.ShopAccount; // 店铺名称 dgvShop.Rows[iGrid].Cells["colLoginStatus"].Value = shop.LoginStatus == "登录成功" ? "在线" : "掉线"; // 登录状态 dicRowColor[dgvShop.Rows[iGrid]] = dgvShop.Rows[iGrid].DefaultCellStyle.BackColor; if (shop.Chat == null) { LocationXY += 5; shop.X = LocationXY % LocationSize; shop.Y = LocationXY / LocationSize; RequestContextSettings requestContextSettings = new RequestContextSettings(); requestContextSettings.PersistSessionCookies = false; //requestContextSettings.PersistUserPreferences = false; try { var cefWebBrowser = CEFBrowser.CreateChromiumWebBrowser("about:blank", false); //new ChromiumWebBrowser("https://store.weixin.qq.com/shop/kf); CustomResourceRequestHandler resourceRequestHandler = new CustomResourceRequestHandler(); resourceRequestHandler.ResourceLoadCompleteEvent += RequestHandler_ResourceLoadComplete; cefWebBrowser.RequestHandler = new CustomRequestHandler(resourceRequestHandler); cefWebBrowser.KeyboardHandler = new KeyboardHandler(); var lifeHandler = new LifeSpanHandlerLocal(PopWindowType.NewTitleWindow); lifeHandler.OnPop += LifeHandler_OnPop; lifeHandler.parent = cefWebBrowser; cefWebBrowser.LifeSpanHandler = lifeHandler; cefWebBrowser.RequestContext = new RequestContext(requestContextSettings); cefWebBrowser.Dock = DockStyle.Fill; //DockStyle.None; cefWebBrowser.Location = new Point(shop.X, shop.Y); shop.Chat = cefWebBrowser; pnlTalk.Controls.Add(shop.Chat); if (i == 0) currentShop = shop; Task.Run(() => { ShowChat(shop); }); } catch (Exception ex) { return; } } })); } } private void RequestHandler_ResourceLoadComplete(object sender, string url, string postData, string responseData) { if (responseData.Contains("你好")) { Task.Run(() => { }); } } private void MainLifeHandler_OnPop(object sender, PopData e) { var targetUrl = e.Url; var lifeHandler = sender as LifeSpanHandlerLocal; Task.Run(() => { if (lifeHandler.parent != null) { var cookies = CEFBrowser.GetCookieList("", lifeHandler.parent.RequestContext.GetCookieManager(null)); Invoke(new Action(() => { CefForm cefForm = new CefForm(targetUrl, cookies); cefForm.Show(); })); } }); } private void LifeHandler_OnPop(object sender, PopData e) { var targetUrl = e.Url; var lifeHandler = sender as LifeSpanHandlerLocal; Task.Run(() => { //if (e.Url.StartsWith("https://haohuo.jinritemai.com/views/product/item")) //{ // var productId = BaseRegex.GetMatchRegexString(ref targetUrl, "&id=(\\d{5,30})"); // if (!string.IsNullOrEmpty(productId)) // { // long product_id = productId.ParseToLong(); // if (product_id > 0) // { // 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("", "") + datax); // string id = BaseRegex.GetMatchRegexString(htmlx, @"([\d]+)"); // if (htmlx.StartsWith("tb")) // targetUrl = "https://item.taobao.com/item.htm?id=" + id; // if (htmlx.StartsWith("pd")) // targetUrl = "https://mobile.yangkeduo.com/goods.html?goods_id=" + id; // if (htmlx.StartsWith("al")) // targetUrl = "https://detail.1688.com/offer/" + id + ".html"; // if (htmlx.StartsWith("dy")) // targetUrl = "https://weidian.com/item.html?itemID=" + id; // } // } //} //if (lifeHandler.parent != null) //{ // var cookies = CEFBrowser.GetCookieList("", lifeHandler.parent.RequestContext.GetCookieManager(null)); // Invoke(new Action(() => // { // CefForm cefForm = new CefForm(targetUrl, cookies); // cefForm.Show(); // })); //} }); } /// /// 更新店铺后台首页 /// /// private void SetMainBrowserUrl(ShopLoginInfo shop) { if (shop == null) return; var cookieLst = JsonHelper.DeserializeJsonToList(shop.Cookies.ParseToString()); if (cookieLst == null) cookieLst = new List(); var cookieManager = mainWebBrowser.RequestContext.GetCookieManager(null); cookieManager.DeleteCookiesAsync("qq.com", null).Wait(); foreach (var cook in cookieLst) { var t = CEFBrowser.SetCookieAsync(cook.Domain, cook.Name + "=" + cook.Value + ";", cookieManager); t.Wait(5000); } mainWebBrowser.Load("https://store.weixin.qq.com/shop/home"); } /// /// 自动回复等 /// public void InitAutoExecute() { //Task.Run(() => //{ // while (true) // { // foreach (var shop in GlobalConfig.DouShopLoginList) // { // try // { // Thread.Sleep(new Random(DateTime.Now.Millisecond).Next(300, 500)); // bool needReLogin = AutoCheckShopLoginStatus(shop); // if (ChatConfig.ChatSettingConfig.IsAutoReLogin && needReLogin) // AutoReLogin(shop); // if (shop.LoginStatus != "登录成功") // continue; // Thread.Sleep(new Random(DateTime.Now.Millisecond).Next(300, 500)); // AutoReConnect(shop); // Thread.Sleep(new Random(DateTime.Now.Millisecond).Next(300, 500)); // AutoCloseMaskWindow(shop); // Thread.Sleep(new Random(DateTime.Now.Millisecond).Next(300, 500)); // var isNewMessage = AutoGetNewMessage(shop); // while (isNewMessage && ChatConfig.ChatSettingConfig.IsAutoReply) // { // AutoReplyWithJs(shop); // Thread.Sleep(new Random(DateTime.Now.Millisecond).Next(300, 500)); // isNewMessage = AutoGetNewMessage(shop); // } // } // catch (Exception ex) // { // } // } // } //}); //Task.Run(() => //{ // var sleepTime = 1000; // while (true) // { // Thread.Sleep(sleepTime); // var jsStr = "function getVideo() {\r\n" + // " var videos = document.getElementsByTagName('video')\r\n" + // " if (videos && videos.length > 0) {\r\n" + // " var src = videos[0].src;\r\n" + // " videos[0].parentElement.parentElement.click();\r\n" + // " return src;\r\n" + // " //return '';\r\n" + // " }\r\n" + // " return '';\r\n" + // "}" + // "getVideo();\r\n"; // if (currentShop?.Chat != null && currentShop.Chat.IsBrowserInitialized) // { // var t = currentShop.Chat.GetMainFrame().EvaluateScriptAsync(jsStr); // t.Wait(); // if (!string.IsNullOrEmpty(t.Result?.Result?.ToString())) // { // Invoke(new Action(() => // { // AllBase.GetHtml.OpenUrl(t.Result.Result.ToString()); // })); // } // } // } //}); //Task.Run(() => //{ // var sleepTime = 2500; // while (true) // { // try // { // Thread.Sleep(sleepTime); // var jsStr1 = "function ClosePopWindow() {\r\n" + // " var result = 'no_pop'\r\n" + // " var item = document.getElementsByClassName('anticon-close-circle');\r\n" + // " for(i = 0; i < item.length; i++) {\r\n" + // " item[i].click();\r\n" + // " result = 'success'\r\n" + // " }\r\n" + // " return result;\r\n" + // "}\r\n" + // "ClosePopWindow();\r\n"; // var jsStr2 = "function clickPopWindow() {\r\n" // + "var child = document.body.firstElementChild;\r\n" // + "var element1 = null;\r\n" // + " while (child) {\r\n" // + " if (child.innerHTML.indexOf('知道了') >= 0) {\r\n" // + " element1 = child;\r\n" // + " if (child.firstElementChild) {\r\n" // + " child = child.firstElementChild; continue;\r\n" // + " } else break;\r\n" // + " }\r\n" // + " child = child.nextElementSibling;\r\n" // + " }\r\n" // + " if (element1) {\r\n" // + " element1.click(); return 'success';\r\n" // + " } else return 'no_pop';\r\n" // + "}\r\n" // + "clickPopWindow();\r\n"; // if (mainWebBrowser.IsBrowserInitialized) // { // var t1 = mainWebBrowser.GetMainFrame().EvaluateScriptAsync(jsStr1); // t1.Wait(); // var t2 = mainWebBrowser.GetMainFrame().EvaluateScriptAsync(jsStr2); // t2.Wait(); // if (t1.Result?.Result?.ToString() == "success" || t2.Result?.Result?.ToString() == "success") // sleepTime = Randomx.GetId(550, 650); // else // sleepTime = Randomx.GetId(2500, 3000); // } // } // catch (Exception ex) { } // } //}); } private void chkIsAutoReLogin_CheckedChanged(object sender, EventArgs e) { ChatConfig.ChatSettingConfig.IsAutoReLogin = chkIsAutoReLogin.Checked; ChatConfig.SaveChatSettingParam(); //GlobalConfig.DouShopSettingParam.IsAutoDragLogin = chkIsAutoReLogin.Checked; } private void chkIsAutoReply_CheckedChanged(object sender, EventArgs e) { ChatConfig.ChatSettingConfig.IsAutoReply = chkIsAutoReply.Checked; ChatConfig.SaveChatSettingParam(); } private void txtAutoReplyText_TextChanged(object sender, EventArgs e) { ChatConfig.ChatSettingConfig.AutoReplayText = txtAutoReplyText.Text; ChatConfig.SaveChatSettingParam(); } private void cmbMessage_SelectedIndexChanged(object sender, EventArgs e) { ChatConfig.ChatSettingConfig.MessageSound = this.cmbMessage.SelectedItem.ToString(); ChatConfig.SaveChatSettingParam(); } private void Chat_SearchResultReceived(ShopLoginInfo shop) { var r = dgvShop.Rows.Cast().FirstOrDefault(x => x.Cells["columnShopId"].Value.ToString() == shop.ShopId); if (r != null) { for (int i = 0; i < dgvShop.Rows.Count; i++) { var row = dgvShop.Rows[i]; if (row.Cells[0].Value.ToString() == shop.ShopId && shop != currentShop) { if (ShopChatCount.ContainsKey(shop.ShopId) && ShopChatCount[shop.ShopId] > 0) { Task.Run(() => { for (int j = 0; j < 4; j++) { Invoke(new Action(() => { row.DefaultCellStyle.BackColor = Color.White; })); Thread.Sleep(100); Invoke(new Action(() => { row.DefaultCellStyle.BackColor = Color.FromArgb(245, 95, 50); })); Thread.Sleep(100); Invoke(new Action(() => { row.DefaultCellStyle.BackColor = Color.FromArgb(245, 45, 10); })); Thread.Sleep(100); } }); } else if (row.DefaultCellStyle.BackColor != Color.White) { row.DefaultCellStyle.BackColor = Color.White; } break; } } } } private void Collect_InfomationReceived(string infomation) { //try //{ // this.Invoke(new Action(() => // { // lblMsg.Text = infomation; // var data = infomation.Split(new string[] { ":" }, StringSplitOptions.RemoveEmptyEntries); // if (data.Length == 2) // { // if (data[1] == FastCarCollect.FASTCAR_QUOTA_FINISH) // { // var shop = gridShop.Rows.Cast().FirstOrDefault(x => x.Cells["columnShopName"].Value.ToString() == data[0]); // if (shop != null) // { // shop.Cells["columnMsg"].Value = data[1]; // } // } // } // if (infomation == "修改出价结束") // this.btnStart.Enabled = true; // if (infomation == "暂停推广结束") // this.btnStop.Enabled = true; // })); //} //catch { } } } }