import requests
requests.packages.urllib3.disable_warnings()

if not len(analysis.sel):
    raise ValueError("Nothing selected")

url = ""

# is it a know string ?
if analysis.sel.start in analysis.strings:
    string = analysis.strings[analysis.sel.start]
    if string.text.lower().startswith("http"):
        url = string.text

# if not look at selected bytes
if not url:
    offset = analysis.map.to_phys(analysis.sel.start)
    if offset is not None:
        data = analysis.file.read(offset, len(analysis.sel))
        if len(data) > 1 and data[1] == 0:
            url = data.decode("utf-16-le", errors="ignore")
        else:
            url = data.decode("ascii", errors="ignore")

if not url.startswith("http"):
    raise ValueError("No string starting with http found in selection")

user_agents = [
        "Mozilla/5.0 (Windows NT; Windows NT 10.0; en-US) WindowsPowerShell/5.1.22621.963",
        "Mozilla/5.0 (Windows NT 10.0; Microsoft Windows 10.0.15063; en-US) PowerShell/6.0.0",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36",
        ]

for user_agent in user_agents:
    headers = {'User-Agent': user_agent}
    print("Downloading content at '{}' as '{:20s}' with a timeout of 30s ...".format(url, user_agent))
    try:
        r = requests.get(url, headers=headers, verify=False, timeout=30)
        r.raise_for_status()
        if not r.content:
            raise ValueError("Empty response [{}]".format(r.status_code))
        gui.open_after(r.content, url)
        gui.print("[clean]Download successful![/clean]")
        break
    except Exception as e:
        gui.print("[error]Could not download: {}[/error]".format(str(e).replace("[", "\\[")), format=True)
    print()
else:
    print("Could not download content :(")

