from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import os
import time
import json
from pymongo import MongoClient

def scrapeExploit(term):
    ch = os.getcwd() + '/tools/chromedriver'
    options = Options()
    curr_dir = os.getcwd()
    prefs = {
        "profile.managed_default_content_settings.images": 2,
        "download.default_directory": curr_dir,
        "download.prompt_for_download": False,
        "download.directory_upgrade": True,
        "safebrowsing.enabled": True,
        'profile.default_content_setting_values.automatic_downloads': 1,
    }
    options.add_experimental_option("prefs", prefs)
    options.set_headless(headless=True)
    options.add_argument("--disable-gpu")
    options.add_argument("--disable-dev-shm-usage")
    options.add_argument("--no-sandbox")
    options.add_argument("log-level=3")
    driver = webdriver.Chrome(options=options, executable_path=ch)
    wait = WebDriverWait(driver, 10)
    driver.implicitly_wait(10)
    driver.get('https://www.exploit-db.com/')
    timestamp = int(time.time())
    search = driver.find_element_by_css_selector("input.form-control")
    search.send_keys(term)
    print("Searched term " + term)
    time.sleep(2)

    table = driver.find_element_by_id("exploits-table")
    results = []
    for tr in table.find_elements_by_tag_name("tr")[1:]:
        temp = {}
        tds = tr.find_elements_by_tag_name("td")
        f = tds[1].find_element_by_tag_name("a")
        fname = f.get_attribute("href").split("/")
        if fname[-1] == "":
            fname = fname[-2]
        else:
            fname = fname[-1]
        temp["timestamp"] = timestamp
        temp["fileName"] = fname
        temp["title"] = tds[4].text
        temp["link"] = tds[4].find_element_by_tag_name("a").get_attribute("href")
        temp["scriptLink"] = f.get_attribute("href")
        temp["searchedWord"] = term
        temp["date"] = tds[0].text
        temp["type"] = tds[5].text
        temp["platform"] = tds[6].text
        temp["author"] = tds[7].text
        results.append(temp)
    driver.quit()
    return results
