#!/usr/bin/python3
# -*- coding: UTF-8 -*-
#author:Wos
#it support proxy(when sometime the server is slow,you can change it)
#auto convert youtube playlist link to invidious instance playlist link,then open with surf suckless browser
#direct parser youtube and invidious play link to play with mpv
import sys
import requests
import pyperclip
import os
import base64
import json
import urllib
import time

fname = ""
vname= ""
tag = [22,18]
pxy = ""
proxies={}
pxy = ""
#modify the server list that fastest for you
premain = "https://invidious.io.lol"                


def GetDesktopPath():
    return os.path.join(os.path.expanduser("~"), 'Desktop')


#download subtitle
def downtxt(vid):
    try:
        global fname,vname
        ensub = ""
        ensub2 = ""
        st = ""
        st2 = ""
        fname = "/tmp/"+str(vid)+".srt"
        url= "https://downsub.com/?url=https://www.youtube.com/watch?v="+str(vid)
        res = requests.get(url)
        txt1 = (res.text.split("context=\'")[1].split("'")[0])
        txt2 = (str(base64.b64decode(txt1)).split("\"id\":\"")[1].split("\"")[0])
        url2 = "https://get-info.downsub.com/"+str(txt2)
        res2 = requests.get(url2,timeout=(3,7)).json()
        vname = res2['title']
        for j in res2['subtitles']:
            if j['name'] == "English (auto-generated)":
                ensub = j['url']
                st = "English (auto-generated)"
            elif j['name'] == "English":
                if ensub == "":
                    ensub = j['url']
                    st = "English"
            elif j['name'] == "Chinese (Traditional)":
                ensub2 = j['url']
                st2 = "Chinese (Traditional)"
            elif j['name'] == "Chinese Simplified":
                if ensub2 == "":
                    ensub2 = j['url']
                    st2 = "Chinese Simplified"





        if ensub == "":
            for j in res2['subtitlesAutoTrans']:
                if j['name'] == "English":
                    ensub = j['url']
                    st = "[English] "
        if ensub != "" and ensub2 != "":
            url3 = "https://subtitle.downsub.com/?title=["+str(st)+"-"+str(st2)+"] "+str(vname).strip()+" [DownSub.com]&url="+str(ensub)+"&urldual="+str(ensub2)
        else:
            url3 = "https://subtitle.downsub.com/?title=["+str(st)+"] "+str(vname).strip()+" [DownSub.com]&url="+str(ensub)
        res_ = requests.get(url3,timeout=(3,7),stream=True)
        with open(fname, 'wb') as f:
            for i in res_.iter_content(chunk_size=1024):
                f.write(i)
            f.close()
    except:
        pass

def play(vid):
    downtxt(vid)
    i = 0
    temp = ""
    while i < len(tag):
        try:
            url2 = premain+"/latest_version?id="+vid+"&itag="+str(tag[i])
            hdr = {
                'user-agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:68.0) Gecko/20100101 Goanna/4.8 Firefox/68.0 PaleMoon/29.4.4'
            }
            res = requests.get(url2,proxies=proxies,headers=hdr,timeout=(3,7),allow_redirects=False)
            temp = res.headers['location']
            break
        except:
            i += 1
            continue
    if temp:
        link = premain+"/videoplayback?"+temp.split("videoplayback?")[1]+"&title="+str(vid)
        pyperclip.copy(link)
        if os.path.exists(fname):
            cmdline = ("mpv --really-quiet %s --sub-file=\"%s\" \"%s\""%(pxy,fname,link))
        else:
            cmdline = ("mpv --really-quiet %s \"%s\""%(pxy,link))
        print(cmdline)
        while True:
            status = os.system(cmdline)
            if str(status) == "0":
                pyperclip.copy("")
                return
            else:
                continue



if __name__ == '__main__':
    while True:
        try:
            os.system("clear")
            sid = input("Quality(1:720p,2:320p):")
            if int(sid) == 1:
                tag = [22,18]
            elif int(sid) == 2:
                tag = [18,22]
            sid = input("Enable Proxy ?(Y/N):")
            if str(sid).strip() == "Y" or str(sid).strip() == "y":
                proxies = {'http':'socks5://127.0.0.1:7891','https':'socks5://127.0.0.1:7891'}
                pxy = " --http-proxy=http://127.0.0.1:7890"
                break
            else:
                proxies = {}
                pxy = ""
                break
        except:
            continue

    while True:
        try:
            os.system("clear")
            url = pyperclip.paste()
            print("invidious and youtube parser is running...")
            if premain != "":
                print("current instance:"+premain)
            if "watch?v=" in str(url):
                vid = str(url).split("watch?v=")[1].split("&")[0]
                play(vid)
                continue
            elif "embed/" in str(url):
                vid = str(url).split("embed/")[1].split("?")[0]
                play(vid)
                continue
            elif str(url).startswith("https://youtu.be/") or str(url).startswith("https://yewtu.be"):
                vid = str(url).split("/")[-1]
                play(vid)
                continue
            elif "/vi/" in str(url):
                vid = str(url).split("/")[-2]
                play(vid)
                continue
            elif str(url).startswith("https://www.youtube.com/channel/"):
                if not str(url).endswith("playlists"):
                    url_ = str(url).replace("https://www.youtube.com",str(premain)).rstrip("/")+"/playlists/"
                    cmdline = ('sh -c \"surf -a a -d -s -T -g -n -x \\\"%s\\\" 2>/dev/null &\"'%(url_))
                    os.system(cmdline)
                    pyperclip.copy("")
                else:
                    url_ = str(url).replace("https://www.youtube.com",str(premain))
                    cmdline = ('sh -c \"surf -a a -d -s -T -g -n -x \\\"%s\\\" 2>/dev/null &\"'%(url_))
                    os.system(cmdline)
                    pyperclip.copy("")

                continue
            else:
                time.sleep(1)
                continue
        except:
           sys.exit()