Пример #1
0
        public void Operations()
        {
            int chromePid = -1;

            try
            {
                WebSocketHelper.msgId = 0;

                // Open a Chrome dev instance in incognito mode
                UpdateStatus("Chrome startup... please wait");
                chromePid = Helper.OpenChromeInstance();

                // Wait for chrome opening and remote debugging service start-up
                UpdateStatus("Establish connection with Chrome... please wait");
                if (WebSocketHelper.WaitForPortOpened() == false)
                {
                    throw new NFAuthException(string.Format("Unable communicate with Chrome debug address {0}:{1}", Helper.localhostAddress, Helper.chromeDebugPort));
                }

                // Get endpoint of our page
                WebSocketHelper.ExtractDebugEndpoint();

                WebSocketHelper.OpenWebsocket();
                WebSocketHelper.WSRequest("Network.enable");
                WebSocketHelper.WSRequest("Page.enable");

                // Load the login webpage
                UpdateStatus("Opening login webpage... please wait");
                WebSocketHelper.WSRequest("Page.navigate", "{'url': '" + Helper.url + "'}");
                //string frameId = WebSocketHelper.WSRequest("Page.navigate", "{'url': '" + Helper.url + "'}")["result"]["frameId"].ToString();

                WebSocketHelper.WSWaitEvent("Page.domContentEventFired");  // Wait loading DOM (document.onDOMContentLoaded event)

                // Wait for the user to login
                UpdateStatus("Please login in to website now ...waiting for you to finish...");
                if (Helper.WaitUserLoggedin() == false)
                {
                    throw new NFAuthException("You have exceeded the time available for the login. Restart the operations.");
                }

                WebSocketHelper.WSWaitEvent("Page.domContentEventFired");  // Wait loading DOM (document.onDOMContentLoaded event)

                // Verify that falcorCache data exist, this data exist only when logged
                UpdateStatus("Verification of data in progress... please wait");
                string htmlPage = WebSocketHelper.WSRequest("Runtime.evaluate", "{'expression': 'document.documentElement.outerHTML'}")["result"]["result"]["value"].ToString();

                if (string.IsNullOrEmpty(htmlPage))
                {
                    throw new NFAuthException("An unexpected problem has occurred, please try again.");
                }

                JObject reactContext = Helper.ExtractJson(htmlPage, "reactContext");
                if (reactContext == null)
                {
                    // An error is happened in the reactContext extraction? try go on
                    UpdateStatus("Error failed to check account membership status, try a simple check");
                    if (htmlPage.Contains("falcorCache") == false)
                    {
                        throw new NFAuthException("Error unable to find falcorCache data.");
                    }
                }
                else
                {
                    // Check the membership status
                    string membershipStatus = reactContext["models"]["userInfo"]["data"]["membershipStatus"].ToString();
                    if (membershipStatus != "CURRENT_MEMBER")
                    {
                        UpdateStatus("The account membership status is: " + membershipStatus);
                        throw new NFAuthException("Your login can not be used. The possible causes are account not confirmed/renewed/reactivacted.");
                    }
                }

                WebSocketHelper.WSWaitEvent("Page.loadEventFired");  // Wait loading page (window.onload event)

                UpdateStatus("File creation in progress... please wait");

                // Get all cookies
                JObject JOCookies = WebSocketHelper.WSRequest("Network.getAllCookies");
                if (JOCookies == null)
                {
                    throw new NFAuthException("WebSocket response for Cookies not received");
                }

                JArray cookies = JOCookies["result"]["cookies"].ToObject <JArray>();
                Helper.AssertCookies(cookies);

                // Generate a random PIN for access to "NFAuthentication.key" file
                string pin = new Random().Next(1000, 9999).ToString();

                // Create file data structure
                JObject data_content = new JObject();
                data_content["cookies"] = cookies;
                JObject data = new JObject();
                data["app_name"]    = Assembly.GetExecutingAssembly().GetName().Name;
                data["app_version"] = Assembly.GetExecutingAssembly().GetName().Version.ToString();
                data["app_system"]  = "Windows";
                data["app_author"]  = "CastagnaIT";
                data["timestamp"]   = (int)DateTime.UtcNow.AddDays(5).Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
                data["data"]        = data_content;

                // Save the "NFAuthentication.key" file
                Helper.SaveData(data, pin);

                // Close the browser
                WebSocketHelper.WSRequest("Browser.close");

                string strMessage = "Operations completed!\r\nThe 'NFAuthentication.key' file has been saved in current folder.\r\nYour PIN protection is: " + pin;
                UpdateStatus(strMessage);

                Dispatcher.BeginInvoke(new Action(() =>
                {
                    BtnCancel.IsEnabled = false;
                    BtnStart.IsEnabled  = true;
                    MessageBox.Show(this, strMessage, this.Title);
                }), DispatcherPriority.Background);
            }
            catch (ThreadAbortException)
            {
                Helper.TerminateChromeInstance(chromePid);
            }
            catch (NFAuthException exc)
            {
                UpdateStatus(exc.Message);
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    BtnCancel.IsEnabled = false;
                    BtnStart.IsEnabled  = true;
                    MessageBox.Show(this, exc.Message, this.Title);
                }), DispatcherPriority.Background);

                Helper.TerminateChromeInstance(chromePid);
            }
            catch (Exception exc)
            {
                // NOTE: the stacktrace info output the error line number only if the .pdb file is included
                UpdateStatus("Error: " + exc.Message + Environment.NewLine + Environment.NewLine + exc.ToString() + Environment.NewLine + exc.StackTrace);
                Dispatcher.BeginInvoke(new Action(() =>
                {
                    BtnCancel.IsEnabled = false;
                    BtnStart.IsEnabled  = true;
                    MessageBox.Show(this, exc.Message, this.Title);
                }), DispatcherPriority.Background);

                Helper.TerminateChromeInstance(chromePid);
            }
            finally
            {
                WebSocketHelper.CloseWebsocket();
            }
        }