#!/bin/sh
#author:Wos
#a script to parser youtube or invidious link or video id and play with vtt subtitle
WORK_DIR=$(dirname $0)
HTMP=/tmp/y2mate.html
PXY=""
PPXY=""
clear
read -e -r -p "Whether to Enable Proxy?Y/N " input
if [[ "${input}" == "y" ]] || [[ "${input}" == "Y" ]]; then
    PXY="--http-proxy=http://127.0.0.1:7891"
    PPXY="--proxy http://127.0.0.1:7891"
fi

while :;
do
clear
echo -e "\033[96;40m"
base64 -d <<<"H4sIAAAAAAAAA6WSPRLEIAiF+5yCzs6aA+QAtnaOY88NOPsCSoxOJlvEgp8X3o74basgp0mMDbHG
XluUXk/dFJlp48NRJEgXIGICyBgBUWclFmZE5jAVLQqekoMqcEhX1byOwHNEJKIceiYS98PIi5uZ
a+yZ+ea+VsBeLL6hWGs3j+PmsmyysmTEJCtw1idJtln/dClLlnc64Mv56HaEittojz5aMdFec4vb
Eep76cMtSGVtR+v67iZq50A4kNZsv0TRXB2t67tbwUFHaG5DB8bghnbq+839ZuO/UmxfHb2hdf3Z
bWRtT82njiLmidb11f0Pyuv56P4Bx9rG2uADAAA="|gunzip
echo "youtube and invidious parser"
echo "copy youtube resource link or invidious resource link or video id,it will auto parser to play(default:720p)"
echo -e "\033[0m"
LINK=$(echo $(xclip -selection clipboard -o 2>/dev/null)|head -1|sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
if [[ "${LINK}" == *watch?v* ]] || [[ "${LINK}" == */shorts/* ]] || [[ "${LINK}" == */youtu.be/* ]] || [[ "${LINK}" == */embed/* ]] || [[ $(echo ${LINK}|wc -c) == 12 ]]; then
    xclip -selection clipboard /dev/null
    if [[ $(echo ${LINK}|wc -c) == 12 ]]; then
        VID=$(echo ${LINK})
    else
        VID=$(echo ${LINK}|awk -F\= '{print $2}'|awk -F\& '{print $1}')
    fi
    if [[ -z "${VID}" ]]; then
        if [[ -z "${VID}" ]]; then
            VID=$(echo ${LINK}|awk -Fshorts\/ '{print $2}')
	    if [[ -z "${VID}" ]]; then
   	        VID=$(echo ${LINK}|awk -Fyoutu.be\/ '{print $2}')
	    fi
	fi
    fi
    VID2="https://www.youtube.com/watch?v=${VID}"
    echo ${VID}
    #download vtt subtitle
    rm /tmp/y2mate.en.vtt 2>/dev/null
    rm /tmp/y2mate.txt 2>/dev/null
    echo "subtitle parsering..."
    while :;
    do
    yt-dlp --extractor-args "youtube:player_client=tv_embedded,mediaconnect" -q ${PPXY} --write-auto-sub --skip-download  --sub-format=vtt --sub-lang=en "${VID2}" -o /tmp/y2mate 2>/dev/null
    grep -q  "00:00" /tmp/y2mate.en.vtt 2>/dev/null && break
    sleep 1
    done
    echo "subtitle Download complete!"
    echo "video and audio parsering..."
    while :;
    do
    yt-dlp --extractor-args "youtube:player_client=tv_embedded,mediaconnect" -q -f 'bestvideo[height<=720]+bestaudio' -g "${VID2}" ${PPXY} 2>/dev/null|sed '/^$/d' > /tmp/y2mate.txt
    if [[ $(cat /tmp/y2mate.txt|wc -l) == 2 ]]; then
        break
    fi
    sleep 1
    done
    echo "enjoy!"
    videourl=$(sed -n 1p /tmp/y2mate.txt|sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
    audiourl=$(sed -n 2p /tmp/y2mate.txt|sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')
    mpv --cache=yes --really-quiet ${PXY} "${videourl}" --audio-file="${audiourl}" --sub-file=/tmp/y2mate.en.vtt
    xclip -selection clipboard /dev/null
else
    sleep 1 
    continue
fi
done