FFMPEG converter script

From msgwiki
Jump to navigation Jump to search
#!/bin/bash
# Define the source and destination directories
source_dir="/media/nextcloud/msgcnx/walt/files/Teacher/Math/Algebra 1/Lesson Videos"
destination_dir="/media/nextcloud/msgcnx/walt/files/Teacher/Math/Algebra 1/PUBLIC Lesson Videos"

# Check if the source directory exists
if [ ! -d "$source_dir" ]; then 
    echo "Source directory not found: $source_dir"
    exit 1 
fi

# Check if the destination directory exists 
if [ ! -d "$destination_dir" ]; then
    echo "Destination directory not found: $destination_dir"
    exit 1
fi

# Function to convert MOV files to MP4
convert_mov_to_mp4() {
    local source_file="$1"
    local destination_file="$2"
    echo "Converting $source_file"
    
    # Perform the conversion
    ffmpeg -i "$source_file" -c:v libx264 -c:a aac "$destination_file" -nostdin 2>/dev/null
    chown www-data:www-data "$destination_file"
}

# Initialize the converted variable outside of the loop
converted=0

# Find and convert MOV files in subdirectories
while IFS= read -r -d  source_file; do
    # Get the relative path of the source file
    relative_path="${source_file#$source_dir/}"
    # Determine the destination file path
    destination_file="$destination_dir/${relative_path%.*}.mp4"
    # Check if the corresponding MP4 file already exists in the destination
    if [ ! -e "$destination_file" ]; then
        # Ensure the destination directory exists
        mkdir -p "$(dirname "$destination_file")"
        # Convert MOV to MP4 and increment the counter
        convert_mov_to_mp4 "$source_file" "$destination_file"
        converted=1
    fi
done < <(find "$source_dir" -type f -name "*.mov" -print0)

# Remove any converted mp4 files that do not have a corresponding mov file
echo "Removing any extra files"

# Clean the destination directory
while IFS= read -r -d  mp4_file; do
    other_dir="$source_dir/${mp4_file#${destination_dir}/}"
    mov_file="${other_dir%.*}.mov"
    if [ ! -e "$mov_file" ]; then
        rm "$mp4_file"
        converted=1
        # Set the variable if any files are removed
        echo "A file was removed"
        echo "$mp4_file"
    fi
done < <(find "$destination_dir" -type f -name "*.mp4" -print0)

# Check if any files were converted
if [ "$converted" -eq 1 ]; then
    echo "Files converted successfully."
    # sudo -u www-data php /var/www/html/next.msgcnx/occ files:scan --path=/walt/files/Teacher/Math/Algebra\ 1/Lesson\ Videos/
    sudo -u www-data php /var/www/html/next.msgcnx/occ files:scan --path="${destination_dir#/media/nextcloud/msgcnx}"
    chown -R www-data:www-data "$destination_dir"
    echo "Nextcloud scan complete."
else
    echo "No files were converted."
fi
exit 0