示例#1
0
    def __init__(self, headless=False):
        if headless:
            enable_headless()
        self.driver = webdriver.Chrome(executable_path=binary_path,
                                       options=options)
        self.credit_card = {}
        self.card_pn = ""
        self.card_series = ""
        try:
            if path.exists(CONFIG_PATH):
                with open(CONFIG_PATH) as json_file:
                    config = json.load(json_file)
                    username = config["username"]
                    password = config["password"]
                    self.card_pn = config.get("card_pn")
                    self.card_series = config["card_series"]
                    self.credit_card["name"] = config["credit_card"]["name"]
                    self.credit_card["number"] = config["credit_card"][
                        "number"]
                    self.credit_card["cvv"] = config["credit_card"]["cvv"]
                    self.credit_card["expiration_month"] = config[
                        "credit_card"]["expiration_month"]
                    self.credit_card["expiration_year"] = config[
                        "credit_card"]["expiration_year"]
        except Exception as e:
            log.error(
                f"This is most likely an error with your {CONFIG_PATH} file.")
            raise e

        self.login(username, password)
示例#2
0
    def __init__(self, notification_handler, headless=False):
        self.notification_handler = notification_handler
        self.url_list = []
        self.reserve = []
        if headless:
            enable_headless()
        options.add_argument(f"user-data-dir=.profile-wmrt")
        try:
            self.driver = webdriver.Chrome(executable_path=binary_path,
                                           options=options)
            self.wait = WebDriverWait(self.driver, 5)
        except Exception as e:
            log.error(e)
            exit(1)
        if path.exists(AUTOBUY_CONFIG_PATH):
            with open(AUTOBUY_CONFIG_PATH) as json_file:
                try:
                    config = json.load(json_file)
                    self.username = config["username"]
                    self.password = config["password"]
                    self.civ = config["civ"]
                    self.url_groups = int(config["url_groups"])
                    self.walmart_website = config.get("walmart_website",
                                                      "walmart.com")
                    for x in range(self.url_groups):
                        self.url_list.append(config[f"url_list_{x+1}"])
                        self.reserve.append(float(config[f"reserve_{x+1}"]))
                    # assert isinstance(self.url_list, list)
                except Exception:
                    log.error(
                        "walmart_config.json file not formatted properly: https://github.com/Hari-Nagarajan/nvidia-bot/wiki/Usage#json-configuration"
                    )
                    exit(0)
        else:
            log.error(
                "No config file found, see here on how to fix this: https://github.com/Hari-Nagarajan/nvidia-bot/wiki/Usage#json-configuration"
            )
            exit(0)

        for key in WALMART_URLS.keys():
            WALMART_URLS[key] = WALMART_URLS[key].format(
                domain=self.walmart_website)
        self.driver.get(WALMART_URLS["BASE_URL"])
        log.info("Waiting for home page.")
        if self.driver.title in CAPTCHA_URL:
            self.defeat_captcha(self.driver.current_url)
        if self.is_logged_in():
            log.info("Already logged in")
        else:
            log.info("Lets log in.")
            log.info("Wait for Sign In page")
            self.login()
            self.notification_handler.send_notification(
                "Logged in and running", False)
            log.info("Waiting 5 seconds.")
            time.sleep(
                5
            )  # We can remove this once I get more info on the phone verification page.
