Skip to content

Instantly share code, notes, and snippets.

@akrisanov
Created June 3, 2022 16:36
Show Gist options
  • Save akrisanov/a5785a6b5f33d0acc6760aa1b3c8086c to your computer and use it in GitHub Desktop.
Save akrisanov/a5785a6b5f33d0acc6760aa1b3c8086c to your computer and use it in GitHub Desktop.
#!/bin/bash
export PATH=/usr/bin:/bin:/usr/sbin:/sbin
# Create subfolder to store renamed files
createDestination() {
destination="$(dirname "$file")/sorted"
mkdir -p "$destination"
}
# Check for file MIME type
hasMIMEType() {
file -I "$file" | grep -q "$1"
}
# Send notification to user
sendNotification() {
osascript <<-EndOfMessage
display notification \
"$1" \
with title "Rename (Timestamp)"
EndOfMessage
}
# Determine file extension
setFileExtension() {
if hasMIMEType "image/jpeg"
then
extension="jpg"
elif hasMIMEType "image/heic"
then
extension="HEIC"
elif hasMIMEType "image/heif"
then
extension="HEIC"
elif hasMIMEType "video/quicktime"
then
extension="mov"
elif hasMIMEType "video/mp4"
then
extension="mp4"
elif hasMIMEType "video/m4v"
then
extension="m4v"
else
return 1
fi
}
# Retrieve EXIF timestamp from media file
getTimeStamp() {
local -r timestampGTM=$(mdls -name kMDItemContentCreationDate -raw "$file")
local -r timestampRaw=$(date -j -f "%F %T %z" "$timestampGTM" +"%Y-%m-%d %H:%M:%S" | cut -d ' ' -f -2)
timestamp=${timestampRaw//:/-}
}
# Rename file, handle timestamp collisions
renameFile() {
# Exit function if file type is not supported
setFileExtension || return 0
getTimeStamp || return 0
createDestination || return 1
# Check if to be renamed file already exists
if [[ -f "$destination/$timestamp.$extension" ]]
then
# If file exists append random string to file
local -r randomString=$(md5 -q "$file")
cp "$file" "$destination/$timestamp-$randomString.$extension"
else
cp "$file" "$destination/$timestamp.$extension"
fi
}
# Send notification to user after the process has finished
presentResults() {
# Count files in destination folder
local counter=0
for file in "$destination"/*.*
do
(( counter ++ ))
done
# Check if renaming was successful
if [ $counter != 0 ] && [ -n "$destination" ]
then
sendNotification "$counter photos/videos have been renamed. Opening destination folder…"
open "$destination"
else
sendNotification "Could not renamd any photos/videos."
fi
}
# Main loop to collect input files from Automator
processFiles() {
while read -r file; do
renameFile
done
}
sendNotification "Processing photos/videos.\\nThis can take a while…"
processFiles
presentResults
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment