Last active
February 1, 2016 16:51
-
-
Save xenithorb/37efc5430c5d41074f31 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
#set -x | |
# | |
# Usage: ./dl_yt_playlist.sh "https://<youtube_playlist>" [<folder>] | |
# By default downloads highest quality audio to current dir | |
# | |
# IMPORTANT: Must use quotes on the commandline, the URI contains &! | |
# | |
# IMPORTANT: Expects a dedicated directory for the playlist | |
# You can specify a nonexistant directory and it will create one | |
# However, if you specify an existing dir, it will rename the files | |
# within. | |
# | |
# Dependencies: the `youtube-dl` command in $PATH | |
# | |
TO_DIR="${2:-.}" | |
red="$(tput setaf 1)" | |
bold="$(tput bold)" | |
normal="$(tput sgr0)" | |
seconds=30 | |
declare -a FROM_ARRAY TO_ARRAY | |
cdDir() { | |
cd "${1}" || { echo "Error: ${1} is not a dir, exiting." >&2; exit 1; } | |
} | |
renameYtFiles() { | |
for i in "${!FROM_ARRAY[@]}"; do | |
mv "${FROM_ARRAY[i]}" "${TO_ARRAY[i]}" | |
done | |
} | |
mkFullDirPath() { | |
echo "Creating dir: ${1}" | |
mkdir -p "${1}" || { echo "Error: error creating dir ${1}" >&2 ; exit 1; } | |
} | |
nameFilter() { | |
sed -r -e 's/-[a-Z0-9]{10,11}\.(m4a|opus)$/\.\1/' \ | |
-e 's/ (\[|\().*(\]|\))//g' \ | |
-e 's/'\''//g' \ | |
-e 's/|//g' \ | |
-e 's/,//g' \ | |
-e 's/_/ /g' \ | |
-e 's/(([a-Z])|[ ])[-_] /\2 - /g' \ | |
<<< "${1}" | |
} | |
if [[ -e ${TO_DIR} ]]; then | |
cdDir "${TO_DIR}" | |
else | |
mkFullDirPath "${TO_DIR}" | |
cdDir "${TO_DIR}" | |
fi | |
# --restrict-filenames actually makes it harder to remove brakcets | |
# -x is what extracts the audio, if you want video remove this. | |
youtube-dl -iwx --yes-playlist "${1}" | grep '^\[download\]' | |
while read -rd '' line; do | |
FROM_DIR="${line%/*}" # get path | |
FROM_DIR="${FROM_DIR/./}" | |
FROM_NAME="${line##*/}" # get basename | |
TO_NAME="$(nameFilter "${FROM_NAME}")" | |
FROM_ARRAY+=("${FROM_DIR}${FROM_NAME}") | |
TO_ARRAY+=("${FROM_DIR}${TO_NAME}") | |
done < <( find . -mindepth 1 -type f ! -name "$0" -print0 ) | |
column -t -s'|' <( | |
for i in "${!FROM_ARRAY[@]}"; do | |
echo "${FROM_ARRAY[i]}|${TO_ARRAY[i]}" | |
done | |
) | |
for (( i=seconds; i>0; i-- )); do | |
echo -ne "${bold}Ok to rename? Will contine in" \ | |
" [${red}${i}${normal}${bold}] seconds [Y/n]:${normal} \033[K\r" | |
sleep 1 | |
done & | |
loop_pid="$!" | |
read -t"$seconds" -rsN1 answer </dev/tty | |
kill "$loop_pid" &>/dev/null | |
echo | |
case $answer in | |
[Yy]|'') echo "Renaming files."; renameYtFiles ;; | |
*) echo "User cancelled the operation." >&2 ; exit 1 ;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment