#!/usr/bin/python3
import hashlib
import urllib.request
from urllib.error import HTTPError, URLError
from urllib.parse import urlparse
from os.path import splitext
import os
import re

# ⠀⢸⠂⠀⠀⠀⠘⣧⠀⠀⣟⠛⠲⢤⡀⠀⠀⣰⠏⠀⠀⠀⠀⠀⢹⡀
# ⠀⡿⠀⠀⠀⠀⠀⠈⢷⡀⢻⡀⠀⠀⠙⢦⣰⠏⠀⠀⠀⠀⠀⠀⢸⠀
# ⠀⡇⠀⠀⠀⠀⠀⠀⢀⣻⠞⠛⠀⠀⠀⠀⠻⠀⠀⠀⠀⠀⠀⠀⢸⠀
# ⠀⡇⠀⠀⠀⠀⠀⠀⠛⠓⠒⠓⠓⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⠀
# ⠀⡇⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣸⠀
# ⠀⢿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣀⣀⣀⠀⠀⢀⡟⠀
# ⠀⠘⣇⠀⠘⣿⠋⢹⠛⣿⡇⠀⠀⠀⠀⣿⣿⡇⠀⢳⠉⠀⣠⡾⠁⠀
# ⣦⣤⣽⣆⢀⡇⠀⢸⡇⣾⡇⠀⠀⠀⠀⣿⣿⡷⠀⢸⡇⠐⠛⠛⣿⠀
# ⠹⣦⠀⠀⠸⡇⠀⠸⣿⡿⠁⢀⡀⠀⠀⠿⠿⠃⠀⢸⠇⠀⢀⡾⠁⠀
# ⠀⠈⡿⢠⢶⣡⡄⠀⠀⠀⠀⠉⠁⠀⠀⠀⠀⠀⣴⣧⠆⠀⢻⡄⠀⠀
# ⠀⢸⠃⠀⠘⠉⠀⠀⠀⠠⣄⡴⠲⠶⠴⠃⠀⠀⠀⠉⡀⠀⠀⢻⡄⠀
# ⠀⠘⠒⠒⠻⢦⣄⡀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣀⣤⠞⠛⠒⠛⠋⠁⠀
# ⠀⠀⠀⠀⠀⠀⠸⣟⠓⠒⠂⠀⠀⠀⠀⠀⠈⢷⡀⠀⠀⠀⠀⠀⠀⠀
# ⠀⠀⠀⠀⠀⠀⠀⠙⣦⠀⠀⠀⠀⠀⠀⠀⠀⠈⢷⠀⠀⠀⠀⠀⠀⠀
# ⠀⠀⠀⠀⠀⠀⠀⣼⣃⡀⠀⠀⠀⠀⠀⠀⠀⠀⠘⣆⠀⠀⠀⠀⠀⠀
# ⠀⠀⠀⠀⠀⠀⠀⠉⣹⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⢻⠀⠀⠀⠀⠀⠀
# ⠀⠀⠀⠀⠀⠀⠀⠀⡿⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⡆⠀⠀⠀⠀⠀
#
# You want to download your discord favourited gifs don't you

def download_file(url):
    ext = splitext(urlparse(url).path)[1]
    filename = hashlib.sha256(url.encode()).hexdigest() + ext

    if os.path.exists(f"mp4/{filename}"):
        print(f"Skipping {filename} as file exists")
    else:
        with urllib.request.urlopen(url) as file:
            if "tenor" in url and "media.tenor" not in url:
                true_url = re.search(r"property=\"og:video\" content=\"(.*?\.mp4)\"", file.read().decode('utf-8')).group(1)
                file = urllib.request.urlopen(true_url)
                ext = splitext(urlparse(true_url).path)[1]
                filename = hashlib.sha256(true_url.encode()).hexdigest() + ext

            if not os.path.exists(f"mp4/{filename}"):
                with open(f"mp4/{filename}", mode="wb") as local_file:
                    local_file.write(file.read())
                    print(f"Downloaded {filename}")

# you can get base64-in by using the network panel and copying the base64
# returned by the request after you click favourite on a gif
# generate base64-clean with:
# base64 -d < base64-in | iconv -c -f utf-8 -t ascii > base64-clean
# you can then also save them as gifs with:
# for i in mp4/*; do namenopath=${i##*/}; ffmpeg -n -i "$i" "gif/${namenopath%.*}.gif"; done
with open("base64-clean") as file:
    file_contents = file.read().rstrip()
    file_contents = re.sub(r"(https\/|\/\/)", r"\nhttps://", file_contents)
    pattern = r"((https:)?\/\/.*?(view\/([a-zA-Z]+|-|\d)+|\.(mp4|gif)(\?ex=.*?&is=.*?&hm=.*?&)?))"
    matches = re.findall(pattern, file_contents, re.MULTILINE)

    for match in matches:
        print(match[0])
        try:
            download_file(match[0])
        except HTTPError as e:
            print(e)
        except URLError as e:
            print(e)

