#!/bin/ksh
#you need xdotool, xclip, mpv, yt-dlp, 
#links2 (compiled with GUI)
#
#search for videos, stream, download,
#rip audio
#
#when running the script inside links2,
#links must be focused! you can run it
#through dmenu, or bind it to a key combo

#choose your favorite from invidious.io
invidious_instance="https://iv.melmac.space"
browser="links -g"

options() {
cat <<eof | dmenu
search
play
dl
rip
eof
}

make_query() {
 query=$(cat /dev/null | dmenu)
}

search() {
 make_query
 [[ $query = "" ]] && $browser $invidious_instance ||\
  $browser "$invidious_instance/search?q=$query" 
}
 
is_focused() {
 xdotool getwindowfocus getwindowname
}

get_url() {
  xdotool key Ctrl+g Ctrl+u Escape
}

play() {
 [[ $(is_focused) = *Links* ]] && \
 get_url
 mpv "$(xclip -o)"
}

dl() {
 [[ $(is_focused) = *Links* ]] &&\
 get_url
 yt-dlp "$(xclip -o)"
}

rip() {
 [[ $(is_focused) = *Links* ]] &&\
 get_url
 yt-dlp -x "$(xclip -o)"
}

case $(options) in 
 search) search;;
 play) play;;
 dl) dl;;
 rip) rip;;
esac

