summaryrefslogtreecommitdiff
path: root/url_handler.sh
blob: 5ae6c59d3c32b6908e96d17e1709f739c3b2ad8b (plain) (blame)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/bin/sh
# Everything I would ever need to do with a URL.

DOWNLOAD_DIR=$HOME/downloads

# Prompt for a URL or search term
get_url() {
	dmenu -p "URL or search"
}

# Action for YouTube URLs
get_action() {
	action=$(dmenu -p "YouTube action" << EOF
1. watch 
2. video download
3. audio download
EOF
	)
	echo "$action" | cut -d'.' -f1
}


# Get title, description, and duration of YouTube URL
toast_info() {
	info=$(youtube-dl --get-title --get-description --get-duration "$1")
	title=$(echo "$info" | head -n 1)
	description=$(echo "$info" | sed '1d;$d')
	duration=$(echo "$info" | tail -n 1)
	notify-send "($duration) $title" "$description"
}


## Download video
video_download() {
	mkdir -p "$DOWNLOAD_DIR"
	youtube-dl \
		-q \
		--add-metadata \
		-o "$DOWNLOAD_DIR/%(title)s_%(id)s.%(ext)s" \
		"$1" && notify-send "Video download done." &
	notify-send "Downloading video:"
}


## Download audio
audio_download() {
	mkdir -p "$DOWNLOAD_DIR"
	youtube-dl \
		-q \
		--add-metadata \
		-o "$DOWNLOAD_DIR/%(title)s_%(id)s.%(ext)s" \
		-x \
		--audio-format flac \
		--audio-quality 0 \
		"$1" && notify-send "Audio download done." &
	notify-send "Downloading audio:"
}


## Play video
play() {
	URL="${1#http?://}"
	mpv --no-terminal --geometry=25%-10-40 --title="Streaming from YouTube" "ytdl://$URL" &
	notify-send "Playing:" 
}

# Handle YouTube URLs
handle_youtube() {
	URL=$1
	toast_info "$URL" &

	case "$(get_action)" in
		1)
			play "$URL"
			;;
		2)
			video_download "$URL"
			;;
		3)
			audio_download "$URL"
	esac
}

# Main
URL=$1
[ -n "$URL" ] || URL=$(get_url)
[ -n "$URL" ] || exit
echo "$URL"

case $URL in 
	*youtube.com*) handle_youtube "$URL" ;;
	*youtu.be*) handle_youtube "$URL" ;;
	*ytsearch:*) handle_youtube "$URL" ;;
	*mailto*) mutt "$URL" ;;
	*http?*) $BROWSER "$URL" ;;
	*)
		$BROWSER --search "$URL"
esac