Ejemplo n.º 1
0
        private static string GetElementScreenshot(long buttonNodeId, IChromeSession chromeSession)
        {
            var buttonBox = chromeSession.SendAsync(new GetBoxModelCommand
            {
                NodeId = buttonNodeId
            });
            var buttonBoxRes = buttonBox.Result.Result.Model;

            double leftBegin = buttonBoxRes.Border[0];
            double leftEnd   = buttonBoxRes.Border[2];
            double topBegin  = buttonBoxRes.Border[1];
            double topEnd    = buttonBoxRes.Border[5];

            var screenshot = chromeSession.SendAsync(new CaptureScreenshotCommand {
                Format = "png"
            }).Result;
            var data6 = Convert.FromBase64String(screenshot.Result.Data);

            int leftTopX = Convert.ToInt32(leftBegin);
            int leftTopY = Convert.ToInt32(topBegin);
            int X        = Convert.ToInt32(leftEnd - leftBegin);
            int Y        = Convert.ToInt32(topEnd - topBegin);

            Rectangle rectangle = new Rectangle(leftTopX, leftTopY, X, Y);
            Bitmap    bmp;

            using (var ms = new MemoryStream(data6))
            {
                bmp = new Bitmap(ms);
            }
            Bitmap bmp2 = bmp.Clone(rectangle, PixelFormat.Format64bppPArgb);

            bmp2.Save("captchaFromArray.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            return(null);
        }
Ejemplo n.º 2
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            if (!init)
            {
                var token = new Random().Next();
                browser.LoadHtml(token.ToString());
                init = true;

                JsManager.Instance.Clear();
                requests     = new List <RequestWillBeSentEvent>();
                requests_id  = new Dictionary <string, RequestWillBeSentEvent>();
                what_is_near = new Dictionary <string, HashSet <int> >();
                response     = new Dictionary <string, ResponseReceivedEvent>();
                scripts      = new List <MasterDevs.ChromeDevTools.Protocol.Chrome.Debugger.ScriptParsedEvent>();
                ss           = await ChromeDevTools.Create();

                (child = new CustomCrawlerDynamicsRequest(ss, this)).Show();
                init_overlay();

                _ = Application.Current.Dispatcher.BeginInvoke(new Action(
                                                                   delegate
                {
                    Navigate.IsEnabled = false;
                }));
            }

            browser.Load(URLText.Text);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Для присоединения к хрому без запуска процесса
        /// </summary>
        /// <param name="port"></param>
        /// <returns></returns>
        async public Task <CallResult <IChromeSession> > GetChromeSession(int port)
        {
            CallResult <IChromeSession> chromeSessionResult = new CallResult <IChromeSession>();

            ChromeSessionInfo sessionInfo           = null;
            CallResult <ChromeSessionInfo[]> result = await GetSessionInfo(port);

            if (result.Success)
            {
                sessionInfo = result.Data[0];
            }
            else
            {
                chromeSessionResult.Error = new UsefulThings.Error(result.Error.Message);
                return(chromeSessionResult);
            }

            try
            {
                var chromeSessionFactory = new ChromeSessionFactory();
                chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl);
            }
            catch (Exception ex)
            {
                chromeSessionResult.Error = new UsefulThings.Error(ex.Message);
                return(chromeSessionResult);
            }

            chromeSession.Subscribe <RequestPausedEvent>(requestPausedEvent =>
            {
                RequestPausedEventHandler(requestPausedEvent);
            });

            chromeSession.Subscribe <AuthRequiredEvent>(authRequiredEvent =>
            {
                AuthRequiredEventHandler(authRequiredEvent);
            });

            chromeSession.Subscribe <FrameNavigatedEvent>(frameNavigatedEvent =>
            {
                FrameNavigatedEventHandler(frameNavigatedEvent);
            });

            chromeSession.Subscribe <LoadingFinishedEvent>(loadingFinishedEvent =>
            {
                LoadingFinishedEventHandler(loadingFinishedEvent);
            });

            //enable page
            var pageEnableResult = await chromeSession.SendAsync <Chrome.Page.EnableCommand>();

            //enable network
            var enableNetwork = await chromeSession.SendAsync(new Chrome.Network.EnableCommand());

            await SetUA(null);

            chromeSessionResult.Data = chromeSession;
            return(chromeSessionResult);
        }
Ejemplo n.º 4
0
        public static async System.Threading.Tasks.Task ClearData(IChromeSession chromeSession, string origin, string storageType)
        {
            CommandResponse <ClearDataForOriginCommandResponse> clearStorage = await chromeSession.SendAsync(new ClearDataForOriginCommand()
            {
                Origin       = origin,
                StorageTypes = storageType
            });

            System.Console.WriteLine(clearStorage.Result);
        }
