Пример #1
0
        /// <summary>
        /// 根据以设置的Cookie,更新用户状态,读取以往数据
        /// </summary>
        /// <returns>Cookie是否成功使用</returns>
        public async Task <bool> UpdateMain()
        {
            try
            {
                ShowLoading("联网获取个人主页...");
                if (!await ExpManager.GetMain())
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                await ShowMessageDialog("程序出错. 可能是没有网络。", "异常代码: " + string.Format("{0:X}", e.HResult) + "\n描述信息" + e.Message);

                App.Current.Exit();
            }
            ShowLoading("读取个人上次数据...");
            await UpdateMainSubStep_InitDataPacks();

            HideLoading();
            ShowNewMainInf();
            isCookieValid = true;
            ShowControls(); //这会点亮更新按钮

            return(true);
        }
Пример #2
0
 private static async Task GetMainSubStep_CookiedGetMain()
 {
     htmlMain = await ExpManager.CookiedGetUrl(
         "https://jingyan.baidu.com/user/nuc",
         "https://jingyan.baidu.com/"
         );
 }
Пример #3
0
        public static async Task <bool> CookielessGetReward(string tp, int cid, int pg)
        {
            string rewardUrl = "https://jingyan.baidu.com/patch?tab=" + tp + "&cid=" + cid + "&pn=" + pg * 15;

            string rewardPage = await ExpManager.CookiedGetUrl(
                rewardUrl,
                "https://jingyan.baidu.com/"
                );

            return(ParseReward(rewardPage, rewardUrl));
        }
Пример #4
0
        private void buttonSearch_Click(object sender, RoutedEventArgs e)
        {
            helpSearchHolder.Visibility = Visibility.Collapsed;
            string order;

            switch (((TextBlock)comboSearchOrderType.SelectionBoxItem).Text)
            {
            case "最佳匹配":
                order = "match";
                break;

            case "最高浏览量":
                order = "view";
                break;

            case "最高浏览量增量":
                order = "viewinc";
                break;

            case "最高收藏量":
                order = "collect";
                break;

            case "最靠前":
                order = "new";
                break;

            default: order = "view"; break;
            }

            int count;

            switch (((TextBlock)comboSearchCount.SelectionBoxItem).Text)
            {
            case "50条":
                count = 50;
                break;

            case "100条":
                count = 100;
                break;

            case "全部":
                count = 100000;
                break;

            default: count = 100000; break;
            }

            ExpManager.SearchContentExps(textBoxSearch.Text, order, count);
            listViewSearchExps.ItemsSource = ExpManager.contentExpsSearched;
        }
Пример #5
0
        //private static string thread0Ret;
        //private static string thread1Ret;
        //private static string thread2Ret;
        //private static string thread3Ret;
        //private static string thread4Ret;
        private static async Task GetContentsSubStep_CookiedGetContentPage(int pg, int threadID)
        {
            string result = await ExpManager.CookiedGetUrl(
                "https://jingyan.baidu.com/user/nucpage/content?tab=exp&expType=published&pn=" + pg * 20,
                "https://jingyan.baidu.com/user/nuc"
                );

            lock (htmlContentPages)//not sure is necessary
            {
                //Debug.WriteLine(Task.CurrentId + " : 成功进入htmlContentPages锁定区域");
                htmlContentPages[pg] = result;
            }
            //if (htmlContentPages[pg] == "FAILED") return false;
            //return true;
        }
Пример #6
0
        public MainPage()
        {
            this.InitializeComponent();
            App.currentMainPage = this;
            ExpManager.Init();
            StatManager.Init();


            listViewSearchExps.ItemsSource = ExpManager.rewardExps;

            VisualStateManager.GoToState(buttonSetCookie, "stateNormal", false);
            ShowControls();//first disable something

            SelfCheckAndInit();
        }
Пример #7
0
        private void buttonSearchReward_Click(object sender, RoutedEventArgs e)
        {
            helpSearchHolder.Visibility = Visibility.Collapsed;
            string order;

            switch (((TextBlock)comboSearchRewardOrderType.SelectionBoxItem).Text)
            {
            case "最佳匹配":
                order = "match";
                break;

            case "最高赏金":
                order = "money";
                break;

            case "名称最短":
                order = "short";
                break;

            case "最靠前":
                order = "new";
                break;

            default: order = "match"; break;
            }

            int count;

            switch (((TextBlock)comboSearchRewardCount.SelectionBoxItem).Text)
            {
            case "20条":
                count = 20;
                break;

            case "50条":
                count = 50;
                break;

            case "全部":
                count = 100000;
                break;

            default: count = 100000; break;
            }

            ExpManager.SearchRewardExps(textBoxSearch.Text, order, count);
            listViewSearchExps.ItemsSource = ExpManager.rewardExpsSearched;
        }
Пример #8
0
        private async void buttonRewardGet_Click(object sender, RoutedEventArgs e)
        {
            string queryId = ((RewardExpEntry)((Button)sender).DataContext).QueryId;

            ShowLoading("领取请求...");
            bool isEnterEdit = await ExpManager.CookiedGetReward(queryId);

            HideLoading();
            if (isEnterEdit)
            {
                buttonCenter_Click(sender, e);
                // await Task.Delay(300);
                JSCodeString.planToGoUrl = "https://jingyan.baidu.com/edit/content?queryId=" + queryId;
                buttonMainPage_Click(sender, e);
            }
        }