示例#3
0
    def __init__(self, notification_handler, headless=False):
        self.notification_handler = notification_handler
        if headless:
            enable_headless()
        options.add_argument(f"user-data-dir=.profile-amz")
        try:
            self.driver = webdriver.Chrome(executable_path=binary_path,
                                           options=options)
            self.wait = WebDriverWait(self.driver, 10)
        except SessionNotCreatedException as e:
            log.error(e)
            exit(1)
        except Exception as e:
            log.error(e)
        if path.exists(AUTOBUY_CONFIG_PATH):
            with open(AUTOBUY_CONFIG_PATH) as json_file:
                try:
                    config = json.load(json_file)
                    self.username = config["username"]
                    self.password = config["password"]
                    self.asin_list = config["asin_list"]
                    self.reserve = float(config["reserve"])
                    self.amazon_website = config.get("amazon_website",
                                                     "smile.amazon.com")
                    assert isinstance(self.asin_list, list)
                except Exception:
                    log.error(
                        "amazon_config.json file not formatted properly: https://github.com/Hari-Nagarajan/nvidia-bot/wiki/Usage#json-configuration"
                    )
                    exit(0)
        else:
            log.error(
                "No config file found, see here on how to fix this: https://github.com/Hari-Nagarajan/nvidia-bot/wiki/Usage#json-configuration"
            )
            exit(0)

        for key in AMAZON_URLS.keys():
            AMAZON_URLS[key] = AMAZON_URLS[key].format(
                domain=self.amazon_website)
        self.driver.get(AMAZON_URLS["BASE_URL"])
        log.info("Waiting for home page.")
        self.check_if_captcha(self.wait_for_pages, HOME_PAGE_TITLES)

        if self.is_logged_in():
            log.info("Already logged in")
        else:
            log.info("Lets log in.")

            is_smile = "smile" in AMAZON_URLS["BASE_URL"]
            xpath = '//*[@id="ge-hello"]/div/span/a' if is_smile else '//*[@id="nav-link-accountList"]/div/span'
            selenium_utils.button_click_using_xpath(self.driver, xpath)
            log.info("Wait for Sign In page")
            self.check_if_captcha(self.wait_for_pages, SIGN_IN_TITLES)
            self.login()
            log.info("Waiting 15 seconds.")
            time.sleep(
                15
            )  # We can remove this once I get more info on the phone verification page.
示例#4
0
 def __init__(self, username, password, headless=False):
     self.notification_handler = NotificationHandler()
     if headless:
         enable_headless()
     self.driver = webdriver.Chrome(executable_path=binary_path, options=options)
     self.wait = WebDriverWait(self.driver, 10)
     self.username = username
     self.password = password
     self.login()
     time.sleep(3)
示例#5
0
    def create_driver(self):
        if self.setup_driver:

            if self.headless:
                enable_headless()

            # profile_amz = ".profile-amz"
            # # keep profile bloat in check
            # if os.path.isdir(profile_amz):
            #     os.remove(profile_amz)
            prefs = {
                "profile.password_manager_enabled": False,
                "credentials_enable_service": False,
            }
            if self.no_image:
                prefs["profile.managed_default_content_settings.images"] = 2
            else:
                prefs["profile.managed_default_content_settings.images"] = 0
            options.add_experimental_option("prefs", prefs)
            options.add_argument(f"user-data-dir=.profile-amz")
            if not self.slow_mode:
                options.set_capability("pageLoadStrategy", "none")

            self.setup_driver = False

        # Delete crashed, so restore pop-up doesn't happen
        path_to_prefs = os.path.join(
            os.path.dirname(os.path.abspath("__file__")),
            ".profile-amz",
            "Default",
            "Preferences",
        )
        try:
            with fileinput.FileInput(path_to_prefs, inplace=True) as file:
                for line in file:
                    print(line.replace("Crashed", "none"), end="")
        except FileNotFoundError:
            pass
        try:
            self.driver = webdriver.Chrome(executable_path=binary_path, options=options)
            self.wait = WebDriverWait(self.driver, 10)
            self.get_webdriver_pids()
        except Exception as e:
            log.error(e)
            log.warning(
                "You probably have a previous Chrome window open. You should close it"
            )
            return False

        return True
示例#6
0
 def __init__(self, username, password, headless=False):
     self.notification_handler = NotificationHandler()
     if headless:
         enable_headless()
     self.driver = webdriver.Chrome(executable_path=binary_path, options=options)
     self.wait = WebDriverWait(self.driver, 10)
     self.username = username
     self.password = password
     self.driver.get(BASE_URL)
     if self.is_logged_in():
         log.info("Already logged in")
     else:
         self.login()
     time.sleep(3)
示例#7
0
 def __init__(self, username, password, item_url, headless=False):
     self.notification_handler = NotificationHandler()
     if headless:
         enable_headless()
     h = hashlib.md5(item_url.encode()).hexdigest()
     options.add_argument(f"user-data-dir=.profile-amz-{h}")
     self.driver = webdriver.Chrome(executable_path=binary_path,
                                    options=options)
     self.wait = WebDriverWait(self.driver, 10)
     self.username = username
     self.password = password
     self.driver.get(BASE_URL)
     if self.is_logged_in():
         log.info("Already logged in")
     else:
         self.login()
         time.sleep(15)