Ejemplo n.º 5
0
        async private void dockIt()
        {
            // STEP 1 - Run Chrome
            var chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner());
            var chromeProcess        = chromeProcessFactory.Create(9401, false, "176.53.142.238:8000", null, "http");
            //var chromeProcess = chromeProcessFactory.Create(9504, false, null, "jniherujherfjio");
            //var chromeProcess1 = chromeProcessFactory.Create(9504, false);
            Process pr = ((RemoteChromeProcess)chromeProcess).Process;
            // STEP 2 - Create a debugging session
            var sessionInfo          = (await chromeProcess.GetSessionInfo()).LastOrDefault();
            var chromeSessionFactory = new ChromeSessionFactory();

            chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl);

            //Process pr = Process.Start("notepad.exe");

            if (hWndDocked != IntPtr.Zero) //don't do anything if there's already a window docked.
            {
                return;
            }

            try
            {
                var navigateResponse = await chromeSession.SendAsync(new NavigateCommand
                {
                    //Url = "https://google.com"
                    Url = "about:blank"
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }



            childHandles = null;
            pDocked      = pr;
            procId       = pr.Id;
            while (hWndDocked == IntPtr.Zero)
            {
                pDocked.WaitForInputIdle(1000); //wait for the window to be ready for input;
                pDocked.Refresh();              //update process info
                if (pDocked.HasExited)
                {
                    return;                            //abort if the process finished before we got a handle.
                }
                hWndDocked = pDocked.MainWindowHandle; //cache the window handle
                //var proceeses=pDocked.
                childHandles = GetAllChildHandles(hWndDocked);
            }
            //Windows API call to change the parent of the target window.
            //It returns the hWnd of the window's parent prior to this call.
            hWndOriginalParent = SetParent(hWndDocked, pannel.Handle);
            //hWndOriginalParent = SetParent(childHandles[1], pannel.Handle);
            //Wire up the event to keep the window sized to match the control
            SizeChanged += window_SizeChanged;
            //Perform an initial call to set the size.
            AlignToPannel();

            //enable network
            var enableNetwork = await chromeSession.SendAsync(new Chrome.Network.EnableCommand());


            await Task.Delay(1000);

            //var navigateResponse = await chromeSession.SendAsync(new NavigateCommand
            //{
            //    Url = "https://google.com"
            //});
            //await Task.Delay(3000);
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            Task.Run(async() =>
            {
                // STEP 1 - Run Chrome
                var chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner());
                //var chromeProcess = chromeProcessFactory.Create(9226, true);
                var chromeProcess = chromeProcessFactory.Create(9401, false, "45.133.32.223:8000", null, "socks5");
                // STEP 2 - Create a debugging session
                var sessionInfo              = (await chromeProcess.GetSessionInfo()).LastOrDefault();
                var chromeSessionFactory     = new ChromeSessionFactory();
                IChromeSession chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl);

                chromeSession.Subscribe <DataReceivedEvent>(dataReceivedEvent =>
                {
                    DataReceivedEventHandler(dataReceivedEvent);
                });

                chromeSession.Subscribe <EventSourceMessageReceivedEvent>(eventSourceMessageReceivedEvent =>
                {
                    EventSourceMessageReceivedEventHandler(eventSourceMessageReceivedEvent);
                });

                chromeSession.Subscribe <RequestWillBeSentEvent>(requestWillBeSentEvent =>
                {
                    RequestWillBeSentEventHandler(requestWillBeSentEvent);
                });

                chromeSession.Subscribe <RequestPausedEvent>(requestPausedEvent =>
                {
                    RequestPausedEventHandler(requestPausedEvent, chromeSession);
                });

                chromeSession.Subscribe <AuthRequiredEvent>(authRequiredEvent =>
                {
                    AuthRequiredEventHandler(authRequiredEvent, chromeSession);
                });

                // STEP 3 - Send a command
                //
                // Here we are sending a commands to tell chrome to set the viewport size
                // and navigate to the specified URL
                await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
                {
                    Width  = ViewPortWidth,
                    Height = ViewPortHeight,
                    Scale  = 1
                });

                //enable network
                var enableNetwork = await chromeSession.SendAsync(new Chrome.Network.EnableCommand());

                //proxy auth
                await ProxyAuthenticate(proxyUser, proxyPass, chromeSession);


                var navigateResponse = await chromeSession.SendAsync(new NavigateCommand
                {
                    Url = "http://mybot.su/webrtcleak.php"
                });
                await Task.Delay(3000);
                Console.WriteLine("NavigateResponse: " + navigateResponse.Id);


                await Task.Delay(10000);
                Console.ReadKey();
                chromeProcess.Dispose();
            }).Wait();
        }
Ejemplo n.º 7
0
        async private static Task ProxyAuthenticate(string proxyUser, string proxyPass, IChromeSession chromeSession)
        {
            chromeSession.ProxyAuthenticate(proxyUser, proxyPass);

            await chromeSession.SendAsync(new Chrome.Network.SetCacheDisabledCommand {
                CacheDisabled = true
            });

            Chrome.Fetch.RequestPattern[] patterns = { new Chrome.Fetch.RequestPattern {
                                                           UrlPattern = "*"
                                                       } };
            await chromeSession.SendAsync(new Chrome.Fetch.EnableCommand {
                HandleAuthRequests = true, Patterns = patterns
            });
        }
Ejemplo n.º 8
0
 private static void RequestPausedEventHandler(RequestPausedEvent requestPausedEvent, IChromeSession chromeSession)
 {
     WriteObject(requestPausedEvent);
     string requestId = requestPausedEvent.RequestId;
     var    cont      = chromeSession.SendAsync(new Chrome.Fetch.ContinueRequestCommand {
         RequestId = requestId
     });
 }
