MsRewards/modules/driver_tools.py

88 lines
2.8 KiB
Python

import json
import os
from random import uniform
from selenium.common import TimeoutException
from selenium.webdriver import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from modules.Tools.logger import debug
from modules.Tools.tools import *
def init_profile(mail, mobile=False):
if not mobile:
chrome_profile_dir = "/app/MsRewards-Reborn/user_data/profile/" + mail
else:
chrome_profile_dir = "/app/MsRewards-Reborn/user_data/profile/mobile-" + mail
os.makedirs(chrome_profile_dir, exist_ok=True)
preferences_file = os.path.join(chrome_profile_dir, "Default", "Preferences")
if not os.path.exists(preferences_file):
os.makedirs(os.path.join(chrome_profile_dir, "Default"), exist_ok=True)
with open(preferences_file, "w") as f:
json.dump(
{
"intl": {
"accept_languages": "fr-FR,en-US,en",
"selected_languages": "fr-FR,en-US,en"
}
}, f
)
else:
with open(preferences_file, "r") as f:
settings = json.load(f)
if "intl" not in settings:
settings["intl"] = {}
settings["intl"]["accept_languages"] = "fr-FR,en-US,en"
settings["intl"]["selected_languages"] = "fr-FR,en-US,en"
with open(preferences_file, "w") as f:
json.dump(settings, f)
return chrome_profile_dir
# Deal with RGPD popup as well as some random popup like 'are you satisfied' one
def rgpd_popup(config) -> None:
for i in ["bnp_btn_accept", "bnp_hfly_cta2", "bnp_hfly_close"]:
try:
config.WebDriver.driver.find_element(By.ID, i).click()
except Exception as err:
debug(err)
"""
send_keys_wait([selenium element:element, str:keys]) send the different keys to the field element, with a random
time between each press to simulate human action.
keys can be an string, but also selenium keys
"""
def send_keys_wait(element, keys: str) -> None:
for i in keys:
element.send_keys(i)
sleep(uniform(0.1, 0.3))
def send_wait_and_confirm(element, keys: str) -> None:
send_keys_wait(element, keys)
element.send_keys(Keys.ENTER)
# Wait for the presence of the element identifier or [timeout]s
def wait_until_visible(search_by: str, identifier: str, timeout: int = 20, browser=None, raise_error=True) -> bool:
try:
WebDriverWait(browser, timeout).until(
expected_conditions.visibility_of_element_located((search_by, identifier)), "element not found")
return True
except TimeoutException as e:
f = error if raise_error else debug
f(f"element {identifier} not found after {timeout}s")
return False