Skip to content
This repository has been archived by the owner on Aug 9, 2023. It is now read-only.

Downloading trailers

Andrey Yantsen edited this page Aug 31, 2018 · 3 revisions

You can use following script to download trailers from youtube for movies within specified directory:

#!/bin/bash

if [ "$#" -ne 1 ]; then
    echo "Usage: $0 <Movies Folder>"
    exit 1
fi

#################################
#Base path to start search
BASE=$1
#TMDB Base URL
TMDB=https://api.themoviedb.org
#API Key
API=""
#Base Url for video download
YTB_URL="https://www.youtube.com/watch?v="
#################################

find "$BASE" -mindepth 1 -maxdepth 1 -type d -name '*(*)' -exec sh -c '! ls -1 "{}/" | egrep -i -q -- "-trailer\.mp4$"' ';' -print | while read dirname
do
	MOVNAME=$(basename "$dirname")
	MOVNAMEMOD=$((basename "$dirname" | cut -d "(" -f1) | sed -e 's/[[:space:]]*$//' | sed 's/ /%20/g')
	MOVYEAR=$(basename "$dirname" |  cut -d "(" -f2 | cut -d ")" -f1)

	MOVID=$((curl -s --request GET --url "$TMDB/3/search/movie?year=$MOVYEAR&query=$MOVNAMEMOD&language=en-US&api_key=$API" --header 'content-type: application/json' --data '{}' ) | cut -d ":" -f7 | cut -d ":" -f6 | cut -d "," -f1)
	for TMDBLANG in 'ru-RU' 'en-US'
	do
		URLS=$(curl -s --request GET "$TMDB/3/movie/$MOVID/videos?api_key=$API&language=$TMDBLANG" | jq -r ".results[] | select(.type == \"Trailer\") | select(.site == \"YouTube\") | \"$YTB_URL\" + .key")

		echo `date`
		echo "*****"$MOVNAME" / $TMDBLANG*****"

		if [[ -z "$URLS" ]]
		then
			echo 'No trailers found'
			echo ""
		else
			echo ""Downloading from YouTube: $URLS""
			youtube-dl --recode-video mp4 --merge-output-format mp4 --postprocessor-args '-c:v libx264 -level:v 3.1 -b:v 1000k -minrate 800k -maxrate 1000k -bufsize 1835k -c:a aac -strict -2 -movflags frag_keyframe+empty_moov+default_base_moof+faststart' -i -f bestvideo+bestaudio -o "$dirname/Trailer #%(autonumber)01d %(title)s-trailer.%(ext)s" $URLS && echo '' && break
		fi
	done
done

echo `date`": Search complete."

Do not forget to change API variable to a proper TMDB's API-key value. You should pass your movies folder as first argument. Within this folder movies should be stored as following:

dir/
    Avatar (2009)/
        Avatar (2009).avi

The extension of movie doesn't really matter. For proper working you need to have on your system following software installed:

  1. ffmpeg
  2. youtube-dl
  3. jq
Clone this wiki locally