示例#8
0
    def __init__(self, headless=False):
        self.notification_handler = NotificationHandler()
        if headless:
            enable_headless()
        options.add_argument(f"user-data-dir=.profile-amz")
        self.driver = webdriver.Chrome(executable_path=binary_path,
                                       options=options)
        self.wait = WebDriverWait(self.driver, 10)
        if path.exists(AUTOBUY_CONFIG_PATH):
            with open(AUTOBUY_CONFIG_PATH) as json_file:
                try:
                    config = json.load(json_file)
                    self.username = config["username"]
                    self.password = config["password"]
                    self.asin_list = config["asin_list"]
                    self.amazon_website = config.get("amazon_website",
                                                     "amazon.com")
                    assert isinstance(self.asin_list, list)
                except Exception:
                    raise InvalidAutoBuyConfigException(
                        "amazon_config.json file not formatted properly.")
        else:
            raise InvalidAutoBuyConfigException(
                "Missing amazon_config.json file.")

        for key in AMAZON_URLS.keys():
            AMAZON_URLS[key] = AMAZON_URLS[key].format(self.amazon_website)
        print(AMAZON_URLS)
        self.driver.get(AMAZON_URLS["BASE_URL"])
        log.info("Waiting for home page.")
        self.check_if_captcha(self.wait_for_pages, HOME_PAGE_TITLES)

        if self.is_logged_in():
            log.info("Already logged in")
        else:
            log.info("Lets log in.")
            selenium_utils.button_click_using_xpath(
                self.driver, '//*[@id="nav-link-accountList"]/div/span')
            log.info("Wait for Sign In page")
            self.check_if_captcha(self.wait_for_pages, SIGN_IN_TITLES)
            self.login()
            log.info("Waiting 15 seconds.")
            time.sleep(
                15
            )  # We can remove this once I get more info on the phone verification page.
示例#9
0
    def __init__(
        self,
        notification_handler,
        headless=False,
        checkshipping=False,
        random_delay=False,
        detailed=False,
        used=False,
        single_shot=False,
        no_screenshots=False,
    ):
        self.notification_handler = notification_handler
        self.asin_list = []
        self.reserve = []
        self.checkshipping = checkshipping
        self.button_xpaths = BUTTON_XPATHS
        self.random_delay = random_delay
        self.detailed = detailed
        self.used = used
        self.single_shot = single_shot
        self.no_screenshots = no_screenshots
        self.start_time = time.time()
        self.start_time_atc = 0

        if not self.no_screenshots:
            if not os.path.exists("screenshots"):
                try:
                    os.makedirs("screenshots")
                except:
                    raise

        if not os.path.exists("html_saves"):
            try:
                os.makedirs("html_saves")
            except:
                raise

        if os.path.exists(CREDENTIAL_FILE):
            credential = load_encrypted_config(CREDENTIAL_FILE)
            self.username = credential["username"]
            self.password = credential["password"]
        else:
            log.info("No credential file found, let's make one")
            credential = self.await_credential_input()
            create_encrypted_config(credential, CREDENTIAL_FILE)
            self.username = credential["username"]
            self.password = credential["password"]

        if os.path.exists(AUTOBUY_CONFIG_PATH):
            with open(AUTOBUY_CONFIG_PATH) as json_file:
                try:
                    config = json.load(json_file)
                    self.asin_groups = int(config["asin_groups"])
                    self.amazon_website = config.get("amazon_website",
                                                     "smile.amazon.com")
                    for x in range(self.asin_groups):
                        self.asin_list.append(config[f"asin_list_{x + 1}"])
                        self.reserve.append(float(config[f"reserve_{x + 1}"]))
                    # assert isinstance(self.asin_list, list)
                except Exception:
                    log.error(
                        "amazon_config.json file not formatted properly: https://github.com/Hari-Nagarajan/fairgame/wiki/Usage#json-configuration"
                    )
                    exit(0)
        else:
            log.error(
                "No config file found, see here on how to fix this: https://github.com/Hari-Nagarajan/fairgame/wiki/Usage#json-configuration"
            )
            exit(0)

        if headless:
            enable_headless()

        # profile_amz = ".profile-amz"
        # # keep profile bloat in check
        # if os.path.isdir(profile_amz):
        #     os.remove(profile_amz)
        options.add_argument(f"user-data-dir=.profile-amz")
        # options.page_load_strategy = "eager"

        try:
            self.driver = webdriver.Chrome(executable_path=binary_path,
                                           options=options)
            self.wait = WebDriverWait(self.driver, 10)
        except Exception as e:
            log.error(e)
            exit(1)

        for key in AMAZON_URLS.keys():
            AMAZON_URLS[key] = AMAZON_URLS[key].format(
                domain=self.amazon_website)