Ejemplo n.º 9
0
        private static void AuthRequiredEventHandler(AuthRequiredEvent authRequiredEvent, IChromeSession chromeSession)
        {
            WriteObject(authRequiredEvent);
            string requestId = authRequiredEvent.RequestId;

            Chrome.Fetch.AuthChallengeResponse acr = new Chrome.Fetch.AuthChallengeResponse {
                Response = "ProvideCredentials",
                Username = proxyUser,
                Password = proxyPass
            };

            var auth = chromeSession.SendAsync(new ContinueWithAuthCommand {
                RequestId             = requestId,
                AuthChallengeResponse = acr
            });
        }
        public CustomCrawlerDynamicsRequest(IChromeSession env, CustomCrawlerDynamics parent)
        {
            InitializeComponent();

            this.parent             = parent;
            RequestList.DataContext = new CustomCrawlerDynamicsRequestDataGridViewModel();
            RequestList.Sorting    += new DataGridSortingEventHandler(new DataGridSorter <CustomCrawlerDynamicsRequestDataGridItemViewModel>(RequestList).SortHandler);

            env.Subscribe <RequestWillBeSentEvent>(x =>
            {
                Task.Run(() => parent.add_request_info(x));
                Application.Current.Dispatcher.BeginInvoke(new Action(
                                                               delegate
                {
                    (RequestList.DataContext as CustomCrawlerDynamicsRequestDataGridViewModel).Items.Add(new CustomCrawlerDynamicsRequestDataGridItemViewModel
                    {
                        Id          = (++index_count).ToString(),
                        Type        = "Request",
                        Url         = x.Request.Url,
                        ContentType = x.Type.ToString(),
                        Request     = x
                    });
                }));
            });

            env.Subscribe <ResponseReceivedEvent>(x =>
            {
                Task.Run(() => parent.add_response_info(x));
                Application.Current.Dispatcher.BeginInvoke(new Action(
                                                               delegate
                {
                    (RequestList.DataContext as CustomCrawlerDynamicsRequestDataGridViewModel).Items.Add(new CustomCrawlerDynamicsRequestDataGridItemViewModel
                    {
                        Id          = (++index_count).ToString(),
                        Type        = "Response",
                        Url         = x.Response.Url,
                        ContentType = x.Type.ToString(),
                        Response    = x
                    });
                }));
            });

            env.Subscribe <DocumentUpdatedEvent>(x =>
            {
                Application.Current.Dispatcher.BeginInvoke(new Action(
                                                               delegate
                {
                    (RequestList.DataContext as CustomCrawlerDynamicsRequestDataGridViewModel).Items.Add(new CustomCrawlerDynamicsRequestDataGridItemViewModel
                    {
                        Id   = (++index_count).ToString(),
                        Type = "DocumentUpdated",
                    });
                }));
            });

            env.Subscribe <ChildNodeInsertedEvent>(x =>
            {
                Application.Current.Dispatcher.BeginInvoke(new Action(
                                                               delegate
                {
                    (RequestList.DataContext as CustomCrawlerDynamicsRequestDataGridViewModel).Items.Add(new CustomCrawlerDynamicsRequestDataGridItemViewModel
                    {
                        Id   = (++index_count).ToString(),
                        Type = "ChildNodeInserted",
                        Url  = $"{x.Node.NodeName}"
                    });
                }));
            });

            env.Subscribe <ScriptParsedEvent>(async x =>
            {
                _ = Task.Run(() => parent.add_script_info(x));
                if (x.Url == "")
                {
                    var pos = "";

                    if (x.StackTrace != null)
                    {
                        pos = $"{x.StackTrace.CallFrames[0].Url}:<{x.StackTrace.CallFrames[0].FunctionName}>:{x.StackTrace.CallFrames[0].LineNumber + 1}:{x.StackTrace.CallFrames[0].ColumnNumber + 1}";

                        // Cannot get the script code later.
                        var src_snippet = await CustomCrawlerDynamics.ss.SendAsync(new GetScriptSourceCommand {
                            ScriptId = x.ScriptId
                        });
                        var src_code = "";
                        if (src_snippet.Result != null)
                        {
                            src_code  = $"/* this code is generated from {pos} */\r\n";
                            src_code += src_snippet.Result.ScriptSource;
                        }

                        await Application.Current.Dispatcher.BeginInvoke(new Action(
                                                                             delegate
                        {
                            (RequestList.DataContext as CustomCrawlerDynamicsRequestDataGridViewModel).Items.Add(new CustomCrawlerDynamicsRequestDataGridItemViewModel
                            {
                                Id               = (++index_count).ToString(),
                                Type             = "AnonymouseParsed",
                                Url              = pos,
                                AnonymouseCode   = src_code,
                                AnonymouseSource = x.StackTrace.CallFrames[0]
                            });
                        }));
                    }
                }
            });

            //Closed += (s, e) =>
            //{
            //    env.Dispose();
            //};
        }
 public static Task <ICommandResponse> SendAsync <T>(this IChromeSession session, T parameter)
 {
     return(session.SendAsync <T>(parameter, CancellationToken.None));
 }
Ejemplo n.º 12
0
        } // End Sub NotMain

        public static async System.Threading.Tasks.Task runVote()
        {
            // synchronization
            System.Threading.ManualResetEventSlim screenshotDone = new System.Threading.ManualResetEventSlim();

            // STEP 1 - Run Chrome
            IChromeProcessFactory chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner());

            using (IChromeProcess chromeProcess = chromeProcessFactory.Create(9222, true))
            {
                // STEP 2 - Create a debugging session
                ChromeSessionInfo[] sessionInfos = await chromeProcess.GetSessionInfo();

                ChromeSessionInfo sessionInfo = (sessionInfos != null && sessionInfos.Length > 0) ?
                                                sessionInfos[sessionInfos.Length - 1]
                    : new ChromeSessionInfo();

                IChromeSessionFactory chromeSessionFactory = new ChromeSessionFactory();
                IChromeSession        chromeSession        = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl);



                CommandResponse <ClearBrowserCacheCommandResponse> clearCache = await chromeSession.SendAsync(new ClearBrowserCacheCommand());

                System.Console.WriteLine(clearCache.Result);


                CommandResponse <ClearBrowserCookiesCommandResponse> clearCookies = await chromeSession.SendAsync(new ClearBrowserCookiesCommand());

                System.Console.WriteLine(clearCookies.Result);

                // CommandResponse<ClearObjectStoreCommandResponse> clearObjectStorage = await chromeSession.SendAsync(new ClearObjectStoreCommand());
                // System.Console.WriteLine(clearObjectStorage.Result);


                // CommandResponse<ClearDataForOriginCommandResponse> clearStorage = await chromeSession.SendAsync(new ClearDataForOriginCommand() { Origin= "www.20min.ch", StorageTypes = "all" });
                // Whatever the correct command for clear everything is...
                await ClearData(chromeSession, "www.20min.ch", "all");
                await ClearData(chromeSession, "20min.ch", "all");
                await ClearData(chromeSession, "*", "all");
                await ClearData(chromeSession, "all", "all");



                // STEP 3 - Send a command
                //
                // Here we are sending a commands to tell chrome to set the viewport size
                // and navigate to the specified URL
                await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
                {
                    Width  = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width,
                    Height = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height,
                    Scale  = 1
                });


                CommandResponse <NavigateCommandResponse> navigateResponse = await chromeSession.SendAsync(new NavigateCommand
                {
                    // Url = "http://www.google.com"
                    // Url = "about:blank"
                    Url = "https://www.20min.ch/schweiz/news/story/GA-wird-teurer--kein-Studentenrabatt-mehr-27426069"
                });

                System.Console.WriteLine("NavigateResponse: " + navigateResponse.Id);



                // STEP 4 - Register for events (in this case, "Page" domain events)
                // send an command to tell chrome to send us all Page events
                // but we only subscribe to certain events in this session

                ICommandResponse pageEnableResult = await chromeSession.SendAsync <MasterDevs.ChromeDevTools.Protocol.Chrome.Page.EnableCommand>();

                System.Console.WriteLine("PageEnable: " + pageEnableResult.Id);

                chromeSession.Subscribe <LoadEventFiredEvent>(loadEventFired =>
                {
                    // we cannot block in event handler, hence the task
                    System.Threading.Tasks.Task2.Run(async() =>
                    {
                        System.Console.WriteLine("LoadEventFiredEvent: " + loadEventFired.Timestamp);

                        /*
                         * long documentNodeId = (await chromeSession.SendAsync(new GetDocumentCommand())).Result.Root.NodeId;
                         * long bodyNodeId =
                         *  (await chromeSession.SendAsync(new QuerySelectorCommand
                         *  {
                         *      NodeId = documentNodeId,
                         *      Selector = "body"
                         *  })).Result.NodeId;
                         *
                         * long height = (await chromeSession.SendAsync(new GetBoxModelCommand { NodeId = bodyNodeId })).Result.Model.Height;
                         */


                        CommandResponse <EvaluateCommandResponse> removePopOver = await chromeSession.SendAsync(new EvaluateCommand
                        {
                            Expression = @"
    window.setTimeout(function(){ 
        var one = document.getElementById('onesignal-popover-cancel-button');
            if(one != null)
        one.click();
    }, 2000);

/*
window.setTimeout(function(){ 
        window.close();
    }, 4000);
*/
    ",
                            // ContextId = 123
                        });



                        CommandResponse <EvaluateCommandResponse> closeWindow = await chromeSession.SendAsync(new EvaluateCommand
                        {
                            // <a href="javascript:window.close(self);">run</a>
                            Expression = @"
console.log('closing');
var a = document.createElement('a');
var linkText = document.createTextNode('T');
a.id = 'lolz';
a.appendChild(linkText);
a.href = 'javascript:window.close(self);';
document.body.appendChild(a);
document.getElementById('lolz').click();
// window.close();
// open(location, '_self').close();
"
                                         // ContextId = 123
                            ,
                            UserGesture = true
                        });
                        System.Console.WriteLine(closeWindow.Result);



                        System.Console.WriteLine("Closing page");
                        var closeTargetResponse = chromeSession.SendAsync(
                            new CloseTargetCommand()
                        {
                            TargetId = navigateResponse.Result.FrameId
                        }
                            );

                        /*
                         * MasterDevs.ChromeDevTools.CommandResponse<CloseTargetCommandResponse> closeTargetResponse =
                         *  await chromeSession.SendAsync(
                         *  new CloseTargetCommand()
                         *  {
                         *      TargetId = navigateResponse.Result.FrameId
                         *  }
                         * );
                         */
                        System.Console.WriteLine("Page closed");
                        System.Console.WriteLine(closeTargetResponse);



                        if (true)
                        {
                            // document.querySelector("#thread3367_msg3367 > div.rate_button > div.clickable.top").click()
                            // document.querySelector("#thread3367_msg3367 > div.rate_button > div.clickable.bottom").click()
                            string threadId      = "3399";
                            string msgId         = "3399";
                            string voteDirection = "bottom"; // top / bottom

                            string votingElement = "#thread" + threadId + "_msg" + msgId + @" > div.rate_button > div.clickable." + voteDirection;

                            string javaScriptToExecute = @"
    (function()
    {
        var elmnt = document.querySelector('" + votingElement + @"');
        if (elmnt != null)
        {
            elmnt.scrollIntoView();
            window.scrollBy(0, -70)
            elmnt.click();
            console.log('https://www.youtube.com/watch?v=h6mJw50OdZ4&t=163');
            console.log('The first honest vote ever in a rotten borough !');
            console.log('CopyLeft 2019 StS');
        }
    })();
    ";


                            CommandResponse <EvaluateCommandResponse> evr = await chromeSession.SendAsync(new EvaluateCommand
                            {
                                Expression = javaScriptToExecute,
                                // ContextId = 123
                            });

                            if (evr.Result.ExceptionDetails != null)
                            {
                                System.Console.WriteLine(evr.Result.ExceptionDetails);
                            }
                            else
                            {
                                System.Console.WriteLine("voted");
                            }
                        }

                        await System.Threading.Tasks.Task2.Delay(3000);

                        // tell the main thread we are done
                        screenshotDone.Set();
                    });
                }); // End Sub LoadEventFired

                // wait for screenshoting thread to (start and) finish
                screenshotDone.Wait();

                System.Console.WriteLine("Exiting ..");
            } // End Using chromeProcess
        }     // End Sub Main(string[] args)
