-
Notifications
You must be signed in to change notification settings - Fork 0
/
ytm
executable file
·70 lines (69 loc) · 2.1 KB
/
ytm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/bin/bash
# search videos and playlists on youtube and play them in mpv, without an API
# usage:
# ytm asks for input in stdin, prompts using fzf
# ytm search query takes input from the passed arg, prompts using fzf
# ytm -r takes input and prompts using rofi
flags="--no-video"
promptcmd="fzf --with-nth=2..-1"
if [ -z "$*" ]; then
echo -n "Search: "
read -r query
else
case "$1" in
-r) query=$(rofi -dmenu -p "Search: ")
promptcmd="rofi -dmenu -no-custom -p Video:";;
*) query="$*";;
esac
fi
if [ -z "$query" ]; then exit; fi
# sanitise the query
query=$(sed \
-e 's|+|%2B|g'\
-e 's|#|%23|g'\
-e 's|&|%26|g'\
-e 's| |+|g'\
<<< "$query")
# fetch the results with the $query
response=$(curl -s "https://www.youtube.com/results?search_query=$query")
vgrep='"videoRenderer":{"videoId":"\K.{11}".+?"text":".+?[^\\](?=")'
pgrep='"playlistRenderer":{"playlistId":"\K.{34}?","title":{"simpleText":".+?[^\"](?=")'
# grep the video id and title
# replace " with “ so that entire title is displayed even if it has "
videoids=$(
echo "$response" | \
grep -oP "$vgrep" | \
sed 's|\\\"|“|g' | \
awk -F\" '{ print $1 "\t\t\t\t" $NF}'
)
# grep the playlist id and title
# replace " with “ so that entire title is displayed even if it has "
playlistids=$(
echo "$response" | \
grep -oP "$pgrep" | \
sed 's|\\\"|“|g' | \
awk -F\" '{ print $1 "\t(playlist) " $NF }'
)
# if there are playlists, append them to list
[ -n "$playlistids" ] && ids="$playlistids\n"
# if there are videos, append them to list
[ -n "$videoids" ] && ids="$ids$videoids"
# url prefix for videos and playlists
videolink="https://youtube.com/"
playlink="https://youtube.com/playlist?list="
# prompt the results to user infinitely until they exit (escape)
while true; do
id=$(
echo -e "$ids" | \
$promptcmd | \
cut -d' ' -f1
)
case $id in
# 11 digit id = video
???????????) clear; videolink="https://yewtu.be/"; mpv "$videolink$id" "$flags";;
# 34 digit id = playlist
??????????????????????????????????) clear; playlink="https://yewtu.be/"; mpv "$playlink$id" "$flags";;
"") exit ;;
*) echo "invalid id - $id" ;;
esac
done