Esempio n. 1
0
        private static void DownloadBrowser()
        {
            var browserFetcher = new BrowserFetcher();

            browserFetcher.DownloadProgressChanged += (sender, e) =>
            {
                Logger.Debug(
                    $"Browser download progress {e.ProgressPercentage}% - {e.BytesReceived}/{e.TotalBytesToReceive}bytes");
            };

            Logger.Debug("Download browser");
            AsyncHelper.RunSync(() => browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision));

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                var       executablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision);
                const int _0755          =
                    S_IRUSR | S_IXUSR | S_IWUSR
                    | S_IRGRP | S_IXGRP
                    | S_IROTH | S_IXOTH;
                chmod(executablePath, _0755);
            }

            Logger.Debug("Browser downloaded");
        }
Esempio n. 2
0
        private void Form1_Load(object sender, EventArgs e)
        {
            toolStripProgressBar1.Maximum = 100;
            toolStripProgressBar1.Value   = 0;
            Task.Run(async() =>
            {
                var browserFetcher = new BrowserFetcher(new BrowserFetcherOptions()
                {
                    Host = "http://cdn.npm.taobao.org/dist"
                });

                try
                {
                    var cp = Process.GetProcessesByName("chrome");
                    if (cp.Length > 0)
                    {
                        foreach (var item in cp)
                        {
                            if (!item.HasExited && item.MainModule.FileName == browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision))
                            {
                                item.Kill();
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
                browserFetcher.DownloadProgressChanged += Bf_DownloadProgressChanged;
                await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);
            });
        }
Esempio n. 3
0
        public static async Task Main(string[] args)
        {
            Console.WriteLine("This example downloads the default version of Chromium to a custom location");

            var currentDirectory = Directory.GetCurrentDirectory();
            var downloadPath     = Path.Combine(currentDirectory, "..", "..", "CustomChromium");

            Console.WriteLine($"Attemping to set up puppeteer to use Chromium found under directory {downloadPath} ");

            if (!Directory.Exists(downloadPath))
            {
                Console.WriteLine("Custom directory not found. Creating directory");
                Directory.CreateDirectory(downloadPath);
            }

            Console.WriteLine("Downloading Chromium");

            var browserFetcherOptions = new BrowserFetcherOptions {
                Path = downloadPath
            };
            var browserFetcher = new BrowserFetcher(browserFetcherOptions);
            await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);

            var executablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision);

            if (string.IsNullOrEmpty(executablePath))
            {
                Console.WriteLine("Custom Chromium location is empty. Unable to start Chromium. Exiting.\n Press any key to continue");
                Console.ReadLine();
                return;
            }

            Console.WriteLine($"Attemping to start Chromium using executable path: {executablePath}");

            var options = new LaunchOptions {
                Headless = true, ExecutablePath = executablePath
            };

            using (var browser = await Puppeteer.LaunchAsync(options))
                using (var page = await browser.NewPageAsync())
                {
                    await page.GoToAsync("http://www.google.com");

                    var jsSelectAllAnchors = @"Array.from(document.querySelectorAll('a')).map(a => a.href);";
                    var urls = await page.EvaluateExpressionAsync <string[]>(jsSelectAllAnchors);

                    foreach (string url in urls)
                    {
                        Console.WriteLine($"Url: {url}");
                    }
                    Console.WriteLine("Press any key to continue...");
                    Console.ReadLine();
                }
            return;
        }
Esempio n. 4
0
        private async Task InitBrowser()
        {
            var currentDirectory = Directory.GetCurrentDirectory();
            var downloadPath     = Path.Combine(currentDirectory, "ChromeRuntime");

            if (!Directory.Exists(downloadPath))
            {
                Directory.CreateDirectory(downloadPath);
            }

            var browserFetcherOptions = new BrowserFetcherOptions {
                Path = downloadPath
            };
            var browserFetcher = new BrowserFetcher(browserFetcherOptions);
            await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);

            var executablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision);

            if (string.IsNullOrEmpty(executablePath))
            {
                throw new Exception("Failed to initialize browser.");
            }

            List <string> args = new List <string> {
                "--no-sandbox",
                "--disable-setuid-sandbox",
                "--disable-infobars",
                "--window-position=0,0",
                "--ignore-certifcate-errors",
                "--ignore-certifcate-errors-spki-list",
                "--user-agent=\"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\""
            };

            if (!m_Proxy.Equals("NONE"))
            {
                args.Add(string.Format("--proxy-server={0}", m_Proxy));
            }

            var options = new LaunchOptions {
                Headless          = true,
                IgnoreHTTPSErrors = true,
                ExecutablePath    = executablePath,
                Args = args.ToArray()
            };

            m_Browser = await Puppeteer.LaunchAsync(options);
        }
