import datetime
import re
import time

import requests
from selenium import webdriver

def get(app_id):
    options = webdriver.FirefoxOptions()
    options.add_argument("--headless")

    with webdriver.Firefox(options=options) as driver:
        driver.get(f"https://apps.evozi.com/apk-downloader/?id={app_id}")
        driver.find_element_by_class_name("btn").click()

        t = datetime.datetime.now()
        while True:
            try:
                dl_url = "https:" + re.search(r'//storage.+?\.apk', driver.page_source).group()
                break
            except AttributeError:
                pass
            if datetime.datetime.now()-t > datetime.timedelta(seconds=10):
                raise RuntimeError('Download failed')
            time.sleep(1)

    return requests.get(dl_url).content
