~smlavine/scripts

ref: bd8b609d96de019c9f48d78deea4ee4cf243021b scripts/src/watchyt -rwxr-xr-x 2.2 KiB
bd8b609dSebastian LaVine src/watchyt: Use echo instead of printf in usage 3 months ago
                                                                                
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
#!/bin/sh
# Copyright (c) 2020-2021 Sebastian LaVine <mail@smlavine.com>
# Licensed under the GNU GPLv3. See GPLv3.txt for details.
#
# File:        watchyt
# Description: Watch the given YouTube video in mpv, using yt-dlp.
# Options:     -c        Use the clipboard value as the video URL.
#              -d        Open the video description in less. (don't launch mpv)
# Arguments:   URL of the video to watch

usage()
{
	echo "USAGE: watchyt [-cd] [url]"
}

while getopts "cdh" o; do
	case "$o" in
		c) url="$(xclip -selection c -o)" ;;
		d) description="True" ;;
		*) usage; exit ;;
	esac
done

# I didn't know this existed until I read the getopts man page. It's useful!
shift $((OPTIND - 1))

# if there isn't already a url and there is no argument, get a url through a
# dmenu prompt.
if [ "$url" ]; then
	# if there is already a url, then it came from the xclip clipboard.
	# Firefox removes text clipped from it if it closes, so re-write url to
	# the xclip clipboard to counteract this.
	printf "%s" "$url" | xclip -selection c -i
else
	if [ "$#" -eq 0 ]; then
		URL_PREFIX="ytdl://ytsearch:"
		url="$(dmenu -p 'Search for:' </dev/null)"
		[ "$url" ] && url="$URL_PREFIX$url"
	else
		url="$*"
	fi
fi

# Remove any chars that are not letters, numbers, or punctuation from the url.
url="$(printf "%s" "$url" | tr -cd '[:alnum:][:punct:]')"

if [ -z "$url" ]; then
	usage
	exit

elif [ "$description" ]; then
	descfile="$(mktemp watchyt.XXXXXXXX -p /tmp)"

	# The order of these fields is important for the printf statement to
	# work correctly.
	jqs='.id, .title, .uploader, (.upload_date | strptime("%Y%m%d") | mktime | strftime("%A, %b. %d, %Y")), .view_count, .description'
	format="https://youtu.be/%s\n%s\nUploaded by %s on %s\n%'d views\n---\n%b\n"
	yt-dlp -j "$url" | jq "$jqs" | xargs printf "$format" > "$descfile"

	st -e lessdown "$descfile"
	rm "$descfile" # Once less is closed, then delete file.

else
	errfile="$(mktemp)"
	mpv --script-opts=ytdl_hook-ytdl_path=yt-dlp \
		--ytdl-format="bestvideo[height<=?1080]+bestaudio/best" \
		--log-file="$errfile" "$url"
	if [ -s "$errfile" ]; then
		grep -E 'ERROR' "$errfile" |
			sed 's/^.*\] //' |
			xargs -Ix dunstify -u 2 -t 5000 x
	fi
	rm "$errfile"
fi