示例#10
0
    def __init__(self, task_id, status_signal, image_signal, product, profile,
                 proxy, monitor_delay, error_delay):
        self.task_id, self.status_signal, self.image_signal, self.product, self.profile, self.monitor_delay, self.error_delay = task_id, status_signal, image_signal, product, profile, float(
            monitor_delay), float(error_delay)
        self.sku_id = parse.parse_qs(parse.urlparse(
            self.product).query)['skuId'][0]
        self.session = requests.Session()
        # TODO: Refactor Bird Bot Auto Checkout Functionality. For now, it will just open the cart link.
        self.auto_buy = False
        self.browser = self.init_driver()
        self.product_image = None
        starting_msg = "Starting Best Buy Task"
        if settings.dont_buy:
            starting_msg = "Starting Best Buy Task in dev mode - Phoenix Bot will not actually checkout. Check Settings page to disable Dev Mode"
        self.status_signal.emit(create_msg(starting_msg, "normal"))

        # TODO: Add Product Image To UI

        if proxy:
            self.session.proxies.update(proxy)

        adapter = HTTPAdapter(max_retries=Retry(
            total=3,
            backoff_factor=1,
            status_forcelist=[429, 500, 502, 503, 504],
            method_whitelist=["HEAD", "GET", "OPTIONS", "POST"],
        ))
        self.session.mount("https://", adapter)
        self.session.mount("http://", adapter)

        response = self.session.get(BEST_BUY_PDP_URL.format(sku=self.sku_id),
                                    headers=DEFAULT_HEADERS)
        self.status_signal.emit(
            create_msg(f"PDP Request: {response.status_code}", "normal"))
        self.product = response.url
        self.status_signal.emit(
            create_msg(f"Product URL: {self.product}", "normal"))
        self.session.get(self.product)
        self.status_signal.emit(
            create_msg(f"Product URL Request: {response.status_code}",
                       "normal"))
        self.status_signal.emit(
            create_msg("Loading headless driver.", "normal"))

        # TODO - check if this still messes up the cookies for headless
        headless = False
        if headless:
            enable_headless()
        options.add_argument(f"User-Agent={settings.userAgent}")

        self.status_signal.emit(
            create_msg("Loading https://www.bestbuy.com/", "normal"))
        self.login()

        self.browser.get(self.product)
        cookies = self.browser.get_cookies()

        [
            self.session.cookies.set_cookie(
                requests.cookies.create_cookie(domain=cookie["domain"],
                                               name=cookie["name"],
                                               value=cookie["value"]))
            for cookie in cookies
        ]

        self.status_signal.emit(
            create_msg("Calling location/v1/US/approximate", "normal"))
        status_code = self.session.get(
            "https://www.bestbuy.com/location/v1/US/approximate",
            headers=DEFAULT_HEADERS).status_code
        self.status_signal.emit(create_msg(f"{status_code}", "normal"))
        self.status_signal.emit(
            create_msg("Calling basket/v1/basketCount", "normal"))
        status_code = self.session.get(
            "https://www.bestbuy.com/basket/v1/basketCount",
            headers=DEFAULT_HEADERS).status_code
        self.status_signal.emit(create_msg(f"{status_code}", "normal"))
        self.check_stock()
