using _29WxOrderWpf.CefHelper; using _29WxOrderWpf.Commands; using _29WxOrderWpf.ViewModels; using AllBase; using AllBase.Helper; using AllBase.Model.DBModel; using AllBase.Model.MvvmBaseClasses; using CefSharp; using CefSharp.Handler; using CefSharp.Wpf; using NaiBa.Util.Extension; using Org.BouncyCastle.Asn1.Ocsp; using System; using System.Collections.Generic; using System.Linq; using System.Security.Policy; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using TemuKJD.ToolForms; using Work; using Work._29Tools.BLL; using Work._29Tools.CefTools; using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel; namespace _29WxOrderWpf.Ctrls.BuyerCtrls { /// /// 淘宝买手购买商品页面 视图模型 /// public class TaobaoBuyOrderViewModel : PropertyNotifyObject { public static TaobaoBuyOrderViewModel TaobaoBuyOrderInstance { get; set; } = null; /// 浏览器创建完成后触发(视图在此把浏览器加入可视树) public event Action BrowserCreated; /// 请求关闭窗口 public event Action RequestClose; public int CloseAfterSecond { get; set; } public string InitUrl { get; set; } = ""; private string shopCookieHead = "taobao.com"; private string buyerLoginUrl = "https://login.taobao.com/havanaone/login/login.htm"; private string MainUrl = "https://i.taobao.com/my_itaobao"; //"https://buyertrade.taobao.com/trade/itemlist/list_bought_items.htm?"; public ChromiumWebBrowser CefWebBrowser { get; private set; } private BuyerLoginInfo buyer = null; private string currentUrl = ""; private volatile bool _isWindowLoaded = false; #region 界面绑定属性 /// 用户名 public string UserName { get { return this.GetValue(x => x.UserName); } set { this.SetValue(x => x.UserName, value); } } /// 密码 public string PassWord { get { return this.GetValue(x => x.PassWord); } set { this.SetValue(x => x.PassWord, value); } } /// 地址栏 public string Address { get { return this.GetValue(x => x.Address); } set { this.SetValue(x => x.Address, value); } } #endregion #region 命令 public ICommand ReloadCommand { get; } public ICommand LoginAgainCommand { get; } public ICommand StopCommand { get; } public ICommand CopyUserNameCommand { get; } public ICommand CopyPasswordCommand { get; } #endregion public TaobaoBuyOrderViewModel(BuyerLoginInfo buyerInfo) { TaobaoBuyOrderInstance = this; buyer = buyerInfo; UserName = buyerInfo?.buyer_name; PassWord = ""; //DataOpenSSL.DecryptString(buyerInfo.Password); ReloadCommand = new DelegateCommand(Reload); LoginAgainCommand = new DelegateCommand(LoginAgain); StopCommand = new DelegateCommand(StopButton); CopyUserNameCommand = new DelegateCommand(CopyUserName); CopyPasswordCommand = new DelegateCommand(CopyPassword); } /// /// 窗口加载完成时调用 /// public void Start() { _isWindowLoaded = true; if (CloseAfterSecond > 0) { Task.Run(() => { Thread.Sleep(1000 * CloseAfterSecond); if (_isWindowLoaded) { Application.Current?.Dispatcher.Invoke(new Action(() => { if (_isWindowLoaded) RequestClose?.Invoke(); })); } }); } Task.Run(() => { AutoLogin(); }); } /// /// 窗口关闭时调用,停止后台任务 /// public void Stop() { _isWindowLoaded = false; } /// /// 自动登录店铺后台 /// private async void AutoLogin() { if (buyer == null) return; _ = Application.Current.Dispatcher.InvokeAsync(async () => { if (CefWebBrowser == null) { if (!string.IsNullOrEmpty(InitUrl)) CefWebBrowser = WPFCEFBrowser.CreateChromiumWebBrowser(InitUrl, false); else CefWebBrowser = WPFCEFBrowser.CreateChromiumWebBrowser(MainUrl, false); LocalResourceRequestHandler resourceRequestHandler = new LocalResourceRequestHandler(); resourceRequestHandler.ResourceLoadCompleteEvent += RequestHandler_ResourceLoadComplete; resourceRequestHandler.BeforeResourceLoadEvent += RequestHandler_BeforeResourceLoad; CefWebBrowser.RequestHandler = new LocalRequestHandler(resourceRequestHandler); var lifeSapnHandler = new LocalLifeSpanHandler(PopWindowType.SelfWindow); CefWebBrowser.LifeSpanHandler = lifeSapnHandler; //CefWebBrowser.KeyboardHandler = new KeyboardHandler(); CefWebBrowser.KeyboardHandler = new CefKeyboardHandler(); CefWebBrowser.FrameLoadEnd += CefWebBrowser_FrameLoadEnd; CefWebBrowser.AddressChanged += CefWebBrowser_AddressChanged; CefWebBrowser.LoadError += CefWebBrowser_LoadError; // 通知视图把浏览器加入可视树(必须在等待浏览器初始化之前完成) BrowserCreated?.Invoke(CefWebBrowser); List cookieLst = new List(); try { if (buyer != null) { cookieLst = JsonHelper.DeserializeJsonToList(buyer?.cookie); if (cookieLst == null) cookieLst = new List(); } } catch { } // cef138必须init后方可设置或删除cookie while (!CefWebBrowser.IsBrowserInitialized || !CefWebBrowser.GetBrowser().MainFrame.IsValid) await Task.Delay(20); WPFCEFBrowser.DeleteCookie(CefWebBrowser.GetCookieManager(null)); //cef 138 如果没有设置RequestContext 可能为空,直接getCookieManager //await WPFCEFBrowser.SetCookieAsync(JsonHelper.SerializeObject(cookieLst), CefWebBrowser.GetCookieManager(null)); foreach (var cook in cookieLst) { await WPFCEFBrowser.SetCookieAsync(cook.Domain.Trim('.'), cook.Name + "=" + cook.Value + ";", CefWebBrowser.GetCookieManager(null)); //t.Wait(5000); } //根据登录的具体店铺设置local storage if (!string.IsNullOrEmpty(buyer?.buyer_id)) { //var storageJsCode = "window.localStorage.setItem('" + "mall-info-id" + "', '" + shop.ShopId + "');\r\n"; //storageJsCode += "window.localStorage.setItem('" + "agentseller-mall-info-id" + "', '" + shop.ShopId + "');\r\n"; //while (!CefWebBrowser.IsBrowserInitialized || !CefWebBrowser.GetBrowser().MainFrame.IsValid) // Thread.Sleep(20); //CefWebBrowser.GetBrowser().MainFrame.ExecuteJavaScriptAsync(storageJsCode); } if (!string.IsNullOrEmpty(InitUrl)) CefWebBrowser.Load(InitUrl); else CefWebBrowser.Load(MainUrl); } }); } private void CefWebBrowser_LoadError(object sender, CefSharp.LoadErrorEventArgs e) { } private void CefWebBrowser_AddressChanged(object sender, DependencyPropertyChangedEventArgs e) { if (Application.Current?.Dispatcher != null) { Application.Current.Dispatcher.Invoke(new Action(() => { currentUrl = e.NewValue.ParseToString(); Address = e.NewValue.ParseToString(); })); } } private void CefWebBrowser_FrameLoadEnd(object sender, CefSharp.FrameLoadEndEventArgs e) { //js绑定C#对象 html页面内声明绑定的C#对象 StringBuilder sb = new StringBuilder(); sb.Append("(function(){"); sb.Append("CefSharp.BindObjectAsync('shopObj');"); sb.Append("})();"); CefWebBrowser.GetBrowser().MainFrame.EvaluateScriptAsync(sb.ToString()); } private bool RequestHandler_BeforeResourceLoad(object sender, string url, string postData, IRequest request) { return false; } private void RequestHandler_ResourceLoadComplete(object sender, string url, string postData, string responseData, IRequest request) { var _url = url; var _responseData = responseData; Task.Run(async() => {await DoResourceLoadComplete(url, responseData); }); } private async Task DoResourceLoadComplete(string url, string responseData) { //if (responseData.Contains("karl_malone_32") || responseData.Contains("jtt_fan")) //{ // //https://h5api.m.taobao.com/h5/mtop.user.getusersimple/1.0/?jsv=2.7.2&appKey=12574478&t=1789984970076&sign=6bb7d3b5cd8bd3ab32bd97c1a0df1c0f&jsonpIncPrefix=tbnavnew&api=mtop.user.getUserSimple&v=1.0&dataType=json&type=originaljson&data=%7B%7D // //{"api":"mtop.user.getUserSimple","v":"1.0","ret":["SUCCESS::调用成功"],"data":{"nick":"jtt_fan","userNumId":440631048,"displayNick":"jtt_fan"}} //} } private void StopButton() { } private void CopyUserName() { if (!string.IsNullOrEmpty(UserName)) Clipboard.SetDataObject(UserName); } private void CopyPassword() { if (!string.IsNullOrEmpty(PassWord)) Clipboard.SetDataObject(PassWord); } private void Reload() { if (CefWebBrowser != null) { if (Address != "about:blank") CefWebBrowser.Load(Address); else CefWebBrowser.Load(MainUrl); } } private void LoginAgain() { if (this.currentUrl != buyerLoginUrl) this.CefWebBrowser?.Load(buyerLoginUrl); } } }