#!/bin/bash set -e YTDLP=$(which yt-dlp) JQ=$(which jq) FFMPEG=$(which ffmpeg) download() { DOWNLOAD_LINK="${1}" SAVE_PATH="${2}" ${YTDLP} -o "${SAVE_PATH}/%(id)s.%(ext)s" \ -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best' \ --write-auto-subs --write-subs --sub-lang en,ru --convert-subs srt --sub-format vtt \ ${DOWNLOAD_LINK} } download_playlist() { PLAYLIST="${1}" JSON="$(${YTDLP} --flat-playlist -j "${PLAYLIST}" 2>/dev/null)" TITLE="$(echo ${JSON} | ${JQ} -r '.playlist_title' | head -n 1)" VIDEOS="$(echo ${JSON} | ${JQ} -r '.title')" IDS="$(echo ${JSON} | ${JQ} -r '.id')" LINKS="$(echo ${JSON} | ${JQ} -r '.original_url')" ALL_LINES=$(echo "${JSON}" | wc -l) mkdir -v "${TITLE}" for ((NUMBER=1; NUMBER<=ALL_LINES; NUMBER++)); do VIDEO="$(echo "${VIDEOS}" | awk "NR==${NUMBER}")" LINK="$(echo "${LINKS}" | awk "NR==${NUMBER}")" VIDEO="${VIDEO//\//-}" DIR_NAME="${NUMBER} - ${VIDEO}" mkdir -v "${TITLE}/${DIR_NAME}" download "${LINK}" "${TITLE}/${DIR_NAME}" done } merge() { MP3="${1}" MP4="${2}" SRT_EN="${3}" SRT_RU="${4}" CURRENT_PATH="${5}" OUTPUT="$(basename "${CURRENT_PATH}")" cd "${CURRENT_PATH}" ${FFMPEG} -i "${MP4}" -i "${MP3}" -i "${SRT_RU}" -i "${SRT_EN}" \ -map 0 -map 1 -map 2 -map 3 \ -c:v copy -c:a copy -metadata:s:a:0 language=eng -metadata:s:a:1 language=rus \ -c:s mov_text -metadata:s:s:0 language=rus -metadata:s:s:1 language=eng -disposition:s:0 default -disposition:s:1 default \ "${OUTPUT}.mp4" } merge_mp3() { SRCDIR="$(realpath "${1}")" for DIR in "${SRCDIR}"/* do for FILE in $(ls "${DIR}") do if [[ "${FILE}" == *".mp3" ]]; then MP3="${FILE}" elif [[ "${FILE}" == *".en.srt" ]]; then SRT_EN="${FILE}" elif [[ "${FILE}" == *".ru.srt" ]]; then SRT_RU="${FILE}" elif [[ "${FILE}" == *".mp4" ]]; then MP4="${FILE}" fi done [ ! -z "${MP3}" ] && [ ! -z "${SRT_EN}" ] && [ ! -z "${SRT_RU}" ] && [ ! -z "${MP4}" ] || continue merge "${MP3}" "${MP4}" "${SRT_EN}" "${SRT_RU}" "${DIR}" done } move_mp4() { SRCDIR="$(realpath "${1}")" DSTDIR="${2}" mkdir -p "${DSTDIR}" for DIR in "${SRCDIR}"/* do FILE="$(basename "${DIR}").mp4" mv -v "${DIR}/${FILE}" "${DSTDIR}" done } main() { COMMAND="${1}" [ ! -z ${COMMAND} ] && shift while [[ $# -gt 0 ]]; do KEY="${1}" VALUE="${2}" case "${KEY}" in -p|--playlist) PLAYLIST="${VALUE}" shift ;; -s|--source) SRCDIR="${VALUE}" shift ;; -d|--destination) DSTDIR="${VALUE}" shift ;; *) ;; esac shift done case "${COMMAND}" in download) [ -z "${PLAYLIST}" ] && echo "Playlist link unknown" && exit 1 download_playlist "${PLAYLIST}" ;; merge) [ -z "${SRCDIR}" ] && echo "Source directory not set" && exit 1 merge_mp3 "${SRCDIR}" ;; move) [ -z "${SRCDIR}" ] && echo "Source directory not set" && exit 1 [ -z "${DSTDIR}" ] && echo "Destination directory not set" && exit 1 move_mp4 "${SRCDIR}" "${DSTDIR}" ;; *) exit 1 ;; esac } main "${@}"