From c0ed667f184c962569eb0ee5dce95ee1222383d5 Mon Sep 17 00:00:00 2001 From: Thomas Wade Date: Tue, 21 Apr 2020 22:44:15 +0930 Subject: [PATCH] Move login logic out of __init__ --- FAAPI/FAAPI.py | 43 ++++++++++++++++++++++++++++--------------- 1 file changed, 28 insertions(+), 15 deletions(-) diff --git a/FAAPI/FAAPI.py b/FAAPI/FAAPI.py index 3a55066..4e1b4af 100644 --- a/FAAPI/FAAPI.py +++ b/FAAPI/FAAPI.py @@ -421,30 +421,43 @@ class FAAPI: A basic FurAffinity API instance. """ - def __init__(self, use_webdriver: bool = True): + def __init__(self): """ Initialises a new FAAPI instance. - Beware that a Chrome instance is launched to bypass Cloudflare and log in during initialisation. Change use_webdriver to False to disable this. """ + self._cookies = None + self._req = None + self._driver = None + self.logged_in = False + self.username = None - if not use_webdriver: - # Can't do any actual API things, stop here + def login(self, cookies=None) -> None: + """ + Logs this instance into FurAffinity. + Beware that a Chrome instance is launched to bypass Cloudflare and log in. Specify valid cookies to bypass this. + @param cookies: Cookies to use for this session. + """ + if self.logged_in: + # No need to do anything if we're already logged in return - # Try sign in to FA - self._driver = webdriver.Chrome() - self._driver.get(FA_BASE_URL + '/login') + if not cookies: + # Try sign in to FA + self._driver = webdriver.Chrome() + self._driver.get(FA_BASE_URL + '/login') - # Wait until our username is visible on the top banner - while not self._driver.find_elements_by_id('my-username'): - pass + # Wait until our username is visible on the top banner + while not self._driver.find_elements_by_id('my-username'): + pass - # Save the username of the account we've logged in as - self.username = self._driver.find_elements_by_css_selector('#my-username:not(.hideondesktop)')[0].text.strip() + # Save the username of the account we've logged in as + self.username = self._driver.find_elements_by_css_selector('#my-username:not(.hideondesktop)')[0].text.strip() - # Extract the cookies and stop the driver - self._cookies = self._driver.get_cookies() - self._driver.close() + # Extract the cookies and stop the driver + self._cookies = self._driver.get_cookies() + self._driver.close() + else: + self._cookies = cookies # Set up a Requests session with the cookies we just got self._req = requests.session()