示例#11
0
    def __init__(self, sku_id, notification_handler, headless=False):
        self.notification_handler = notification_handler
        self.sku_id = sku_id
        self.session = requests.Session()
        self.auto_buy = False
        self.account = {"username": "", "password": ""}

        adapter = HTTPAdapter(max_retries=Retry(
            total=3,
            backoff_factor=1,
            status_forcelist=[429, 500, 502, 503, 504],
            method_whitelist=["HEAD", "GET", "OPTIONS", "POST"],
        ))
        self.session.mount("https://", adapter)
        self.session.mount("http://", adapter)

        response = self.session.get(BEST_BUY_PDP_URL.format(sku=self.sku_id),
                                    headers=DEFAULT_HEADERS)
        log.info(f"PDP Request: {response.status_code}")
        self.product_url = response.url
        log.info(f"Product URL: {self.product_url}")

        self.session.get(self.product_url)
        log.info(f"Product URL Request: {response.status_code}")

        if self.auto_buy:
            log.info("Loading headless driver.")
            if headless:
                enable_headless(
                )  # TODO - check if this still messes up the cookies.
            options.add_argument(
                "user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36"
            )

            self.driver = webdriver.Chrome(
                executable_path=binary_path,
                options=options,
            )
            log.info("Loading https://www.bestbuy.com.")
            self.login()

            self.driver.get(self.product_url)
            cookies = self.driver.get_cookies()

            [
                self.session.cookies.set_cookie(
                    requests.cookies.create_cookie(
                        domain=cookie["domain"],
                        name=cookie["name"],
                        value=cookie["value"],
                    )) for cookie in cookies
            ]

            # self.driver.quit()

            log.info("Calling location/v1/US/approximate")
            log.info(
                self.session.get(
                    "https://www.bestbuy.com/location/v1/US/approximate",
                    headers=DEFAULT_HEADERS,
                ).status_code)

            log.info("Calling basket/v1/basketCount")
            log.info(
                self.session.get(
                    "https://www.bestbuy.com/basket/v1/basketCount",
                    headers={
                        "x-client-id": "browse",
                        "User-Agent":
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36",
                        "Accept": "application/json",
                    },
                ).status_code)
示例#12
0
    def __init__(self, gpu, locale="en_us", test=False, headless=False):
        self.product_ids = set([])
        self.cli_locale = locale.lower()
        self.locale = self.map_locales()
        self.session = requests.Session()
        self.gpu = gpu
        self.enabled = True
        self.auto_buy_enabled = False
        self.attempt = 0
        self.started_at = datetime.now()
        self.test = test

        self.gpu_long_name = GPU_DISPLAY_NAMES[gpu]

        if path.exists(AUTOBUY_CONFIG_PATH):
            with open(AUTOBUY_CONFIG_PATH) as json_file:
                try:
                    self.config = json.load(json_file)
                except Exception as e:
                    log.error(
                        "Your `autobuy_config.json` file is not valid json.")
                    raise e
                if self.has_valid_creds():
                    self.nvidia_login = self.config["NVIDIA_LOGIN"]
                    self.nvidia_password = self.config["NVIDIA_PASSWORD"]
                    self.auto_buy_enabled = self.config["FULL_AUTOBUY"]
                    self.cvv = self.config.get("CVV")
                    self.interval = int(self.config.get("INTERVAL", 5))
                else:
                    raise InvalidAutoBuyConfigException(self.config)
        else:
            log.info("No Autobuy creds found.")

        # Disable auto_buy_enabled if the user does not provide a bool.
        if type(self.auto_buy_enabled) != bool:
            self.auto_buy_enabled = False

        adapter = TimeoutHTTPAdapter(max_retries=Retry(
            total=10,
            backoff_factor=1,
            status_forcelist=[429, 500, 502, 503, 504],
            method_whitelist=["HEAD", "GET", "OPTIONS"],
        ))
        self.session.mount("https://", adapter)
        self.session.mount("http://", adapter)
        self.notification_handler = NotificationHandler()

        log.info("Opening Webdriver")
        if headless:
            enable_headless()
        self.driver = webdriver.Chrome(executable_path=binary_path,
                                       options=options)
        self.sign_in()
        selenium_utils.add_cookies_to_session_from_driver(
            self.driver, self.session)
        log.info("Adding driver cookies to session")

        log.info("Getting product IDs")
        self.token_data = self.get_nvidia_access_token()
        self.payment_option = self.get_payment_options()
        if not self.payment_option.get("id") or not self.cvv:
            log.error(
                "No payment option on account or missing CVV. Disable Autobuy")
            self.auto_buy_enabled = False
        else:
            log.debug(self.payment_option)
            self.ext_ip = self.get_ext_ip()

        if not self.auto_buy_enabled:
            log.info("Closing webdriver")
            self.driver.close()

        self.get_product_ids()
        while len(self.product_ids) == 0:
            log.info(
                f"We have no product IDs for {self.gpu_long_name}, retrying until we get a product ID"
            )
            self.get_product_ids()
            sleep(5)