import requests
import urllib.request
import xml.etree.ElementTree as ET
import subprocess

filenametemplate = "./video/S{}E{} {}.mp4"

srcfile = open("./list.txt", 'r')
logfile = open("./video/downloadlog.txt", "a")

logfile.write("\nNew Session\n")

while True:
    contentid = srcfile.readline().replace("\n", "")[:-1]
    if not contentid:
        break

    contentid_lastslash = contentid.rfind('/') + 1
    contentid = int(contentid[contentid_lastslash:])

    requesturl = "https://www.myspass.de/includes/apps/video/getvideometadataxml.php?id=" + str(contentid)

    headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 5.1.1; SM-G928X Build/LMY47X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.83 Mobile Safari/537.36'}
    response = requests.get(requesturl, headers=headers)   

    root = ET.ElementTree(ET.fromstring(response.text)).getroot()

    title = root.find("title").text
    season = root.find("season").text
    episode = root.find("episode").text
    
    videourl = root.find("url_flv").text

    if videourl or response.status_code != 200:        
        videourl = videourl.split('/')
        
        videourl[12] = str(int(int(videourl[12]) / contentid))
        videourl[13] = str(int(int(videourl[13]) / contentid))
        videourl[14] = str(int(int(videourl[14]) / contentid))
        
        temp = videourl[15].split('_')
        videourl[15] = str(int(int(temp[0]) / contentid)) + "_" + temp[1]
        
        videourl = '/'.join(videourl)
        
        filename = filenametemplate.format(season, episode, title)
        
        videoprobe = requests.head(videourl)

        if videoprobe.status_code == 200:
            print("# Downloading following entry:")
            print(filename)
            #print(videourl)
            logfile.write("Downloading '" + str(contentid) + "'\n")
            subprocess.run(["youtube-dl", "-o", filename, "-f bestvideo+bestaudio/best", videourl])
        else:
            logfile.write("Videoprobe: Skipping '" + str(contentid) + "'' Response Code: '" + str(videoprobe.status_code) + "'\n")

    else:
        logfile.write("Empty Response: Skipping '" + str(contentid) + "'' Response Code: '" + str(response.status_code) + "'\n")
    
    logfile.flush()

srcfile.close()
logfile.close()