Esempio n. 5
0
        public async Task DescargarNavegador()
        {
            BrowserFetcher browserFetcher = new BrowserFetcher(new BrowserFetcherOptions
            {
                Path = this.path
            });


            await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);

            this.options = new LaunchOptions
            {
                //Args = ...,
                Headless        = false,
                ExecutablePath  = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision),
                DefaultViewport = null,
                Timeout         = 10000
            };
        }
Esempio n. 6
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var bfOptions = new BrowserFetcherOptions();

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                bfOptions.Path = Path.GetTempPath();
            }
            var bf = new BrowserFetcher(bfOptions);
            var a  = bf.DownloadAsync(BrowserFetcher.DefaultChromiumRevision).Result;

            bf.DownloadAsync(BrowserFetcher.DefaultChromiumRevision).Wait();
            var info = new AppInfo
            {
                BrowserExecutablePath = bf.GetExecutablePath(BrowserFetcher.DefaultChromiumRevision)
            };

            builder.Services.AddSingleton(info);
        }
Esempio n. 7
0
        public static async Task <string> GetTextAsync(string url)
        {
            var browserFetcher = new BrowserFetcher(new BrowserFetcherOptions()
            {
                Path = HostPath
            });
            await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision).ConfigureAwait(false);

            using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions()
            {
                Headless = true,
                TransportFactory = AspNetWebSocketTransport.AspNetTransportFactory,
                ExecutablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision)
            }).ConfigureAwait(false))
                using (var page = await browser.NewPageAsync().ConfigureAwait(false))
                {
                    var response = await page.GoToAsync(url).ConfigureAwait(false);

                    return(await response.TextAsync().ConfigureAwait(false));
                }
        }
Esempio n. 8
0
        public override void Configure(IFunctionsHostBuilder builder)
        {
            var bfOptions = new BrowserFetcherOptions();

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                bfOptions.Path = Path.GetTempPath();
            }
            var bf = new BrowserFetcher(bfOptions);

            bf.DownloadAsync(BrowserFetcher.DefaultRevision).Wait();
            var info = new AppInfo
            {
                BrowserExecutablePath = bf.GetExecutablePath(BrowserFetcher.DefaultRevision)
            };

            var port = GetAvailablePort();

            info.RazorPagesServerPort = port;
            builder.Services.AddSingleton(info);

            var webHost = Host.CreateDefaultBuilder()
                          .ConfigureWebHostDefaults(webBuilder =>
            {
                var scriptRoot = Environment.GetEnvironmentVariable("AzureWebJobsScriptRoot");
                System.Console.WriteLine($"Starting web server on port {port}");
                if (!string.IsNullOrEmpty(scriptRoot))
                {
                    webBuilder.UseContentRoot(scriptRoot);
                }

                webBuilder.UseUrls($"http://0.0.0.0:{port}")
                .UseStartup <OfferteTemplater.Startup>();
            })
                          .Build();

            webHost.Start();
        }
Esempio n. 9
0
        private async void GetBrowserLastVersion(BrowserFetcher browserFetcher)
        {
            try
            {
                BytesReceived = 0;

                btnMailRuEmail.Enabled = false;
                btnYandexEmail.Enabled = false;
                btnGmail.Enabled       = false;
                textBox1.Text          = $@"GetBrowserLastVersion() start... - {DateTime.Now} {Environment.NewLine}";
                await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);

                textBox1.AppendText($@"GetExecutablePath - {browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision)}{Environment.NewLine}");
                textBox1.AppendText($@"GetBrowserLastVersion() complete... - {DateTime.Now} {Environment.NewLine}");
                btnMailRuEmail.Enabled = true;
                btnYandexEmail.Enabled = true;
                btnGmail.Enabled       = true;
            }
            catch (Exception exception)
            {
                Log.Error(exception);
            }
        }