Ejemplo n.º 13
0
        private static void Main(string[] args)
        {
            // synchronization
            var screenshotDone = new ManualResetEventSlim();

            // STEP 1 - Run Chrome
            var     chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner());
            var     chromeProcess        = chromeProcessFactory.Create(9401, false);
            Process pr = ((RemoteChromeProcess)chromeProcess).Process;

            // STEP 2 - Create a debugging session
            var            sessionInfoArray     = chromeProcess.GetSessionInfo().Result;
            var            sessionInfo          = sessionInfoArray.LastOrDefault();
            var            chromeSessionFactory = new ChromeSessionFactory();
            IChromeSession chromeSession        = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl, pr);

            Task.Run(async() =>
            {
                /*
                 * ProcessStartInfo psiOpt = new ProcessStartInfo("cmd.exe", "/C netstat -a -n -o");
                 * psiOpt.WindowStyle = ProcessWindowStyle.Hidden;
                 * psiOpt.RedirectStandardOutput = true;
                 * psiOpt.UseShellExecute = false;
                 * psiOpt.CreateNoWindow = true;
                 * // запускаем процесс
                 * Process procCommand = Process.Start(psiOpt);
                 * // получаем ответ запущенного процесса
                 * StreamReader srIncoming = procCommand.StandardOutput;
                 * // выводим результат
                 * string[] ss = srIncoming.ReadToEnd().Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                 * StringCollection procStr = new StringCollection();
                 * foreach (string s in ss)
                 * {
                 *  if (s.Contains("9222"))
                 *  {
                 *
                 *      string[] parts = s.Split(null);
                 *      int lenght = parts.Length;
                 *      int pid = Int32.Parse(parts[lenght - 1]);
                 *      var proc = Process.GetProcessById(pid);
                 *      //proc.Kill();
                 *      procStr.Add(s);
                 *  }
                 *
                 *
                 * }
                 *
                 * Console.WriteLine(srIncoming.ReadToEnd());
                 * // закрываем процесс
                 * procCommand.WaitForExit();*/



                //cookies
                var ccs = await chromeSession.SendAsync(new Protocol.Chrome.Network.GetAllCookiesCommand());
                //await chromeSession.SendAsync(new Protocol.Chrome.Network.ClearBrowserCookiesCommand());

                // STEP 3 - Send a command
                //
                // Here we are sending a commands to tell chrome to set the viewport size
                // and navigate to the specified URL
                await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
                {
                    Width  = ViewPortWidth,
                    Height = ViewPortHeight,
                    Scale  = 1
                });

                //enable network
                var enableNetwork = await chromeSession.SendAsync(new Protocol.Chrome.Network.EnableCommand());

                var navigateResponse = await chromeSession.SendAsync(new NavigateCommand
                {
                    Url = "http://mybot.su/login.php"
                });
                await Task.Delay(3000);
                Console.WriteLine("NavigateResponse: " + navigateResponse.Id);

                // STEP 4 - Register for events (in this case, "Page" domain events)
                // send an command to tell chrome to send us all Page events
                // but we only subscribe to certain events in this session
                var pageEnableResult = await chromeSession.SendAsync <Protocol.Chrome.Page.EnableCommand>();
                Console.WriteLine("PageEnable: " + pageEnableResult.Id);

                Console.WriteLine("Taking screenshot");
                var screenshot = await chromeSession.SendAsync(new CaptureScreenshotCommand {
                    Format = "png"
                });

                var data = Convert.FromBase64String(screenshot.Result.Data);
                File.WriteAllBytes("output.png", data);
                Console.WriteLine("Screenshot stored");

                /*
                 * chromeSession.Subscribe<LoadEventFiredEvent>(loadEventFired =>
                 * {
                 *  // we cannot block in event handler, hence the task
                 *  Task.Run(async () =>
                 *  {
                 *      Console.WriteLine("LoadEventFiredEvent: " + loadEventFired.Timestamp);
                 *
                 *      var documentNodeId = (await chromeSession.SendAsync(new GetDocumentCommand())).Result.Root.NodeId;
                 *      var bodyNodeId =
                 *          (await chromeSession.SendAsync(new QuerySelectorCommand
                 *          {
                 *              NodeId = documentNodeId,
                 *              Selector = "body"
                 *          })).Result.NodeId;
                 *      var height = (await chromeSession.SendAsync(new GetBoxModelCommand { NodeId = bodyNodeId })).Result.Model.Height;
                 *
                 *      await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
                 *      {
                 *          Width = ViewPortWidth,
                 *          Height = height,
                 *          Scale = 1
                 *      });
                 *
                 *      await Task.Delay(1000);
                 *
                 *      Console.WriteLine("Taking screenshot");
                 *      var screenshot = await chromeSession.SendAsync(new CaptureScreenshotCommand { Format = "png" });
                 *
                 *      var data = Convert.FromBase64String(screenshot.Result.Data);
                 *      File.WriteAllBytes("output.png", data);
                 *      Console.WriteLine("Screenshot stored");
                 *
                 *      // tell the main thread we are done
                 *      screenshotDone.Set();
                 *  });
                 * });*/

                // wait for screenshoting thread to (start and) finish
                //screenshotDone.Wait();

                ICommandResponse cr = chromeSession.SendAsync <GetDocumentCommand>().Result;
                long docNodeId      = ((CommandResponse <GetDocumentCommandResponse>)cr).Result.Root.NodeId;
                //var dom = Protocol.Chrome.DOM.GetDocumentCommand();

                var qs = chromeSession.SendAsync(new QuerySelectorCommand
                {
                    NodeId   = docNodeId,
                    Selector = "#login_input_username"
                }).Result;
                var emailNodeId = qs.Result.NodeId;

                var sv = chromeSession.SendAsync(new FocusCommand
                {
                    NodeId = emailNodeId
                });

                var it = chromeSession.SendAsync(new ChromeDevTools.Protocol.Chrome.Input.InsertTextCommand
                {
                    Text = "*****@*****.**"
                });

                //pwd
                var qsPwd = chromeSession.SendAsync(new QuerySelectorCommand
                {
                    NodeId   = docNodeId,
                    Selector = "#login_input_password"
                }).Result;
                var pwdNodeId = qsPwd.Result.NodeId;

                var svPwd = chromeSession.SendAsync(new FocusCommand
                {
                    NodeId = pwdNodeId
                });

                var itPwd = chromeSession.SendAsync(new ChromeDevTools.Protocol.Chrome.Input.InsertTextCommand
                {
                    Text = "qwerty"
                });



                await Task.Delay(1000);

                Console.WriteLine("Taking screenshot 2");
                var screenshot2 = await chromeSession.SendAsync(new CaptureScreenshotCommand {
                    Format = "png"
                });

                var data2 = Convert.FromBase64String(screenshot2.Result.Data);
                File.WriteAllBytes("output2.png", data2);
                Console.WriteLine("Screenshot 2 stored");


                //click button
                var qsButton = chromeSession.SendAsync(new QuerySelectorCommand
                {
                    NodeId   = docNodeId,
                    Selector = "body:nth-child(2) div.container:nth-child(1) form:nth-child(21) > button.btn.btn-default:nth-child(4)"
                }).Result;
                var buttonNodeId = qsButton.Result.NodeId;
                Console.WriteLine("buttonNodeId " + buttonNodeId);

                ///take screenshot button
                ///
                string pathToScreenshot = GetElementScreenshot(buttonNodeId, chromeSession);

                var buttonBox = chromeSession.SendAsync(new GetBoxModelCommand
                {
                    NodeId = buttonNodeId
                });
                var buttonBoxRes = buttonBox.Result.Result.Model;

                double leftBegin = buttonBoxRes.Border[0];
                double leftEnd   = buttonBoxRes.Border[2];
                double topBegin  = buttonBoxRes.Border[1];
                double topEnd    = buttonBoxRes.Border[5];

                double x = Math.Round((leftBegin + leftEnd) / 2, 2);
                double y = Math.Round((topBegin + topEnd) / 2, 2);

                try
                {
                    var click = chromeSession.SendAsync(new ChromeDevTools.Protocol.Chrome.Input.DispatchMouseEventCommand
                    {
                        Type       = "mousePressed",
                        X          = x,
                        Y          = y,
                        ClickCount = 1,
                        Button     = "left"
                    });

                    await Task.Delay(100);

                    var clickReleased = chromeSession.SendAsync(new ChromeDevTools.Protocol.Chrome.Input.DispatchMouseEventCommand
                    {
                        Type       = "mouseReleased",
                        X          = x,
                        Y          = y,
                        ClickCount = 1,
                        Button     = "left"
                    });

                    Console.WriteLine("midle " + x + " " + y);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }


                await Task.Delay(5000);

                await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
                {
                    Width  = ViewPortWidth,
                    Height = ViewPortHeight,
                    Scale  = 1
                });

                Console.WriteLine("Taking screenshot 3");
                var screenshot3 = await chromeSession.SendAsync(new CaptureScreenshotCommand {
                    Format = "png"
                });

                var data3 = Convert.FromBase64String(screenshot3.Result.Data);
                File.WriteAllBytes("output3.png", data3);
                Console.WriteLine("Screenshot 3 stored");


                //scrolling

                /*
                 * ICommandResponse cr_ = chromeSession.SendAsync<GetDocumentCommand>().Result;
                 * long docNodeId2 = ((CommandResponse<GetDocumentCommandResponse>)cr_).Result.Root.NodeId;
                 *
                 * var bodyNodeId2 =
                 *          (await chromeSession.SendAsync(new QuerySelectorCommand
                 *          {
                 *              NodeId = docNodeId2,
                 *              Selector = "body"
                 *          })).Result.NodeId;
                 *
                 * var fc = chromeSession.SendAsync(new FocusCommand
                 * {
                 *  NodeId = bodyNodeId2
                 * });*/


                await Task.Delay(100);

                var scroll = chromeSession.SendAsync(new ChromeDevTools.Protocol.Chrome.Input.DispatchMouseEventCommand
                {
                    Type   = "mouseWheel",
                    X      = x,
                    Y      = y,
                    DeltaX = 0,
                    DeltaY = 10000
                });

                await Task.Delay(1000);

                Console.WriteLine("Taking screenshot 4");
                var screenshot4 = await chromeSession.SendAsync(new CaptureScreenshotCommand {
                    Format = "png"
                });
                var data4 = Convert.FromBase64String(screenshot4.Result.Data);
                File.WriteAllBytes("output4.png", data4);
                Console.WriteLine("Screenshot 4 stored");


                //cookies
                var cookies = (await chromeSession.SendAsync(new Protocol.Chrome.Network.GetAllCookiesCommand())).Result.Cookies;


                //cookies to json string format
                var json = Newtonsoft.Json.JsonConvert.SerializeObject(cookies);


                //delete cookies
                await chromeSession.SendAsync(new Protocol.Chrome.Network.ClearBrowserCookiesCommand());


                //check delete cookies
                var cookiesForCheck   = (await chromeSession.SendAsync(new Protocol.Chrome.Network.GetAllCookiesCommand())).Result.Cookies;
                var navigateResponse2 = await chromeSession.SendAsync(new NavigateCommand
                {
                    Url = "http://mybot.su/login.php"
                });

                Console.WriteLine("Taking screenshot 5");
                var screenshot5 = await chromeSession.SendAsync(new CaptureScreenshotCommand {
                    Format = "png"
                });
                var data5 = Convert.FromBase64String(screenshot5.Result.Data);
                File.WriteAllBytes("output5.png", data5);
                Console.WriteLine("Screenshot 5 stored");

                //deserialise cookies
                //set cookies
                JArray ja = JArray.Parse(json);
                List <Protocol.Chrome.Network.Cookie> cookiesList = new List <Protocol.Chrome.Network.Cookie>();
                foreach (var cookie in ja)
                {
                    Console.WriteLine(cookie["Name"]);
                    Console.WriteLine(cookie["Value"]);
                    Console.WriteLine(cookie["Domain"]);
                    Console.WriteLine(cookie["Path"]);
                    Console.WriteLine(cookie["Expires"]);
                    Console.WriteLine(cookie["Size"]);
                    Console.WriteLine(cookie["HttpOnly"]);
                    Console.WriteLine(cookie["Secure"]);
                    Console.WriteLine(cookie["Session"]);
                    Console.WriteLine(cookie["SameSite"]);

                    double expires = Double.Parse(cookie["Expires"].ToString());
                    bool secure    = (cookie["Secure"].ToString() == "true") ? true : false;
                    bool httpOnly  = (cookie["HttpOnly"].ToString() == "true") ? true : false;

                    var setCookie = await chromeSession.SendAsync(new Protocol.Chrome.Network.SetCookieCommand
                    {
                        Name     = cookie["Name"].ToString(),
                        Value    = cookie["Value"].ToString(),
                        Domain   = cookie["Domain"].ToString(),
                        Path     = cookie["Path"].ToString(),
                        Secure   = secure,
                        HttpOnly = httpOnly,
                        SameSite = cookie["SameSite"].ToString(),
                        Expires  = expires
                    });
                }
                await Task.Delay(1000);


                //check cookies settings
                var cookiesForCheck2  = (await chromeSession.SendAsync(new Protocol.Chrome.Network.GetAllCookiesCommand())).Result.Cookies;
                var navigateResponse3 = await chromeSession.SendAsync(new NavigateCommand
                {
                    Url = "http://mybot.su/login.php"
                });

                Console.WriteLine("Taking screenshot 6");
                var screenshot6 = await chromeSession.SendAsync(new CaptureScreenshotCommand {
                    Format = "png"
                });
                var data6 = Convert.FromBase64String(screenshot6.Result.Data);
                File.WriteAllBytes("output6.png", data6);
                Console.WriteLine("Screenshot 6 stored");

                Console.WriteLine("Exiting ..");
                //await chromeSession.SendAsync(new Protocol.Chrome.Network.ClearBrowserCookiesCommand());

                await Task.Delay(3000);
            }).Wait();
            chromeProcess.Dispose();
        }
