ytgrabber/ytgrabber

58 lines
2.3 KiB
Bash
Executable File

#!/usr/bin/env bash
# mode type
# - -
# 0 video
# 1 playlist
# 2 channel/user
[[ "${#@}" -lt 2 ]] &&
printf '%s\n%s\n\t%s %s\n' 'Not enough Arguments.' 'USAGE:' "${0}" '<0 1 2, video playlist channel respectively> <search1> [search2, ...]' 1>&2 && exit 1
co() { printf '%s' "$(tput setaf "${1}")";return 0; }
re() { printf '%s' "$(tput sgr0)";return 0; }
ue() { temp="$LC_COLLATE";LC_COLLATE='C';length="${#1}";for (( i = 0; i < length; i++ )) ;do c="${1:$i:1}"; case "${c}" in [a-zA-Z0-9.~_-]) printf '%s' "${c}" ;; *) printf '%%%02X' "'${c}";;esac;done;LC_COLLATE="${temp}";return 0; }
di() { printf "$(co 1)"'%s'"$(re)"'\n' "${*}" 1>&2;return 0; }
if grep -qE '^[0-2]$' <<<"${1}";then
mode="${1}"
else
mode=0
fi
prefixes=('video' 'playlist' 'channel/user')
for i in "${@}";do
grep -qE '^[0-2]$' <<<"${i}" && continue;
printf "$(co 2)"'"%s"'"$(re)"' ('"$(co 3)"'%s'"$(re)"') '"$(co 2)"'-->'"$(re)"' %s\n' "${i}" "${prefixes[${mode}]}" 'Downloading page:' 1>&2
raw="$(wget -q --show-progress -O- 'm.youtube.com/results?search_query='"$(ue "${i}")" || di 'Uh Oh! You don'\''t seem to have an internet connection.' && exit 1)"
printf "$(co 2)"'"%s"'"$(re)"' ('"$(co 3)"'%s'"$(re)"') '"$(co 2)"'-->'"$(re)"' %s\n' "${i}" "${prefixes[${mode}]}" 'Filtering[1]: Getting URLs' 1>&2
filter1="$(grep -oP '(?<="url":").*?(?=")' <<<"${raw}")"
printf "$(co 2)"'"%s"'"$(re)"' ('"$(co 3)"'%s'"$(re)"') '"$(co 2)"'-->'"$(re)"' %s\n' "${i}" "${prefixes[${mode}]}" 'Filtering[2]: Filtering by type' 1>&2
case "${mode}" in
0) filter2="$(grep -E 'watch[?&]v=[a-zA-Z0-9_=-]+$' <<<"${filter1}")";;
1) filter2="$(grep -E 'playlist[?&]list=PL[a-zA-Z0-9_=-]+' <<<"${filter1}")";;
2) filter2="$(grep -E '(user|channel)/[a-zA-Z0-9_=-]+' <<<"${filter1}")";;
esac
[[ "${#filter2}" -eq 0 ]] &&
di 'No results.' &&
continue;
printf ''"$(co 2)"'"%s"'"$(re)"' ('"$(co 3)"'%s'"$(re)"') '"$(co 2)"'-->'"$(re)"' %s\n' "${i}" "${prefixes[${mode}]}" 'Filtering[3]: Here comes the output.' 1>&2
awk '!x[$0]++'<<<"${filter2}" | while IFS= read -r url;do
if [[ "${mode}" == "2" ]];then
printf '%s%s%s\n' 'https://youtube.com' "${url}" "/videos"
else
printf '%s%s\n' 'https://youtube.com' "${url}"
fi
done
done