Skip to content

Commit 88ce179

Browse files
committed
improved error handling
1 parent 753ec0c commit 88ce179

File tree

2 files changed

+42
-14
lines changed

2 files changed

+42
-14
lines changed

README.md

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
# youtube-from-terminal
1+
# YouTube from Terminal
22

3-
A simple script to search youtube from terminal and watch video in mpv
3+
This script allows you to search for YouTube videos from the terminal and watch them using `mpv`.
44

55
# Usage
66

77
```sh
8-
./yt.sh <search-query>
8+
./yt.sh -q <search-query>
99
```
1010
# Setup
1111

@@ -18,5 +18,5 @@ chmod +x yt.sh
1818

1919
- curl
2020
- awk
21-
- fzf or dmenu (change variable from ``` menu=fzf ``` to ``` menu=dmenu ``` to use dmenu)
21+
- fzf
2222
- mpv

yt.sh

100644100755
+38-10
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,48 @@
11
#!/bin/bash
22

3-
[ $# -eq 0 ] && echo "Syntax : $0 <search-query>" && exit 1
3+
command_exists() {
4+
command -v "$1" >/dev/null 2>&1
5+
}
6+
7+
handle_error() {
8+
echo "Error: $1"
9+
exit 1
10+
}
11+
12+
if ! command_exists mpv || ! command_exists fzf || ! command_exists awk || ! command_exists curl; then
13+
handle_error "Please make sure 'mpv', 'fzf', 'awk' and 'curl' are installed."
14+
fi
15+
16+
if [ $# -eq 0 ] || [[ "$1" != "-q" ]]; then
17+
echo "Syntax: $0 -q <search-query>"
18+
exit 1
19+
fi
20+
21+
query_encoded=$(printf '%q ' "${@:2}")
422

5-
query=$(echo $@ | awk '{gsub(" ","+")}1')
623
menu=fzf
24+
725
yt="https://www.youtube.com/watch?v="
8-
id=$(curl https://www.youtube.com/results \
9-
-s -G --data-urlencode search_query=$query \
10-
-G --data-urlencode sp= \
11-
-H 'Authority: www.youtube.com' \
12-
-H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.152 Safari/537.36' \
13-
-H 'Accept-Language: en-US,en;q=0.9' \
26+
27+
video_id=$(curl "https://www.youtube.com/results" \
28+
-s -G --data-urlencode "search_query=$query_encoded" \
29+
-G --data-urlencode "sp=" \
30+
-H "Authority: www.youtube.com" \
31+
-H "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.152 Safari/537.36" \
32+
-H "Accept-Language: en-US,en;q=0.9" \
1433
-L --compressed \
1534
| awk '{gsub("<","\n<")}1' \
1635
| awk '{gsub("videoId","\n videoId")}1' \
1736
| awk '{gsub("views","views\n")}1' \
1837
| awk -F '"' '/videoId/ { print $39 " " $3 }' \
19-
| awk '/views/' | $menu | awk -F ' ' '{ print $(NF-0) }')
20-
mpv ${yt}${id}
38+
| awk '/views/' | "$menu" | awk -F ' ' '{ print $(NF-0) }')
39+
40+
if [ -z "$video_id" ]; then
41+
handle_error "No video selected or found."
42+
fi
43+
44+
echo "Loading..."
45+
46+
if ! mpv "${yt}${video_id}"; then
47+
handle_error "Failed to play the video."
48+
fi

0 commit comments

Comments
 (0)