Ejemplo n.º 14
0
        async public Task <CallResult <IChromeSession> > GetChromeSession(string proxisString, string ua, string proxyProtocol, bool isDebug = false, bool headless = true, string profilePath = null)
        {
            L.Trace();
            CallResult <IChromeSession> chromeSessionResult = new CallResult <IChromeSession>();

            Proxy proxy = (proxisString != null && !String.IsNullOrWhiteSpace(proxisString)) ? new Proxy(proxisString) : null;

            this.isDebug = isDebug;
            var chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner());

            port = GetFreeLocalPort();

            try
            {
                if (proxy != null)
                {
                    string ipPort = proxy.Ip + ":" + proxy.Port;
                    chromeProcess = chromeProcessFactory.Create(port, headless, ipPort, profilePath, proxyProtocol);
                }
                else
                {
                    chromeProcess = chromeProcessFactory.Create(port, headless, null, profilePath, proxyProtocol);
                }

                var sessionInfoArray = await chromeProcess.GetSessionInfo();

                var sessionInfo = sessionInfoArray.LastOrDefault();

                var chromeSessionFactory = new ChromeSessionFactory();
                chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl);

                chromeSession.Subscribe <RequestPausedEvent>(requestPausedEvent =>
                {
                    RequestPausedEventHandler(requestPausedEvent);
                });

                chromeSession.Subscribe <AuthRequiredEvent>(authRequiredEvent =>
                {
                    AuthRequiredEventHandler(authRequiredEvent);
                });

                chromeSession.Subscribe <FrameNavigatedEvent>(frameNavigatedEvent =>
                {
                    FrameNavigatedEventHandler(frameNavigatedEvent);
                });

                chromeSession.Subscribe <LoadingFinishedEvent>(loadingFinishedEvent =>
                {
                    LoadingFinishedEventHandler(loadingFinishedEvent);
                });

                /*
                 * await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
                 * {
                 *  Width = GlobalVars.ViewPortWidth,
                 *  Height = GlobalVars.ViewPortHeight,
                 *  Scale = 1
                 * });*/
                /*
                 * //Target.setDiscoverTargets
                 * var setDiscoverTargetsResult = await chromeSession.SendAsync(new Chrome.Target.SetDiscoverTargetsCommand
                 * {
                 *  Discover=true
                 * });
                 * //Target.createTarget
                 * var createTargetResult = await chromeSession.SendAsync(new Chrome.Target.CreateTargetCommand
                 * {
                 *  Url= "about:blank"
                 * });
                 * string targetId = createTargetResult.Result.TargetId;
                 * //Target.attachToTarget
                 * var attachToTargetResult = await chromeSession.SendAsync(new Chrome.Target.AttachToTargetCommand
                 * {
                 *  TargetId = targetId,
                 *  Flatten=true
                 *
                 * });
                 * string sessionId = attachToTargetResult.Result.SessionId;
                 * chromeSession.MainSessionId = sessionId;*/
                //enable page
                var pageEnableResult = await chromeSession.SendAsync <Chrome.Page.EnableCommand>();

                //Page.getFrameTree
                var getFrameTreeResult = await chromeSession.SendAsync <Chrome.Page.GetFrameTreeCommand>();

                //Target.setAutoAttach
                var setAutoAttachResult = await chromeSession.SendAsync(new Chrome.Target.SetAutoAttachCommand
                {
                    AutoAttach             = true,
                    WaitForDebuggerOnStart = false,
                    Flatten = true
                });

                //Performance.enable
                var performanceEnableResult = await chromeSession.SendAsync <Chrome.Performance.EnableCommand>();

                //enable network
                var enableNetwork = await chromeSession.SendAsync(new Chrome.Network.EnableCommand());
            }
            catch (Exception ex)
            {
                chromeSessionResult.Error = new UsefulThings.Error(ex.Message);
                return(chromeSessionResult);
            }
            await Task.Delay(1000);



            //proxy auth
            if (proxy != null)
            {
                if (!String.IsNullOrWhiteSpace(proxy.Login))
                {
                    await ProxyAuthenticate(proxy.Login, proxy.Pwd);
                }
            }

            await SetUA(ua);

            chromeSessionResult.Data = chromeSession;
            return(chromeSessionResult);
        }
Ejemplo n.º 15
0
        } // End Sub KillHeadless

        private static void Main(string[] args)
        {
            KillHeadless();

            Task.Run(async() =>
            {
                // synchronization
                System.Threading.ManualResetEventSlim screenshotDone = new System.Threading.ManualResetEventSlim();

                // STEP 1 - Run Chrome
                IChromeProcessFactory chromeProcessFactory = new ChromeProcessFactory(new StubbornDirectoryCleaner());
                using (IChromeProcess chromeProcess = chromeProcessFactory.Create(9222, true))
                {
                    // STEP 2 - Create a debugging session
                    //ChromeSessionInfo sessionInfo = (await chromeProcess.GetSessionInfo()).LastOrDefault();
                    ChromeSessionInfo[] sessionInfos = await chromeProcess.GetSessionInfo();
                    ChromeSessionInfo sessionInfo    = (sessionInfos != null && sessionInfos.Length > 0) ?
                                                       sessionInfos[sessionInfos.Length - 1]
                        : new ChromeSessionInfo();

                    IChromeSessionFactory chromeSessionFactory = new ChromeSessionFactory();
                    IChromeSession chromeSession = chromeSessionFactory.Create(sessionInfo.WebSocketDebuggerUrl);

                    // STEP 3 - Send a command
                    //
                    // Here we are sending a commands to tell chrome to set the viewport size
                    // and navigate to the specified URL
                    await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
                    {
                        Width  = ViewPortWidth,
                        Height = ViewPortHeight,
                        Scale  = 1
                    });

                    var navigateResponse = await chromeSession.SendAsync(new NavigateCommand
                    {
                        Url = "http://www.google.com"
                    });
                    System.Console.WriteLine("NavigateResponse: " + navigateResponse.Id);

                    // STEP 4 - Register for events (in this case, "Page" domain events)
                    // send an command to tell chrome to send us all Page events
                    // but we only subscribe to certain events in this session
                    ICommandResponse pageEnableResult = await chromeSession.SendAsync <Protocol.Chrome.Page.EnableCommand>();
                    System.Console.WriteLine("PageEnable: " + pageEnableResult.Id);

                    chromeSession.Subscribe <LoadEventFiredEvent>(loadEventFired =>
                    {
                        // we cannot block in event handler, hence the task
                        Task.Run(async() =>
                        {
                            System.Console.WriteLine("LoadEventFiredEvent: " + loadEventFired.Timestamp);

                            long documentNodeId = (await chromeSession.SendAsync(new GetDocumentCommand())).Result.Root.NodeId;
                            long bodyNodeId     =
                                (await chromeSession.SendAsync(new QuerySelectorCommand
                            {
                                NodeId = documentNodeId,
                                Selector = "body"
                            })).Result.NodeId;

                            long height = (await chromeSession.SendAsync(new GetBoxModelCommand {
                                NodeId = bodyNodeId
                            })).Result.Model.Height;

                            await chromeSession.SendAsync(new SetDeviceMetricsOverrideCommand
                            {
                                Width  = ViewPortWidth,
                                Height = height,
                                Scale  = 1
                            });

                            System.Console.WriteLine("Taking screenshot");
                            var screenshot = await chromeSession.SendAsync(new CaptureScreenshotCommand {
                                Format = "png"
                            });

                            byte[] data = System.Convert.FromBase64String(screenshot.Result.Data);
                            System.IO.File.WriteAllBytes("output.png", data);
                            System.Console.WriteLine("Screenshot stored");


                            PrintToPDFCommand printCommand = new PrintToPDFCommand()
                            {
                                Scale           = 1,
                                MarginTop       = 0,
                                MarginLeft      = 0,
                                MarginRight     = 0,
                                MarginBottom    = 0,
                                PrintBackground = true,
                                Landscape       = false,
                                PaperWidth      = cm2inch(21),
                                PaperHeight     = cm2inch(29.7)
                            };


                            System.Console.WriteLine("Printing PDF");
                            CommandResponse <PrintToPDFCommandResponse> pdf = await chromeSession.SendAsync(printCommand);
                            System.Console.WriteLine("PDF printed.");

                            byte[] pdfData = System.Convert.FromBase64String(pdf.Result.Data);
                            System.IO.File.WriteAllBytes("output.pdf", pdfData);
                            System.Console.WriteLine("PDF stored");


                            // tell the main thread we are done
                            screenshotDone.Set();
                        });
                    });

                    // wait for screenshoting thread to (start and) finish
                    System.Console.WriteLine("Exiting ..");
                    screenshotDone.Wait();
                }
            }).Wait();
        }