public static void SetWebView(WebView webView, WebView secondWebView) { webView.NavigationCompleted += async(view, args) => { if (App.currentMainPage.isJsDebugConsole) { App.currentMainPage.ShowLoading("🚧 加载调试辅助..."); try { await AddScriptUri(webView, codeLibsMsAppxWeb + "eruda.js"); Debug.WriteLine("## eruda.js loaded."); await Task.Delay(250); await RunJs(webView, "eruda.init()"); await Task.Delay(50); Debug.WriteLine("## eruda.js init."); } catch (Exception) { Debug.WriteLine("## eruda.js failed."); App.currentMainPage.ShowNotify("调试辅助已忽略", "非必须模块,加载不成功", Symbol.Message); } App.currentMainPage.HideLoading(); } if (args.Uri.AbsoluteUri.ToLower().IndexOf("/edit/content") > 0) { App.currentMainPage.isAssistEditorEditing = true; string loadingStatus = "init\n"; try { App.currentMainPage.ShowLoading("加载基础库..."); await AddScriptUri(webView, extensionLibsMsAppxWeb + "react.development.js"); await Task.Delay(50); //unknown reason. ReactDOM is undefined occurs on first start. await AddScriptUri(webView, extensionLibsMsAppxWeb + "react-dom.development.js"); await Task.Delay(200); //unknown reason. ReactDOM is undefined occurs on first start. loadingStatus += "react-done\n"; await AddScriptUri(webView, extensionToolsMsAppxWeb + "AllComps.js"); await AddScriptUri(webView, extensionToolsMsAppxWeb + "AllPoly.js"); loadingStatus += "allpoly-done\n"; //LOADFUNC Config Code if (App.currentMainPage.isCheckedBasicCheck) { Utility.LogEvent("OK_FuncCheckBasicCalled"); App.currentMainPage.ShowLoading("加载基本检查..."); await AddScriptUri(webView, extensionToolsMsAppxWeb + "Checker.js"); loadingStatus += "checker-done\n"; } if (App.currentMainPage.isCheckedBigPic) { Utility.LogEvent("OK_FuncBigPicCalled"); App.currentMainPage.ShowLoading("加载大图片框..."); await AddScriptUri(webView, extensionToolsMsAppxWeb + "BigPic.js"); loadingStatus += "bigpic-done\n"; } if (App.currentMainPage.isCheckedPicInsert) { Utility.LogEvent("OK_FuncPicInsertCalled"); App.currentMainPage.ShowLoading("加载插入图片..."); await AddScriptUri(webView, extensionToolsMsAppxWeb + "PicInsert.js"); loadingStatus += "picinsert-done\n"; } if (App.currentMainPage.isCheckedBriefPic) { Utility.LogEvent("OK_FuncBriefPicCalled"); App.currentMainPage.ShowLoading("加载简介图..."); try { await InjectCommonData(webView); await AddScriptUri(webView, extensionToolsMsAppxWeb + "BriefPic.js"); Utility.LogEvent("YES_BigPicInstSucceed"); loadingStatus += "briefpic-done\n"; } catch (Exception e) { Debug.WriteLine("加载简介图失败: " + e.Message); await Utility.ShowMessageDialog("加载简介图失败", "异常问题,请联系开发者 [email protected]"); } } if (App.currentMainPage.isCheckedAutoComplete) { Utility.LogEvent("OK_FuncAutoCompleteCalled"); App.currentMainPage.ShowLoading("加载自动补全..."); await AddScriptUri(webView, codeLibsMsAppxWeb + "alertify.js"); await AddCssUri(webView, codeLibsMsAppxWeb + "alertify.com.css"); await App.currentMainPage.LoadAutoCompleteAsync(); loadingStatus += "autocomplete-done\n"; } App.currentMainPage.HideLoading(); } catch (Exception e) { App.currentMainPage.ShowNotify("有模块加载失败", e.Message, Symbol.Cancel); await Utility.FireErrorReport("JS模块加载失败", "loadingStatus = " + loadingStatus); } try { await AddScriptUri(webView, "https://cdn.bootcss.com/layer/3.1.0/layer.js"); await AddCssUri(webView, "https://cdn.bootcss.com/layer/3.1.0/theme/default/layer.css?v=3.1.0"); } catch (Exception) { } } else { App.currentMainPage.isAssistEditorEditing = false; } //App.currentMainPage.ShowNotify("到达页面", args.Uri.AbsoluteUri); if (args.Uri.AbsoluteUri.ToLower().StartsWith("http://")) { App.currentMainPage.ShowLoading("当前为HTTP页面,正在跳转到对应HTTPS页面..."); string newUri = args.Uri.AbsoluteUri.Replace("http://", "https://").Replace("HTTP://", "HTTPS://"); webView.Navigate(new Uri(newUri)); return; } App.currentMainPage.HideLoading(); await InsertCookieAndRefresh(view, args); // if plan to go somewhere, go. Currently include [the reward edit page] // await Utility.ShowMessageDialog("debug: " + isCookieInsertSucceed.ToString(), planToGoUrl); if (isCookieInsertSucceed && planToGoUrl != "") { string url = planToGoUrl; planToGoUrl = ""; App.currentMainPage.ShowLoading("前往 " + url + " ... "); webView.Navigate(new Uri(url)); } else { //正常到达的页面,运行自定义功能 await CheckRunNavigateTools(webView, args.Uri.AbsoluteUri); } }; webView.NewWindowRequested += (sender, args) => { args.Handled = true; WebViewNewWindowRequestedEventArgs argss = args; HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, argss.Uri); req.Headers.Referer = argss.Referrer; ((WebView)sender).NavigateWithHttpRequestMessage(req); }; webView.NavigationStarting += async(o, args) => { return; //code below have some problems. await RunJs(webView, "window.realCreateElement = false; window.realCreateElementDone = false;"); Debug.WriteLine("# NavigationStarting add DOMContentLoaded handler."); string oldStatus = ""; for (int i = 0; i < 40; i++) { //await RunJs(webView, "window.external.notify('OMG');"); string status = await RunJs(webView, "document.readyState"); Debug.WriteLine("# NavigationStarting document state: " + status); string status2 = await RunJs(webView, "document.createElement.toString()"); Debug.WriteLine("# NavigationStarting document.createElement state: " + status2); if (status != oldStatus) { if (status == "complete") { //await RunJs(webView, "document.addEventListener('DOMContentLoaded', function(event) { window.realCreateElement = window.document.createElement; });"); await RunJs(webView, "window.realCreateElement = window.document.createElement;"); //await RunJs(webView, "window.console.log = () => {return console.warn(...arguments);};"); string result = await RunJs(webView, "window.document.createElement = () => {return window.realCreateElement(...arguments); };"); Debug.WriteLine("# NavigationStarting hacking result: " + result); string status3 = await RunJs(webView, "document.createElement.toString()"); Debug.WriteLine("# NavigationStarting document.createElement state: " + status3); break; } oldStatus = status; } await Task.Delay(20); } }; webView.ScriptNotify += async(o, args) => { if (args.Value.StartsWith("TEST_NOTIFY")) { Debug.WriteLine("# 测试 window.external.notify."); } else if (args.Value.StartsWith("DATA: ")) { string jsonData = args.Value.Substring(6); await StorageManager.SaveAutoCompleteData("", jsonData); //Utility.ShowMessageDialog(o.ToString(), args.Value); } else if (args.Value.StartsWith("ERROR: ")) { await Utility.ShowMessageDialog("javascript 运行异常", args.Value); Utility.LogEvent("ERROR_JSRUN"); await Utility.FireErrorReport("未知的JS运行异常", "latestJsEvaluated=" + latestJsEvaluated, null, args.Value); } else if (args.Value.StartsWith("GOTO: ") || args.Value.StartsWith("2ND-GOTO: ")) { string gotoType = args.Value.Split(':')[0]; string newUri = args.Value.Replace("2ND-GOTO: ", "").Replace("GOTO: ", "").Trim(); string referrer = ""; if (newUri.Contains(" FROM: ")) { string[] us = newUri.Split(new string[] { " FROM: " }, StringSplitOptions.RemoveEmptyEntries); newUri = us[0]; referrer = us[1]; } try { HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Get, new Uri(newUri)); if (referrer != "") { req.Headers.Referer = new Uri(referrer); } if (gotoType == "GOTO") { webView.NavigateWithHttpRequestMessage(req); } else { secondWebView.NavigateWithHttpRequestMessage(req); } App.currentMainPage.ShowNotify("跳转成功", newUri); } catch (Exception ee) { await Utility.ShowMessageDialog("跳转不成功", "尝试跳转目标: " + newUri); await Utility.ShowDetailedError("出错详细信息", ee); } } else if (args.Value.StartsWith("2ND-VISIBILITY: ")) { string val = args.Value.Replace("2ND-VISIBILITY: ", "").Trim(); if (val == "VISIBLE") { App.currentMainPage.ShowNotify("第二页面可见", "可以手动关闭"); App.currentMainPage.SecondWebViewVisibility = true; } else { App.currentMainPage.ShowNotify("第二页面隐藏", "回到主页面"); App.currentMainPage.SecondWebViewVisibility = false; } } else if (args.Value.StartsWith("NOTIFY: ")) { string info = args.Value.Replace("NOTIFY: ", ""); string[] nParams = info.Split('|'); if (nParams.Length != 3) { await Utility.ShowMessageDialog("Javascript Notify 消息提示调用不正确", "格式为:\nNOTIFY: 标题 | 说明 | OK/WARN/ERROR "); } Symbol smb = Symbol.Accept; if (nParams[2].Trim() == "WARN") { smb = Symbol.Comment; } if (nParams[2].Trim() == "ERROR") { smb = Symbol.Cancel; } App.currentMainPage.ShowNotify(nParams[0].Trim(), nParams[1].Trim(), smb); } else if (args.Value.StartsWith("LOG-EVENT: ")) { string info = args.Value.Replace("LOG-EVENT: ", ""); Utility.LogEvent(info); } else if (args.Value.StartsWith("SHOW-DIALOG: ")) { string info = args.Value.Replace("SHOW-DIALOG: ", ""); string[] nParams = info.Split('|'); if (nParams.Length != 2) { await Utility.ShowMessageDialog("Javascript Notify 消息提示调用不正确", "格式为:\nSHOW-DIALOG: 标题 | 说明"); } await Utility.ShowMessageDialog(nParams[0].Trim(), nParams[1].Trim()); } else if (args.Value.StartsWith("CONFIRM: ")) { string info = args.Value.Replace("CONFIRM: ", ""); string[] nParams = info.Split('|'); if (nParams.Length != 2) { await Utility.ShowMessageDialog("Javascript Notify 消息提示调用不正确", "格式为:\nCONFIRM: 标题 | 说明"); } else { bool isConfirmed = await Utility.ShowConfirmDialog(nParams[0].Trim(), nParams[1].Trim()); try { string callee = isConfirmed ? "external_confirmCallbackYes" : "external_confirmCallbackNo"; await WrapInvokeScriptAsync(webView, callee, new string[] { }); } catch (Exception e) { App.currentMainPage.ShowNotify("js调用失败", "external_confirmCallback"); } } } else if (args.Value.StartsWith("LAUNCH: ")) { string url = args.Value.Replace("LAUNCH: ", "").Trim(); await Launcher.LaunchUriAsync(new Uri(url)); App.currentMainPage.ShowNotify("浏览器调用成功", url, Symbol.Accept); } else if (args.Value.StartsWith("SET-DATA: ")) { string data = args.Value.Replace("SET-DATA: ", "").Trim(); JsonObject jo = null; string groupId = ""; try { jo = JsonValue.Parse(data).GetObject(); groupId = jo["group-id"].GetString(); } catch (Exception e) { Utility.LogEvent("NO_CommonDataParseError"); await Utility.ShowMessageDialog("保存数据调用格式错误", "请确定是JSON字符串,且含有字符串成员 group-id"); await Utility.ShowDetailedError("详细错误信息", e); return; } StorageManager.SetCommonData(groupId, jo); await StorageManager.SaveCommonData(groupId); Utility.LogEvent("YES_CommonDataSucceed"); App.currentMainPage.ShowNotify("数据保存成功", "保存组别为" + groupId); } else if (args.Value.StartsWith("SAVE-PIC: ") || args.Value.StartsWith("SAVEAS-PIC: ") || args.Value.StartsWith("GET-PIC-FOR-UPLOAD: ")) { bool isSave = args.Value.StartsWith("SAVE-PIC: "); bool isSaveAs = args.Value.StartsWith("SAVEAS-PIC: "); bool isGetPic = args.Value.StartsWith("GET-PIC-FOR-UPLOAD: "); string[] data = args.Value.Replace("SAVEAS-PIC: ", "").Replace("SAVE-PIC: ", "").Replace("GET-PIC-FOR-UPLOAD: ", "").Trim().Split('|'); if (data.Length != 3) { await Utility.ShowMessageDialog("保存图片调用格式不正确", "正确格式为 SAVEAS-PIC/SAVE-PIC/GET-PIC-FOR-UPLOAD: : 宽高比 | 宽度 | 高度"); return; } else { App.currentMainPage.ShowLoading("保存简介图..."); double ratio = 1; int width = 100; int height = 100; WriteableBitmap img = null; try { ratio = Convert.ToDouble(data[0].Trim()); width = Convert.ToInt32(data[1].Trim()); height = Convert.ToInt32(data[2].Trim()); img = await App.currentMainPage.GetWebViewImageAsync(ratio, width, height); } catch (Exception e) { await Utility.ShowMessageDialog("图片生成失败", e.Message); } if (img != null) { if (isGetPic) { try { string base64 = await Utility.WritableBitmapToPngBase64Async(img); await WrapInvokeScriptAsync( webView, "external_getUploadPicSucceed", new string[] { base64 }); App.currentMainPage.HideLoading(); } catch (Exception e) { await Utility.ShowMessageDialog("图片转码和发送失败", e.Message); App.currentMainPage.HideLoading(); try { await WrapInvokeScriptAsync( webView, "external_getUploadPicFailed", new string[] { e.Message }); } catch (Exception) { } } } else { try { bool isSaved = await StorageManager.SaveWritableBitmapAsync(img, isSaveAs); App.currentMainPage.HideLoading(); if (!isSaved) { App.currentMainPage.ShowNotify("取消保存", "简介图未保存", Symbol.Cancel); } } catch (Exception e) { await Utility.ShowMessageDialog("保存简介图片失败", "未能保存到文件"); await Utility.ShowDetailedError("错误详细信息", e); App.currentMainPage.HideLoading(); return; } } } } } else if (args.Value.StartsWith("IMAGE-GET: ")) { string originalUrl = args.Value.Replace("IMAGE-GET: ", "").Trim(); Debug.WriteLine("## IMAGE-GET: " + originalUrl); try { string url = originalUrl; bool isCaching = true; if (url.StartsWith("nocache-")) { isCaching = false; url = url.Replace("nocache-", ""); } if (url.StartsWith("https://exp-picture")) { isCaching = false; } if (url.StartsWith("http://exp-picture")) { isCaching = false; //don't know. } WriteableBitmap img = null; if (isCaching) { img = await StorageManager.TryReadImageCacheAsync(url); } if (img == null) { img = await ExpManager.SimpleRequestImage(url); if (img == null) { throw new ArgumentNullException("img"); } if (isCaching) { await StorageManager.TryWriteImageCacheAsync(url, img); } } else { Debug.WriteLine("# 来自图片缓存: " + url); } Debug.WriteLine("WriteableBitmap img: W:" + img.PixelWidth + " H:" + img.PixelHeight); string base64 = await Utility.WritableBitmapToPngBase64Async(img); await WrapInvokeScriptAsync( webView, "external_getImageSucceed", new string[] { originalUrl, base64 }); } catch (Exception e) { Debug.WriteLine("## image failed:" + e.Message); try { await WrapInvokeScriptAsync( webView, "external_getImageFailed", new string[] { originalUrl, e.Message }); } catch (Exception e2) { Debug.WriteLine("## image failed callback failed:" + e2.Message); App.currentMainPage.ShowNotify("JS API调用失败", "window.external.getImageFailed", Symbol.Cancel); } } } else { await Utility.ShowMessageDialog("未知的 window.external.notify 调用", args.Value.ToString()); } }; }
public void SafeSetUserName(string uname) { mainUserName = StorageManager.RemoveInvalidXmlChars(uname); }
/// <summary> /// 设置按钮状态,弹窗请求输入Cookie,设置Cookie,尝试更新Main。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void buttonSetCookie_Click(object sender, RoutedEventArgs e) { buttonSetCookie.IsEnabled = false; buttonSetCookieProgress.IsActive = true; buttonSetCookieProgress.Visibility = Visibility.Visible; ShowLoading("Cookie设置流程中..."); ContentWelcomeDialog cwd = new ContentWelcomeDialog(); ContentDialogResult resultCwd = await cwd.ShowAsync(); if (resultCwd == ContentDialogResult.Primary) { ContentTeachDialog ctd = new ContentTeachDialog(); await ctd.ShowAsync(); ContentHelpDialog chd = new ContentHelpDialog(); await chd.ShowAsync(); } ContentSetCookieDialog scd = new ContentSetCookieDialog(); ContentDialogResult cdr = await scd.ShowAsync(); HideLoading(); if (cdr == ContentDialogResult.None) { ShowMessageDialog("设置取消", "设置取消,保持原状。"); buttonSetCookie.IsEnabled = true; buttonSetCookieProgress.IsActive = false; buttonSetCookieProgress.Visibility = Visibility.Collapsed; return; } if (scd.userInputCookie.Trim() == "") { ShowMessageDialog("输入为空", "设置取消,保持原状。"); buttonSetCookie.IsEnabled = true; buttonSetCookieProgress.IsActive = false; buttonSetCookieProgress.Visibility = Visibility.Collapsed; return; } bool isCookieOK = ExpManager.SetCookie(scd.userInputCookie); if (!isCookieOK) { ShowMessageDialog("Cookie添加", ExpManager.setcookieFailedInfo); buttonSetCookie.IsEnabled = true; buttonSetCookieProgress.IsActive = false; buttonSetCookieProgress.Visibility = Visibility.Collapsed; return; } VisualStateManager.GoToState(buttonSetCookie, "stateWaiting", false); bool isValid = await UpdateMain(); VisualStateManager.GoToState(buttonSetCookie, "stateNormal", false); buttonSetCookie.IsEnabled = true; buttonSetCookieProgress.IsActive = false; buttonSetCookieProgress.Visibility = Visibility.Collapsed; if (isValid) { await StorageManager.SaveCookie(ExpManager.cookie); buttonSetCookieText.Text = "√ Cookie"; await ShowMessageDialog("设置完成", "Cookie有效,可以更新信息了。\n点击头像链接到个人中心。"); ContentTipsDialog scd3 = new ContentTipsDialog(); await scd3.ShowAsync(); } else { ShowMessageDialog("验证Cookie", "Cookie无效,请重新设置"); } HideLoading(); }
/// <summary> /// 尝试从存储读取Cookie,尝试更新Main。 /// </summary> public async void SelfCheckAndInit() { gridMain.Visibility = Visibility.Visible; gridSecond.Visibility = Visibility.Collapsed; JSCodeString.SetWebView(webViewMain); WebSetUpdate(true, false, false, false); ShowLoading("读取设置..."); bool isSettingsRead = await StorageManager.ReadSettings(); if (StorageManager.AppSettings.isFirstIn || StorageManager.AppSettings.version != "1.4.3") { ContentNewDialog cnd = new ContentNewDialog(); ContentDialogResult cdr2 = await cnd.ShowAsync(); if (cdr2 == ContentDialogResult.Secondary) { StorageManager.AppSettings.isFirstIn = false; StorageManager.AppSettings.version = "1.4.3"; } ShowLoading("更新设置..."); await StorageManager.SaveSettings(); } if (!isSettingsRead) { await StorageManager.SaveSettings(); } ShowLoading("读取Edit设置..."); await StorageManager.ReadEditSettings(); if (Window.Current.Bounds.Width < 1100) { textUserName.Text = "您的窗口过窄"; } Uri[] uris = { new Uri("ms-appx:///Assets/8-5-4.jpg"), new Uri("ms-appx:///Assets/8-5-5.jpg"), new Uri("ms-appx:///Assets/8-5-6.jpg"), new Uri("ms-appx:///Assets/8-5-1.jpg"), new Uri("ms-appx:///Assets/8-5-2.jpg"), new Uri("ms-appx:///Assets/8-5-3.jpg") }; Random r = new Random(); int i = r.Next() % 6; ShowLoading("加载背景..."); try { StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(uris[i]); IRandomAccessStream stream = await file.OpenReadAsync(); //打开读取流 BitmapImage img = new BitmapImage(); await img.SetSourceAsync(stream); //从流产生BitmapImage ImageBrush ib = new ImageBrush(); //新建ImageBrush画刷 ib.ImageSource = img; ib.Stretch = Stretch.UniformToFill; //设置拉伸样式 this.Background = ib; //如上设置刚才创建的ImageBrush //Background是一个Brush类型属性 stream.Dispose(); } catch (Exception e) { await ShowMessageDialog("非关键异常", "自动背景图更换失败,请联系开发者\n" + e.Message); } isSelfChecked = true; ShowControls(); HelpStoryboard.Begin(); OpenFolderStoryboard.Begin(); ShowLoading("读取Cookie..."); string cookieGet = await StorageManager.GetCookieTry(); if (cookieGet != null) { if (!ExpManager.SetCookie(cookieGet)) { return; } ShowLoading("尝试更新个人信息..."); bool getSucceed = await UpdateMain(); if (!getSucceed) { await ShowMessageDialog("主页获取不成功", "如果不是网络问题,那可能是BDUSS已经失效。(是否有退出登录操作?)"); } HideLoading(); } else { buttonSetCookie_Click(null, null); } }
private async void buttonSaveDIYEntry_Click(object sender, RoutedEventArgs e) { if (textBoxDIYEntryName.Text == "") { await Utility.ShowMessageDialog("内容不完整", "自定义功能名称不能为空。"); return; } if (textBoxDIYEntryCode.Text == "") { await Utility.ShowMessageDialog("内容不完整", "代码不能为空。"); return; } if (radioDIYEntryUrlTrig.IsChecked == true && !(textBoxDIYEntryUrl.Text.StartsWith("https://"))) { await Utility.ShowMessageDialog("内容不完整", "要使用到达页面触发的方式,必须填写https开头的页面地址."); return; } bool isFound = false; foreach (var tool in StorageManager.dIYToolsSettings.DIYTools) { if (tool.Name == textBoxDIYEntryName.Text) { tool.TargetUrl = textBoxDIYEntryUrl.Text; tool.Note = textBoxDIYEntryNote.Text; tool.Code = textBoxDIYEntryCode.Text; tool.TrigType = radioDIYEntryClickTrig.IsChecked == true ? "click" : "navigate"; isFound = true; break; } } if (!isFound) { var tool = new DIYTool( textBoxDIYEntryName.Text, textBoxDIYEntryUrl.Text, radioDIYEntryClickTrig.IsChecked == true ? "click" : "navigate", textBoxDIYEntryNote.Text, textBoxDIYEntryCode.Text); StorageManager.dIYToolsSettings.DIYTools.Add(tool); } bool isSucceed = await StorageManager.SaveDIYToolsSettings(); if (!isSucceed) { await Utility.ShowMessageDialog("保存出错", "自定义工具未能保存到文件. 可联系开发者. [email protected]"); } else { await Utility.ShowMessageDialog("保存成功", "自定义工具已保存."); listViewDIYTools.ItemsSource = null; listViewDIYTools.ItemsSource = StorageManager.dIYToolsSettings.DIYTools; } }