aboutsummaryrefslogtreecommitdiff
path: root/bin/yt
blob: 1ba331abc776e9eef529bf2e376871ac14d6dab8 (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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#!/bin/sh
set -eu

usage() {
	cat <<-'EOF'
		Usage:
		  yt [-f] [-n PLAYLIST_COUNT] [URL...|FILE...|-]
		  yt -h
	EOF
}

help() {
	cat <<-'EOF'


		Options:
		  -n PLAYLIST_COUNT    the number of videos to grab from a
		                       playlist (default: 15)
		  -f                   force to download a video already in the
		                       archive
		  -h, --help           show this message

		  URL                  an 'https://...' address
		  FILE                 a file with 'https://...' addresses, one
		                       per line


		Download videos and store them locally.


		Examples:

		  Download the video from the given URL:

		    $ yt https://www.youtube.com/watch?v=EihZv2XgJdU


		  Force re-download the latest 5 videos already downloaded:

		    $ yt -nf5 https://www.youtube.com/watch?list=TLPQMTIwODIwMjLnL2XjyRRgSw
	EOF
}


for flag in "$@"; do
	case "$flag" in
		(--)
			break
			;;
		(--help)
			usage
			help
			exit
			;;
		(*)
			;;
	esac
done

PLAYLIST_COUNT=15
while getopts 'fn:h' flag; do
	case "$flag" in
		(f)
			FORCE=1
			;;
		(n)
			PLAYLIST_COUNT="$OPTARG"
			;;
		(h)
			usage
			help
			exit
			;;
		(*)
			usage >&2
			exit 2
			;;
	esac
done
shift $((OPTIND - 1))
set -x

if [ -z "${1:-}" ]; then
	echo 'Missing URL|FILE argument' >&2
	usage >&2
	exit 2
fi


if [ ! -e "$1" ]; then
	F="$(mkstemp)"
	trap 'rm -f "$F"' EXIT
	printf '%s\n' "$1" > "$F"
else
	F="$1"
fi


YT_TEMPLATE="$HOME/Downloads/yt-dl/%(uploader)s/%(upload_date)s %(title)s.%(ext)s"

EXTRA_OPTIONS=''
if [ -z "${FORCE:-}" ]; then
	EXTRA_OPTIONS="--download-archive $HOME/Documents/yt-dl-seen.txt"
fi

# The value of $EXTRA_OPTIONS doesn't depend on user input, and can't contain
# spaces, unless $HOME contains spaces:
# shellcheck disable=2086
yt-dlp \
	--batch-file "$F"                \
	--prefer-free-formats            \
	--playlist-end "$PLAYLIST_COUNT" \
	--write-description              \
	--output "$YT_TEMPLATE"          \
	$EXTRA_OPTIONS