reddit | | reddit post | Search

The code imports necessary libraries and defines functions enterReddit and loginReddit to interact with the Reddit website using Selenium WebDriver. However, the code has several issues, including recursive function calls, unhandled errors, and incomplete implementation, which need to be addressed.

Run example

npm run import -- "reddit login"

reddit login


const getClient = importer.import("selenium client")
const { Builder, Browser, By, Key, until } = require('selenium-webdriver')

//const PROFILE_PATH = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
//const PASSWORDS_FILE = path.join(PROFILE_PATH, '.credentials', 'brian-reddit.json');

async function enterReddit(driver) {
  console.log('Reddit: Sign in required');

  //var credentials = require(PASSWORDS_FILE)

  //let body = await driver.findElement(By.css('body'))
  await driver.wait(until.elementLocated(By.css('#post-submit-form')), 30000);
  
  let loginStill, loginStill2, loginStill3
  try {
    loginStill = await driver.findElement(By.css('#captcha-internal'))
  } catch (e) {}
  try {
    loginStill2 = await driver.findElement(By.css('input[name*="session_password"]'))
  } catch (e) {}
  try {
    loginStill3 = await driver.findElement(By.xpath('//*[contains(text(),"Check your notifications")]'))
  } catch (e) {}

  if(loginStill3) {
    await new Promise(resolve => setTimeout(resolve, 20000))
    try {
      loginStill = false
      loginStill2 = false
      loginStill3 = await driver.findElement(By.xpath('//*[contains(text(),"Check your notifications")]'))
    } catch (e) {}
  }

  if(loginStill || loginStill2 || loginStill3) {
    throw new Error('captcha')
  }
}

async function loginReddit(driver) {
  if(!driver) {
    driver = await getClient();
  }

  try {
    let url = await driver.getCurrentUrl()
    let loggedIn = url.indexOf('reddit') > -1 && url.indexOf('login') == -1

    debugger
    if(loggedIn) {
      //if(await driver.findElement(By.xpath('iframe.authentication-iframe'))) {
      //  await driver.frame((await driver.element('iframe.authentication-iframe')).value)
        await enterReddit(driver)
        //await frame()
      //}
    } else {
      await driver.get('https://www.reddit.com/submit')

      let loginLink, loginLink2
      try {
        loginLink = await driver.findElement(By.xpath('//auth-flow-link[text()[contains(.,"Forgot password?")]]'))
      } catch (e) {}
      try {
        loginLink2 = await driver.findElement(By.xpath('//auth-flow-link[text()[contains(.,"Sign up")]]'))
      } catch (e) {}

      if(loginLink || loginLink2) {
        await enterReddit(driver)
      }
    }
  } catch (e) {
    driver.quit() // avoid leaving sessions hanging around

    throw e
  }

  return driver
}

module.exports = loginReddit

What the code could have been:

const { Client, Builder, Browser, By, Key, until } = require('selenium-webdriver');

async function enterReddit(driver) {
  console.log('Reddit: Sign in required');

  const waitOptions = {
    timeout: 30000,
    timeoutMessage: 'Timed out waiting for element to be present',
  };

  const elementOptions = {
    timeout: 30000,
    timeoutMessage: 'Timed out waiting for element to be present',
  };

  let loginStill, loginStill2, loginStill3;

  try {
    loginStill = await driver.wait(
      until.elementLocated(By.css('#captcha-internal'), elementOptions),
      waitOptions.timeout
    );
  } catch (error) {
    loginStill = null;
  }

  try {
    loginStill2 = await driver.wait(
      until.elementLocated(By.css('input[name*="session_password"]'), elementOptions),
      waitOptions.timeout
    );
  } catch (error) {
    loginStill2 = null;
  }

  try {
    loginStill3 = await driver.wait(
      until.elementLocated(
        By.xpath('//*[contains(text(),"Check your notifications")]'),
        elementOptions
      ),
      waitOptions.timeout
    );
  } catch (error) {
    loginStill3 = null;
  }

  if (loginStill3) {
    await new Promise((resolve) => setTimeout(resolve, 20000));
    try {
      loginStill = null;
      loginStill2 = null;
      loginStill3 = await driver.wait(
        until.elementLocated(
          By.xpath('//*[contains(text(),"Check your notifications")]'),
          elementOptions
        ),
        waitOptions.timeout
      );
    } catch (error) {
      loginStill3 = null;
    }
  }

  if (loginStill || loginStill2 || loginStill3) {
    throw new Error('captcha');
  }
}

async function loginReddit(driver) {
  if (!driver) {
    driver = await new Builder()
     .forBrowser(Browser.FIREFOX)
     .build();
  }

  try {
    const url = await driver.getCurrentUrl();
    const loggedIn = url.indexOf('reddit') > -1 && url.indexOf('login') === -1;

    if (loggedIn) {
      await enterReddit(driver);
    } else {
      await driver.get('https://www.reddit.com/submit');

      let loginLink, loginLink2;

      try {
        loginLink = await driver.wait(
          until.elementLocated(
            By.xpath('//auth-flow-link[text()[contains(.,"Forgot password?")]]'),
            {
              timeout: 30000,
              timeoutMessage: 'Timed out waiting for element to be present',
            }
          ),
          30000
        );
      } catch (error) {
        loginLink = null;
      }

      try {
        loginLink2 = await driver.wait(
          until.elementLocated(
            By.xpath('//auth-flow-link[text()[contains(.,"Sign up")]]'),
            {
              timeout: 30000,
              timeoutMessage: 'Timed out waiting for element to be present',
            }
          ),
          30000
        );
      } catch (error) {
        loginLink2 = null;
      }

      if (loginLink || loginLink2) {
        await enterReddit(driver);
      }
    }
  } catch (error) {
    await driver.quit(); // Avoid leaving sessions hanging around

    throw error;
  }

  return driver;
}

module.exports = loginReddit;

Code Breakdown

Importing Dependencies

The code imports the following dependencies:

Function: enterReddit

This function takes a driver object as an argument and performs the following steps:

  1. Waits for an element with the ID post-submit-form to be located on the page.
  2. Tries to find three elements:
  3. If the notification element is found, adds a 20-second delay and tries to find the CAPTCHA element again.
  4. If any of the elements are found, throws an error with the message "captcha".

Function: loginReddit

This function takes a driver object as an argument (optional, defaults to creating a new driver instance using getClient()). The function performs the following steps:

  1. Checks if the current URL contains "reddit" and does not contain "login". If true, calls enterReddit().
  2. If not logged in, navigates to the Reddit submit page.
  3. Tries to find a login link with the text "Forgot password?".
  4. (The code is incomplete, with a catc statement instead of a catch block.)

Note that the code has several issues, including: