Exemplo n.º 1
0
        public static async Task PuppeteerOpenBrowser(BotData data)
        {
            data.Logger.LogHeader();

            // Check if there is already an open browser
            var oldBrowser = data.TryGetObject <PuppeteerSharp.Browser>("puppeteer");

            if (oldBrowser is not null && !oldBrowser.IsClosed)
            {
                data.Logger.Log("The browser is already open, close it if you want to open a new browser", LogColors.DarkSalmon);
                return;
            }

            var args = data.ConfigSettings.PuppeteerSettings.CommandLineArgs;

            if (data.Proxy != null && data.UseProxy)
            {
                if (data.Proxy.Type == ProxyType.Http || !data.Proxy.NeedsAuthentication)
                {
                    args += $" --proxy-server={data.Proxy.Type.ToString().ToLower()}://{data.Proxy.Host}:{data.Proxy.Port}";
                }
                else
                {
                    var proxyType   = data.Proxy.Type == ProxyType.Socks5 ? Yove.Proxy.ProxyType.Socks5 : Yove.Proxy.ProxyType.Socks4;
                    var proxyClient = new ProxyClient(
                        data.Proxy.Host, data.Proxy.Port,
                        data.Proxy.Username, data.Proxy.Password,
                        proxyType);
                    data.SetObject("puppeteer.yoveproxy", proxyClient);
                    args += $" --proxy-server={proxyClient.GetProxy(null).Authority}";
                }
            }

            // Configure the options
            var launchOptions = new LaunchOptions
            {
                Args            = new string[] { args },
                ExecutablePath  = data.Providers.PuppeteerBrowser.ChromeBinaryLocation,
                Headless        = data.ConfigSettings.PuppeteerSettings.Headless,
                DefaultViewport = null // This is important
            };

            // Add the plugins
            var extra = new PuppeteerExtra();

            extra.Use(new StealthPlugin());

            // Launch the browser
            var browser = await extra.LaunchAsync(launchOptions);

            browser.IgnoreHTTPSErrors = data.ConfigSettings.PuppeteerSettings.IgnoreHttpsErrors;

            // Save the browser for further use
            data.SetObject("puppeteer", browser);
            var page = (await browser.PagesAsync()).First();

            SetPageAndFrame(data, page);
            await SetPageLoadingOptions(data, page);

            // Authenticate if the proxy requires auth
            if (data.UseProxy && data.Proxy is { NeedsAuthentication : true, Type : ProxyType.Http } proxy)
            {
                await page.AuthenticateAsync(new Credentials { Username = proxy.Username, Password = proxy.Password });
            }

            data.Logger.Log($"{(launchOptions.Headless ? "Headless " : "")}Browser opened successfully!", LogColors.DarkSalmon);
        }