Skip to content

Commit

Permalink
Get remaining searches from Browser
Browse files Browse the repository at this point in the history
  • Loading branch information
cal4 committed Jul 5, 2024
1 parent 98edecc commit 84fe7fc
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 74 deletions.
52 changes: 31 additions & 21 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@
DailySet,
Account,
)
from src.browser import RemainingSearches
from src.loggingColoredFormatter import ColoredFormatter
from src.utils import Utils, RemainingSearches
from src.utils import Utils


def main():
Expand All @@ -37,11 +38,11 @@ def main():
for currentAccount in loadedAccounts:
try:
earned_points = executeBot(currentAccount, args)
except Exception as e:
except Exception as e1:
logging.error("", exc_info=True)
Utils.sendNotification(
f"⚠️ Error executing {currentAccount.username}, please check the log",
f"{e}\n{e.__traceback__}",
f"{e1}\n{e1.__traceback__}",
)
continue
previous_points = previous_points_data.get(currentAccount.username, 0)
Expand Down Expand Up @@ -204,44 +205,53 @@ class AppriseSummary(Enum):
def executeBot(currentAccount: Account, args: argparse.Namespace):
logging.info(f"********************{currentAccount.username}********************")

accountPointsCounter: int
remainingSearches: RemainingSearches
startingPoints: int
# noinspection PyUnusedLocal
accountPointsCounter: int | None = None
# noinspection PyUnusedLocal
remainingSearches: RemainingSearches | None = None
# noinspection PyUnusedLocal
startingPoints: int | None = None

with (Browser(mobile=False, account=currentAccount, args=args) as desktopBrowser):
with Browser(mobile=False, account=currentAccount, args=args) as desktopBrowser:
utils = desktopBrowser.utils
Login(desktopBrowser, args).login()
startingPoints = accountPointsCounter = utils.getAccountPoints()
startingPoints = utils.getAccountPoints()
logging.info(
f"[POINTS] You have {utils.formatNumber(startingPoints)} points on your account"
)
# todo Send notification if these fail to Apprise versus just logging
ReadToEarn(desktopBrowser).completeReadToEarn(startingPoints)
DailySet(desktopBrowser).completeDailySet()
PunchCards(desktopBrowser).completePunchCards()
MorePromotions(desktopBrowser).completeMorePromotions()
# VersusGame(desktopBrowser).completeVersusGame()
remainingSearches = utils.getRemainingSearches()

if remainingSearches.desktop != 0:
with Searches(desktopBrowser, remainingSearches) as searches:
accountPointsCounter = searches.bingSearches(remainingSearches.desktop) # todo Seems redundant
with Searches(desktopBrowser) as searches:
searches.bingSearches()

# noinspection PyUnusedLocal
goalPoints = utils.getGoalPoints()
# noinspection PyUnusedLocal
goalTitle = utils.getGoalTitle()

# noinspection PyUnusedLocal
remainingSearches = desktopBrowser.getRemainingSearches(desktopAndMobile=True)
# noinspection PyUnusedLocal
accountPointsCounter = utils.getAccountPoints()

time.sleep(7.5) # give time for browser to close, probably can be more fine-tuned

if remainingSearches.mobile != 0:
with Browser(mobile=True, account=currentAccount, args=args) as mobileBrowser:
utils = mobileBrowser.utils
Login(mobileBrowser, args).login()
with Searches(mobileBrowser, remainingSearches) as searches:
accountPointsCounter = searches.bingSearches(remainingSearches.mobile) # todo Seems redundant
with Browser(mobile=True, account=currentAccount, args=args) as mobileBrowser:
utils = mobileBrowser.utils
Login(mobileBrowser, args).login()
with Searches(mobileBrowser) as searches:
searches.bingSearches()

goalPoints = utils.getGoalPoints()
goalTitle = utils.getGoalTitle()
goalPoints = utils.getGoalPoints()
goalTitle = utils.getGoalTitle()

remainingSearches = utils.getRemainingSearches()
remainingSearches = mobileBrowser.getRemainingSearches(desktopAndMobile=True)
accountPointsCounter = utils.getAccountPoints()

logging.info(
f"[POINTS] You have earned {utils.formatNumber(accountPointsCounter - startingPoints)} points this run !"
Expand Down
40 changes: 39 additions & 1 deletion src/browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import random
from pathlib import Path
from types import TracebackType
from typing import Any, Type
from typing import Any, Type, NamedTuple

import ipapi
import seleniumwire.undetected_chromedriver as webdriver
Expand All @@ -17,6 +17,14 @@
from src.utils import Utils


class RemainingSearches(NamedTuple):
desktop: int
mobile: int

def getTotal(self) -> int:
return self.desktop + self.mobile


class Browser:
"""WebDriver wrapper class."""

Expand Down Expand Up @@ -225,3 +233,33 @@ def getChromeVersion() -> str:
# driver.__exit__(None, None, None)

return version

def getRemainingSearches(
self, desktopAndMobile: bool = False
) -> RemainingSearches | int:
dashboard = self.utils.getDashboardData()
searchPoints = 1
counters = dashboard["userStatus"]["counters"]

progressDesktop = counters["pcSearch"][0]["pointProgress"]
targetDesktop = counters["pcSearch"][0]["pointProgressMax"]
if len(counters["pcSearch"]) >= 2:
progressDesktop = progressDesktop + counters["pcSearch"][1]["pointProgress"]
targetDesktop = targetDesktop + counters["pcSearch"][1]["pointProgressMax"]
if targetDesktop in [30, 90, 102]:
searchPoints = 3
elif targetDesktop == 50 or targetDesktop >= 170 or targetDesktop == 150:
searchPoints = 5
remainingDesktop = int((targetDesktop - progressDesktop) / searchPoints)
remainingMobile = 0
if dashboard["userStatus"]["levelInfo"]["activeLevel"] != "Level1":
progressMobile = counters["mobileSearch"][0]["pointProgress"]
targetMobile = counters["mobileSearch"][0]["pointProgressMax"]
remainingMobile = int((targetMobile - progressMobile) / searchPoints)
if desktopAndMobile:
return RemainingSearches(desktop=remainingDesktop, mobile=remainingMobile)
elif self.mobile:
return remainingMobile
elif not self.mobile:
return remainingDesktop
raise AssertionError
41 changes: 19 additions & 22 deletions src/searches.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from selenium.webdriver.support.wait import WebDriverWait

from src.browser import Browser
from src.utils import Utils, RemainingSearches
from src.utils import Utils

LOAD_DATE_KEY = "loadDate"

Expand All @@ -38,7 +38,7 @@ class Searches:
config.get("attempts", {}).get("strategy", AttemptsStrategy.constant.name)
]

def __init__(self, browser: Browser, searches: RemainingSearches):
def __init__(self, browser: Browser):
self.browser = browser
self.webdriver = browser.webdriver

Expand All @@ -53,7 +53,9 @@ def __init__(self, browser: Browser, searches: RemainingSearches):
if loadDate is None or loadDate < date.today():
self.googleTrendsShelf.clear()
self.googleTrendsShelf[LOAD_DATE_KEY] = date.today()
trends = self.getGoogleTrends(searches.getTotal())
trends = self.getGoogleTrends(
browser.getRemainingSearches(desktopAndMobile=True).getTotal()
)
random.shuffle(trends)
for trend in trends:
self.googleTrendsShelf[trend] = None
Expand Down Expand Up @@ -102,41 +104,35 @@ def getRelatedTerms(self, term: str) -> list[str]:
return [term]
return relatedTerms

def bingSearches(self, numberOfSearches: int, pointsCounter: int = 0) -> int:
def bingSearches(self) -> None:
# Function to perform Bing searches
logging.info(
f"[BING] Starting {self.browser.browserType.capitalize()} Edge Bing searches..."
)

self.browser.utils.goToSearch()

# todo Make sure rewards quiz is done

for searchCount in range(1, numberOfSearches + 1):
remainingSearches = self.browser.getRemainingSearches()
for searchCount in range(1, remainingSearches + 1):
# todo Disable cooldown for first 3 searches (Earning starts with your third search)
logging.info(f"[BING] {searchCount}/{numberOfSearches}")
googleTrends: list[str] = list(self.googleTrendsShelf.keys())
logging.debug(f"self.googleTrendsShelf.keys() = {googleTrends}")
googleTrend = list(self.googleTrendsShelf.keys())[1]
pointsCounter = self.bingSearch(googleTrend)
logging.debug(f"pointsCounter = {pointsCounter}")
logging.info(f"[BING] {searchCount}/{remainingSearches}")
self.bingSearch()
time.sleep(random.randint(10, 15))

