Skip to content

Instantly share code, notes, and snippets.

@whatyoubendoing
Created May 27, 2019 20:16
Show Gist options
  • Save whatyoubendoing/e8eede5b6681015ae0a292a2198d13e1 to your computer and use it in GitHub Desktop.
Save whatyoubendoing/e8eede5b6681015ae0a292a2198d13e1 to your computer and use it in GitHub Desktop.
A shell script to add to Transmission so the downloads automatically get added to iTunes library. If conversion (with or without encoding) is required from MKV or AVI formats to MP4, this script automatically does that before adding to library. (HandBrakeCLI and FFMPEG required).
#!/bin/bash
# development
# if [ -z "$1" ]; then
# TR_DOWNLOADS="$TR_TORRENT_DIR/$TR_TORRENT_NAME"
# else
# TR_DOWNLOADS="$1"
# TR_TORRENT_NAME="Temp_Torrent_Name"
# fi
# production
TR_DOWNLOADS="$TR_TORRENT_DIR/$TR_TORRENT_NAME"
LOG_DIR="$HOME/Downloads/Transmission Downloads/Logs"
mkdir -p "$LOG_DIR"
LOGFILE=$LOG_DIR/$TR_TORRENT_NAME.log
if [ ! -e "$LOGFILE" ] ; then
touch "$LOGFILE"
fi
function edate {
echo "`date '+%Y-%m-%d %H:%M:%S'` $1" >> "$LOGFILE"
# development
# echo "$1"
}
function copy_file() {
edate "Copying $1 to iTunes folder"
cp -v "$1" $HOME/Music/iTunes/iTunes\ Media/Automatically\ Add\ to\ iTunes.localized/ >> "$LOGFILE"
}
function convert_and_copy_file() {
filename=$(basename "$1")
extension="${filename##*.}"
filename="${filename%.*}"
cd $HOME/Downloads > /dev/null 2>&1
current_time=$(date "+%Y.%m.%d-%H.%M.%S")
mkdir "$current_time"
edate "Converting $1"
/usr/local/bin/ffmpeg -i "$1" -c:v copy -c:a copy "$current_time/$filename.mp4" >> "$LOGFILE"
# You can use ffmpeg for just converting the container of the file to mp4, copying the audio and video streams.
# Or if you file needs encoding, you can use HandBrake for that.
# /usr/local/bin/HandBrakeCLI -i "$1" -o "$current_time/$filename.mp4" --preset="Normal" >> "$LOGFILE"
edate "Conversion complete"
edate "Copying $current_time/$filename.mp4 to iTunes folder"
mv -vf "$current_time/$filename.mp4" $HOME/Music/iTunes/iTunes\ Media/Automatically\ Add\ to\ iTunes.localized/ >> "$LOGFILE"
rm -frv "$current_time"
}
function process_file() {
filename=$(basename "$1")
extension="${filename##*.}"
filename="${filename%.*}"
edate "Processing file: $filename.$extension"
case "$extension" in
"mp4") copy_file "$1"
;;
"m4v") copy_file "$1"
;;
"mkv") convert_and_copy_file "$1"
;;
"avi") convert_and_copy_file "$1"
;;
esac
}
edate "Directory is $TR_TORRENT_DIR"
edate "Torrent ID is $TR_TORRENT_ID"
edate "Torrent Hash is $TR_TORRENT_HASH"
edate "Working on the new download $TR_DOWNLOADS"
if [ -d "$TR_DOWNLOADS" ]; then
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
for f in $(find "$TR_DOWNLOADS"); do
if ! [ -d "$f" ]; then
process_file "$f"
fi
done;
IFS=$SAVEIFS
else
process_file "$TR_DOWNLOADS"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment