Skip to content

Instantly share code, notes, and snippets.

@mark-kubacki
Last active October 6, 2016 19:26
Show Gist options
  • Save mark-kubacki/3eb02ef60c18534ba485 to your computer and use it in GitHub Desktop.
Save mark-kubacki/3eb02ef60c18534ba485 to your computer and use it in GitHub Desktop.
gets videos from the internet and stores them as MKV
#!/bin/bash
#
# Gets videos, for example from YouTube, as best-quality separate tracks
# and stitches them, video by video, into a MKV – avoiding excess clutter files.
#
# wrapper to: mkvtoolnix youtube-dl iconv jq file
#
# author: W-Mark Kubacki <wmark@hurrikane.de>
set -e -o pipefail
if [[ -t 1 ]] && tput colors >&/dev/null; then
V_BOLD_RED=$(tput bold; tput setaf 1)
V_BOLD_GREEN=$(tput bold; tput setaf 2)
V_VIDOFF=$(tput sgr0)
fi
info() {
printf "${V_BOLD_GREEN}${1}${V_VIDOFF}"
}
error() {
>&2 printf "${V_BOLD_RED}${1}${V_VIDOFF}"
}
stitch_result() {
source_files=()
tracks_from=()
attach=()
while read FNAME; do
source_files+=("${FNAME}")
if [[ "${FNAME}" =~ (json|jpeg|jpg|png|webp)$ ]]; then
attach+=("--attachment-mime-type" $(file --brief --mime-type "${FNAME}"))
attach+=("--attach-file" "${FNAME}")
continue
fi
tracks_from+=("${FNAME}")
done < <(find -type f -name "*${1%%=*}*")
description_file="$(find -type f -name "*${1%%=*}*.json")"
output_filename="$(jq -r .'title' "${description_file}" | iconv -c -t UTF-8//TRANSLIT | tr -d '"*/:<>?|&' | sed -e 's:\.\.\.:…:').mkv"
if [[ -s "${output_filename}" ]]; then
error "Output file already exists: ${output_filename}\n"
exit
fi
mkvmerge \
--title "$(jq -r .'fulltitle' "${description_file}")" \
-o "${2}/${output_filename}" \
"${tracks_from[@]}" \
"${attach[@]}"
info "Finished: ${output_filename}\n"
rm "${source_files[@]}"
}
download_content() {
local LINK="${1}"
info "Started: $LINK\n"
local WORKDIR="$(mktemp -d -t ytdownload.XXXXXX)"
mkdir -p "${WORKDIR}/video" "${WORKDIR}/audio"
cd "${WORKDIR}"
(cd "audio"; youtube-dl --no-overwrites --format bestaudio --write-info-json --write-thumbnail "${LINK}")
(cd "video"; youtube-dl --no-overwrites --format bestvideo "${LINK}")
stitch_result "${LINK##*=}" "${2}"
cd ..
rm -r "${WORKDIR}"
}
: ${destdir:="$(pwd)"}
for LINK; do
if [[ ! "$LINK" == *"://"* ]]; then
LINK="https://www.youtube.com/watch?v=${LINK}"
fi
download_content "$LINK" "${destdir}" &
done
wait
info "Done.\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment