Search code examples
applescriptphoto

Apple scripts. Set name for photos with empty name


I have an apple script for setting names for photos in a "Photos" application.

tell application "Photos"
activate
set imageSel to (get selection)
if (imageSel is {}) then
    error "Please select at least one image."
else
    repeat with i from 1 to count of imageSel
        set next_image to item i of imageSel
        set capture_date to (the date of next_image)
        set short_capture_date_string to the short date string of capture_date
        set capture_time_string to the time string of capture_date
        set new_title to short_capture_date_string & " _ " & capture_time_string & " _ rnd" & (random number 1000)
        tell next_image
            set the name of next_image to the new_title as text
            set the description of next_image to the "" as text
        end tell
    end repeat
end if
return ¬
    "Adjusted the names of " & (the length of imageSel) ¬
    & ¬
    " photos.

end tell

Now the script sets new names for all photos indiscriminately. How can I modify it so that names are set only for those photos for which it is empty?


Solution

  • First of all the tell next_image block is wrong as next_image is already referenced in the tell block.

    And the as text coercions are redundant as both types are text.

    To process only photos with empty names check for "" at the beginning of the repeat loop.

    tell application "Photos"
        activate
        set imageSel to (get selection)
        if imageSel is {} then
            error "Please select at least one image."
        else
            repeat with i from 1 to count of imageSel
                set next_image to item i of imageSel
                if name of next_image is missing value or name of next_image is "" then
                    set capture_date to the date of next_image
                    set short_capture_date_string to the short date string of capture_date
                    set capture_time_string to the time string of capture_date
                    set new_title to short_capture_date_string & " _ " & capture_time_string & " _ rnd" & (random number 1000)
                    set the name of next_image to new_title
                    set the description of next_image to ""
                end if
            end repeat
        end if
        return ¬
            "Adjusted the names of " & (the length of imageSel) ¬
            & ¬
            " photos."
    end tell