logging.info(
f"[BING] Finished {self.browser.browserType.capitalize()} Edge Bing searches !"
)
return pointsCounter

def bingSearch(self, term: str) -> int:
def bingSearch(self) -> None:
# Function to perform a single Bing search
pointsBefore = self.browser.utils.getAccountPoints()

terms = self.getRelatedTerms(term)
rootTerm = list(self.googleTrendsShelf.keys())[1]
terms = self.getRelatedTerms(rootTerm)
logging.debug(f"terms={terms}")
termsCycle: cycle[str] = cycle(terms)
baseDelay = Searches.baseDelay
passedInTerm = term
logging.debug(f"passedInTerm={passedInTerm}")
logging.debug(f"rootTerm={rootTerm}")

for i in range(self.maxAttempts):
if i != 0:
Expand All @@ -156,7 +152,7 @@ def bingSearch(self, term: str) -> int:
searchbar = self.browser.utils.waitUntilClickable(
By.ID, "sb_form_q", timeToWait=20
)
for _ in range(100):
for _ in range(1000):
searchbar.click()
searchbar.clear()
term = next(termsCycle)
Expand All @@ -171,12 +167,13 @@ def bingSearch(self, term: str) -> int:
break
logging.debug("error send_keys")
else:
# todo Still happens occasionally, gotta be a fix
raise TimeoutException
searchbar.submit()

pointsAfter = self.browser.utils.getAccountPoints()
if pointsBefore < pointsAfter:
del self.googleTrendsShelf[passedInTerm]
del self.googleTrendsShelf[rootTerm]
return pointsAfter

# todo
Expand All @@ -186,7 +183,7 @@ def bingSearch(self, term: str) -> int:
logging.error("[BING] Reached max search attempt retries")

logging.debug("Moving passedInTerm to end of list")
del self.googleTrendsShelf[passedInTerm]
self.googleTrendsShelf[passedInTerm] = None
del self.googleTrendsShelf[rootTerm]
self.googleTrendsShelf[rootTerm] = None

return pointsBefore
30 changes: 0 additions & 30 deletions src/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,6 @@
from .constants import SEARCH_URL


class RemainingSearches(NamedTuple):
desktop: int
mobile: int

def getTotal(self) -> int:
return self.desktop + self.mobile


class Utils:
args: Namespace

Expand Down Expand Up @@ -225,28 +217,6 @@ def visitNewTab(self, timeToWait: float = 0) -> None:
self.switchToNewTab(timeToWait)
self.closeCurrentTab()

def getRemainingSearches(self) -> RemainingSearches:
dashboard = self.getDashboardData()
searchPoints = 1
counters = dashboard["userStatus"]["counters"]

progressDesktop = counters["pcSearch"][0]["pointProgress"]
targetDesktop = counters["pcSearch"][0]["pointProgressMax"]
if len(counters["pcSearch"]) >= 2:
progressDesktop = progressDesktop + counters["pcSearch"][1]["pointProgress"]
targetDesktop = targetDesktop + counters["pcSearch"][1]["pointProgressMax"]
if targetDesktop in [30, 90, 102]:
searchPoints = 3
elif targetDesktop == 50 or targetDesktop >= 170 or targetDesktop == 150:
searchPoints = 5
remainingDesktop = int((targetDesktop - progressDesktop) / searchPoints)
remainingMobile = 0
if dashboard["userStatus"]["levelInfo"]["activeLevel"] != "Level1":
progressMobile = counters["mobileSearch"][0]["pointProgress"]
targetMobile = counters["mobileSearch"][0]["pointProgressMax"]
remainingMobile = int((targetMobile - progressMobile) / searchPoints)
return RemainingSearches(desktop=remainingDesktop, mobile=remainingMobile)

@staticmethod
def formatNumber(number, num_decimals=2) -> str:
return pylocale.format_string(
Expand Down

0 comments on commit 84fe7fc

Please sign in to comment.