Пример #9
0
        /// <summary>
        /// 在Main已经成功更新后,更新Content
        /// </summary>
        /// <returns>更新Content是否成功</returns>
        public async Task <bool> UpdateContents()
        {
            bool ret = await ExpManager.GetContents(
                textVisitAll,
                listViewContentExps);

            if (ret)
            {
                ShowContentInf();
                isDataAvailable   = true;
                isThisTimeUpdated = true;
                ShowControls();
            }

            return(ret);
        }
Пример #10
0
        public async Task UpdateReward(int pglow, int pghigh, string tp, int cid)
        {
            ExpManager.rewardExps.Clear();
            for (int i = pglow; i <= pghigh;)
            {
                Task <bool> Task0          = ExpManager.CookielessGetReward(tp, cid, i);
                string      cacheStateText = "正在获取页码: " + i;
                i++;
                Task <bool> Task1 = null;
                Task <bool> Task2 = null;
                if (i <= pghigh)
                {
                    Task1           = ExpManager.CookielessGetReward(tp, cid, i);
                    cacheStateText += ", " + i;
                    i++;
                }
                if (i <= pghigh)
                {
                    Task2           = ExpManager.CookielessGetReward(tp, cid, i);
                    cacheStateText += ", " + i;
                    i++;
                }
                textRewardCacheState.Text = cacheStateText;

                if (!(await Task0))
                {
                    break;
                }
                if (Task1 != null && !(await Task1))
                {
                    break;
                }
                if (Task2 != null && !(await Task2))
                {
                    break;
                }
            }
            isCacheReward = true;
            await ShowMessageDialog("悬赏获取", "共获取 " + ExpManager.rewardExps.Count + " 条.");

            ShowControls();
        }
Пример #11
0
        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());
                }
            };
        }
Пример #12
0
        //if fire report succeed, this app should exit or continue. No throw exceptions.
        // ------------------
        //The final exceptions are report failures, and unknown ones.
        public static async Task FireErrorReport(string name, string relatedVars, Exception err = null, string eventMessage = "")
        {
            string eventStr      = string.Join(", ", customEventsLog);
            string localEventStr = string.Join("\n", localEventLog);
            string errStr        = "";

            if (err != null)
            {
                errStr = eventMessage + "\n" + err.HResult.ToString() + "\n" + err.Message + "\n" + err.Source + "\n" + err.StackTrace;
            }

            string varTraceStr          = "";
            string relatedVarsFirstLine = relatedVars.Split('\n')[0].Trim();

            if (relatedVarsFirstLine.StartsWith("[") && relatedVarsFirstLine.EndsWith("]"))
            {
                foreach (string key in Utility.varTrace.Keys)
                {
                    if (key.Contains(relatedVarsFirstLine))
                    {
                        varTraceStr = varTraceStr + key + " = " + Utility.varTrace[key] + "\n";
                    }
                }
            }

            string bar    = "==================";
            string report = bar + "NAME" + bar + "\n\n"
                            + name + "\n"
                            + bar + "VER" + bar + "\n"
                            + StorageManager.VER + "\n\n"
                            + bar + "EXCEPTION" + bar + "\n"
                            + errStr + "\n\n"
                            + bar + "RELATED-VARS" + bar + "\n"
                            + relatedVars + "\n" + varTraceStr + "\n\n"
                            + bar + "EVENTS" + bar + "\n"
                            + eventStr + "\n\n"
                            + bar + "LOCAL-EVENTS" + bar + "\n"
                            + localEventStr + "\n\n";

            var dlg    = new ContentErrorReportDialog(name, report);
            var result = Windows.UI.Xaml.Controls.ContentDialogResult.None;

            try
            {
                result = await dlg.ShowAsync();
            }
            catch (Exception) //允许在ContentDialog打开的情况下出错
            {
                bool shouldSend = await ShowConfirmDialog("是否将错误报告发送给开发者? ", "窗口被占用, 错误报告无法显示. 是否将错误报告发送给开发者?", "发送给开发者", "忽略此错误");

                if (shouldSend)
                {
                    result = Windows.UI.Xaml.Controls.ContentDialogResult.Secondary;
                }
            }
            if (result == Windows.UI.Xaml.Controls.ContentDialogResult.Secondary)
            {
                App.currentMainPage.ShowLoading("正在发送错误报告...");
                string data = report;
                if (dlg.errorNote != "")
                {
                    data += bar + "NOTE" + bar + "\n" + dlg.errorNote + "\n\n";
                }
                var    formData   = new KeyValuePair <string, string>[] { new KeyValuePair <string, string>("data", data) };
                string postResult = await ExpManager.PostData("http://193.112.68.240:8122/errorreport", "", formData);

                App.currentMainPage.HideLoading();

                if (postResult.StartsWith("ERROR"))
                {
                    await ShowMessageDialog("发送失败", postResult + "如果始终无法发送,下次出错直接复制错误报告的内容,发送邮件给开发者 [email protected]");

                    throw new Exception("ERROR-REPORT-FAILED");
                }
                else
                {
                    await ShowMessageDialog("匿名发送成功", "谢谢,错误报告已经匿名提交成功。\n注意,开发者可以看到报告但是无法与你取得联系。\n如果需要与开发者取得联系,可邮件 [email protected]");

                    return;
                }
            }
        }
Пример #13
0
        /// <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);
            }
        }
Пример #14
0
        /// <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();
        }