Esempio n. 10
0
    public override async void Configure(IFunctionsHostBuilder builder)
    {
        builder.Services.AddHttpClient();

        //builder.Services.AddSingleton<ILoggerProvider, MyLoggerProvider>();

        // for PupeteerSharp browser automation
        var bfOptions = new BrowserFetcherOptions();

        if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            bfOptions.Path = Path.GetTempPath();
        }
        var bf = new BrowserFetcher(bfOptions);
        await bf.DownloadAsync(BrowserFetcher.DefaultChromiumRevision);

        var info = new AppInfo
        {
            BrowserExecutablePath = bf.GetExecutablePath(BrowserFetcher.DefaultChromiumRevision)
        };

        builder.Services.AddSingleton(info);
    }
        public Printer(IWebHostEnvironment env)
        {
            this.env = env;

            templateFolderPath = Path.Combine(env.ContentRootPath, "Print_Templates");
            engine             = new RazorLightEngineBuilder()
                                 // required to have a default RazorLightProject type,
                                 // but not required to create a template from string.
                                 .UseFileSystemProject(templateFolderPath)
                                 .UseMemoryCachingProvider()
                                 .Build();
            var bfOptions = new BrowserFetcherOptions();

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                bfOptions.Path = Path.GetTempPath();
            }
            var bf = new BrowserFetcher(bfOptions);

            bf.DownloadAsync(BrowserFetcher.DefaultRevision).Wait();
            browserExecutablePath = bf.GetExecutablePath(BrowserFetcher.DefaultRevision);
            //revisionInfo = (new BrowserFetcher()).DownloadAsync(BrowserFetcher.DefaultRevision).Result;
        }
Esempio n. 12
0
        public static async Task <string> Capture(string url, string path)
        {
            //return string: path+filename.png
            var currentDirectory = Directory.GetCurrentDirectory();
            var downloadPath     = Path.Combine(currentDirectory, "CustomChromium");

            Console.WriteLine($"Attemping to set up puppeteer to use Chromium found under directory {downloadPath} ");

            if (!Directory.Exists(downloadPath))
            {
                Console.WriteLine("Custom directory not found. Creating directory");
                Directory.CreateDirectory(downloadPath);
            }

            Console.WriteLine("Downloading Chromium...");

            var browserFetcherOptions = new BrowserFetcherOptions {
                Path = downloadPath
            };
            var browserFetcher = new BrowserFetcher(browserFetcherOptions);
            await browserFetcher.DownloadAsync(BrowserFetcher.DefaultRevision);

            var executablePath = browserFetcher.GetExecutablePath(BrowserFetcher.DefaultRevision);

            if (string.IsNullOrEmpty(executablePath))
            {
                Console.WriteLine("Custom Chromium location is empty. Unable to start Chromium. Exiting.\n Press any key to continue");
                Console.ReadLine();
            }

            Console.WriteLine($"Attemping to start Chromium using executable path: {executablePath}");

            var options = new LaunchOptions {
                Headless = true, ExecutablePath = executablePath
            };

            using (var browser = await Puppeteer.LaunchAsync(options))
                using (var page = await browser.NewPageAsync())
                {
                    await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
                    await page.SetViewportAsync(new ViewPortOptions { Width = 1920, Height = 1080 });

                    var waitUntil = new NavigationOptions {
                        Timeout = 0, WaitUntil = new[] { WaitUntilNavigation.Networkidle0 }
                    };
                    await page.GoToAsync(url, waitUntil);

                    #region Screenshot Dashboard:
                    var optionsScreenShot = new ScreenshotOptions {
                        FullPage = true
                    };
                    //Đường dẫn lưu file
                    if (!Directory.Exists(path))
                    {
                        Console.WriteLine("SavePath directory not found. Creating directory");
                        Directory.CreateDirectory(path);
                    }
                    string date       = DateTime.Now.ToString("yyyyMMddHHmmss");
                    var    outputfile = path + "/capture_" + date + ".png";
                    await page.ScreenshotAsync(outputfile, optionsScreenShot);

                    #endregion
                    await page.CloseAsync();

                    //return string = path+filename.png
                    return(outputfile);
                }
        }