Apple script to export images from "Photos" application - applescript

I have albums and nested albums and folders in Photos application. I want my applescript to export images maintaining the Album or Folder structure that I have the in the application.
I tried scripts available online :
tell application "Finder"
set location_1 to (choose folder with prompt "Choose a folder to export into") as text
end tell
tell application "Photos"
set x to name of every folder
choose from list x with prompt "Choose a project to export"
set theP to item 1 of result
tell application "Finder" to make new folder at alias location_1 with properties {name:theP}
tell folder theP
set initflist to every folder
set initalist to every album
if initflist is equal to {} then
log "process albums"
processAlbums(initalist, location_1 & theP) of me
else
if initalist is not equal to {} then
log "process albums"
processAlbums(initalist, location_1 & theP) of me
end if
log "process sub folders "
processSfolders(initflist, (location_1 & theP)) of me
end if
end tell
end tell
on processAlbums(alist, apath)
tell application "Photos"
repeat with a in alist
tell a
set theimages to get media items of album a
set thename to name of a
tell application "Finder"
if not (exists folder thename in alias apath) then
make new folder at alias apath with properties {name:thename}
end if
set destination to apath & ":" & thename & ":"
end tell
with timeout of 6000 seconds
tell a
set settings to "JPEG - Original Size"
export theimages to alias destination
end tell
end timeout
end tell
end repeat
end tell
end processAlbums
on processSfolders(flist, fpath)
tell application "Photos"
repeat with a in flist
try
set thename to name of a
tell application "Finder"
if not (exists folder thename in alias fpath) then
make new folder at alias fpath with properties {name:thename}
end if
end tell
tell a
set sAlist to every album
set sflist to every folder
if sflist is equal to {} then
processAlbums(sAlist, fpath & ":" & thename) of me
else
if sAlist is not equal to {} then
processAlbums(sAlist, fpath & ":" & thename) of me
end if
processSfolders(sflist, fpath & ":" & thename) of me
end if
end tell
on error errMsg
log "error"
end try
end repeat
end tell
end processSfolders
The issue is that it gets names of only child albums and not top level albums. I have to maintain the entire structure of album or folder.
I do not know AppleScript and I tried tweaking this one but no luck so far. can I get a direction please?

You can get the name of the folders, and the albums contained in the folder, which will enable you to create the top level and child directories. Albums can only contain media items, not albums. Top level albums are classified as folders or containers. In the Applescript dictionary for Photos, it gives the definitions for these items.
tell application "Finder"
set location_1 to (choose folder with prompt "Choose a folder to export into") as text
end tell
tell application "Photos"
activate
set fds to folders
repeat with fd in fds
set fdName to name of fd
set abNames to every album of fd
if parent of fd is missing value then
my createFolders(fdName, abNames, location_1, fd)
end if
end repeat
end tell
on createFolders(fName, aAlbums, fPath, fd)
tell application "Finder"
if not (exists folder fName in alias fPath) then
make new folder with properties {name:fName} at fPath
end if
repeat with a in aAlbums
set aName to name of a
set aPath to ((fPath as alias) as text) & fName
if not (exists folder aName in alias aPath) then
make new folder with properties {name:aName} at aPath
end if
set exPath to ((aPath as alias) as text) & aName
my exportImages(a, exPath)
end repeat
end tell
tell application "Photos"
set rcFolders to every folder of fd
repeat with rcFd in rcFolders
set rcAlbums to every album of rcFd
set rcName to name of rcFd
set rcPath to ((fPath as alias) as text) & fName
my createFolders(rcName, rcAlbums, rcPath, rcFd)
end repeat
end tell
end createFolders
on exportImages(photoAlbum, destination)
tell application "Photos"
set theimages to get media items of photoAlbum
with timeout of 6000 seconds
tell photoAlbum
set settings to "JPEG - Original Size"
export theimages to alias destination
end tell
end timeout
end tell
end exportImages
EDIT - Error Handling
To handle errors, locate the command that is causing the error and wrap it in a try block. Solution could be to quit the application, so that the process will end, and maybe add a short delay and then continue with the script.
try
export theimages to alias destination
on error
-- statements to execute in case of error
error "The exporting of images failed to complete"
quit
end try
From the developer reference - When a command fails to complete in the allotted time (whether the default of two minutes, or a time set by a with timeout statement), AppleScript stops running the script and returns the error "event timed out". AppleScript does not cancel the operation—it merely stops execution of the script. If you want the script to continue, you can wrap the statements in a try statement. However, whether your script can send a command to cancel an offending lengthy operation after a timeout is dependent on the application that is performing the command. Further info regarding try statements.

Related

Combining two (applescript) scripts into one

I'm trying to simplify my workflow by combining the following two applescripts into one, they work fine separately but it'd be more efficient to combine them.
In short, script A trims a file name into the last 3 characters and Script B adds the folder name (where the files reside) to the file name.
This might be a very simple fix but I'm script-writing challenged so any help is welcomed.
SCRIPT A:
on open whichFile
repeat with aFile in whichFile
tell application "Finder"
set filename to name of aFile
set name of aFile to ((characters -1 thru -7 of filename) as string)
--set name of whichFile to ((characters 1 thru -4 of filename) as string) --trim last 3
end tell
end repeat
end open
SCRIPT B
on open theDroppedItems
repeat with a from 1 to length of theDroppedItems
set theCurrentDroppedItem to item a of theDroppedItems
set theCurrentDroppedItem to theCurrentDroppedItem as string
tell application "System Events"
set folderPath to theCurrentDroppedItem as string
--display dialog (folderPath)
set AppleScript's text item delimiters to ":"
set newFileName to (text item -4 of folderPath as string) & "-" & (text item -2 of folderPath as string) & "-" & (text item -1 of folderPath as string)
--display dialog (newFileName)
--rename file
set fileAlias to (theCurrentDroppedItem) as alias
set the name of fileAlias to newFileName
end tell
end repeat
end open
You can start by opening a new Script Editor document for the combined script. The open handler is passed a list of file items, so you can add a new handler declaration with an empty repeat statement that steps through the dropped items. From there, just identify the statements that perform the various operations (trim name, get folder name, etc), and copy them into the new open handler's repeat statement, editing as needed to use consistent variable names.
Once the new script is running, then you can look at optimizing it by combining and/or rearranging statements that may be doing the same thing in the different scripts. It can also be helpful to organize functions into their own handlers, such as the getNamePieces handler below. I also like to add a run handler with a choose file dialog so that you can test without having to drag items onto a droplet.
Note that the file name includes any extension, so you should break it apart in order to work with just the name part. There is also a bit of unnecessary thrashing about in the script that gets the folder name, so after cleaning it up your script could look something like:
on run
open (choose file with multiple selections allowed)
end run
on open droppedItems
repeat with anItem in droppedItems
set {folderPath, theName, extension} to getNamePieces from anItem
set trimmedName to text -1 thru -3 of theName -- work with just the name part
tell application "System Events"
set folderName to name of disk item folderPath
set newName to folderName & "-" & trimmedName & extension -- assemble the pieces
log newName -- for testing
# set name of anItem to newName -- uncomment to go live
end tell
end repeat
end open
to getNamePieces from someItem -- return the containing folder path, the name, and the extension
tell application "System Events" to tell disk item (someItem as text)
set theContainer to path of the container
set {theName, extension} to {name, name extension}
end tell
if extension is not "" then
set theName to text 1 thru -((count extension) + 2) of theName -- just the name part
set extension to "." & extension
end if
return {theContainer, theName, extension}
end getNamePieces

Add vcard to Contacts with Mail rules and Applescript

I receive a lot of customer vcards to a specific email address. I want to automatically add the vcards to my contacts through the Mail rules and an AppleScript.
I searched a lot and found something. I modified it a bit. And the opening and adding process works fine. But only when I choose a file. I can't get the file into a variable from the mail message. I tried it but it won't work.
Here is my code so far:
tell application "Mail"
set att to attachment
end tell
set thefile to att
tell application "Contacts"
activate
open thefile
end tell
tell application "System Events" to keystroke return
If I delete line 1, 2 and 3 and write in line 4 "set thefile to choose file" then it will work - if I choose a file.
But the first three lines I tried something out, but without any success.
So my question is, how can I get the file from the message?
Thank you
Yours sincerely,
Chris
Solution:
set Dest to ((path to desktop folder) as string)
tell application "Finder" to make new folder in Dest with properties {name:"TempFiles"} -- create TempFiles folder
Set Dest to Dest & "TempFiles:"
tell application "Mail"
activate -- not sure is mandatory, but I prefer to see selected mails !!
set ListMessage to selection -- get all selected messages
repeat with aMessage in ListMessage -- loop through each message selected
set AList to every mail attachment of aMessage -- get all attachements
repeat with aFile in AList -- for each attachement
if (downloaded of aFile) then
set Filepath to Dest & (name of aFile)
do shell script "touch " & (quoted form of (POSIX path of Filepath)) -- required because "Save" only works with existing file !
save aFile in (Filepath as alias) as native format
end if
end repeat -- next file
end repeat -- next message
end tell
tell application "Finder" to set CardList to every file of folder Dest whose name extension is {"vcf"}
tell application "Contacts"
activate
repeat with aCard in CardList
open aCard
delay 1
tell application "System Events" to keystroke return
end repeat
end tell
delay 2
-- tell application "Finder" to delete folder Dest
The file attached from email respond to the 'save" command, but not to 'open'. Then, you must first save the attached files, and later, move them to next application (add in 'Contacts' in your case).
The attachement is a member of a list of 'mail attachement' of a message : keep in mind that there could be many files attached.
Also, you can only save the attached file if its 'downloaded' attribute is true.
Last, but not least, it seems that the "save" instruction which was working nice in Snow Leopard, does not work the same in El Capitain : the file where to save must exist before the "save"...this is why I added the "touch" command to create it first (just create the entry in the tempFiles folder).
I also add at bottom of script the open vCard with the enter key to validate in Contact. You may have to add a delay to leave sometime for your computer to process the card.
if the keys broke does not work in your case, please check System Preferences accessibility settings to allow your computer to let your script control your Mac.
I added as much comments as possible to make it clear...may be too much !
set Dest to ((path to desktop folder) as string)
tell application "Finder" to make new folder in Dest with properties {name:"TempFiles"} -- create TempFiles folder
Set Dest to Dest & "TempFiles:"
tell application "Mail"
activate -- not sure is mandatory, but I prefer to see selected mails !!
set ListMessage to selection -- get all selected messages
repeat with aMessage in ListMessage -- loop through each message selected
set AList to every mail attachment of aMessage -- get all attachements
repeat with aFile in AList -- for each attachement
if (downloaded of aFile) then
set Filepath to Dest & (name of aFile)
do shell script "touch " & (quoted form of (POSIX path of Filepath)) -- required because "Save" only works with existing file !
save aFile in (Filepath as alias) as native format
end if
end repeat -- next file
end repeat -- next message
end tell
tell application "Finder" to set CardList to every file of folder Dest whose name extension is {"vcf"}
tell application "Contacts"
activate
repeat with aCard in CardList
open aCard
tell application "System Events" to keystroke return
end repeat
end tell
-- tell application "Finder" to delete folder Dest
As you can see, I filter the content of the temp folder with only files with extension 'vcd'...just in case your selected emails contain also other type of file which Contact can't handled.
At end of the script, I delete the temp folder. however, until you test it, I set this last row as a comment only (more safe !)

how to fix 100's of alias' on mac after migration?

I really hope someone can help me out with this. I recently moved from one mac to another and did a clean install. I have several folders with hundreds of alias (how do you say the plural of alias?)...
The original file path is "/Volumes/Media Drive/Ableton/Warped Tracks/", and the new path needs to be "/users/joel/Music/Ableton Projects/Warped Tracks"
I see how to fix them one at a time, but that would take hours. I tried this applescript, but had no luck:
https://apple.stackexchange.com/questions/2656/how-do-i-fix-failed-aliases
Can anyone give me a better applescript or another solution? As I mentioned, I tried this applescript:
tell application "Finder"
set these_items to the selection
end tell
repeat with i from 1 to the count of these_items
set this_item to (item i of these_items) as alias
set this_info to info for this_item
if class of this_item is alias then
tell application "Finder"
set original_file to original item of this_item
set this_alias_file_name to displayed name of this_item
set container_folder to container of this_item
set the_path to the POSIX path of (original_file as alias)
set new_path to my replaceText("/Volumes/Media Drive/Ableton/Warped Tracks/", "/users/joel/Music/Ableton Projects/Warped Tracks", the_path)
move this_item to trash
try
make new alias file at container_folder to (POSIX file new_path) with properties {name:this_alias_file_name}
on error errMsg number errorNumber
if errorNumber is -10000 then -- new original file not found, try relinking to old
try
make new alias file at container_folder to (POSIX file the_path) with properties {name:this_alias_file_name}
on error errMsg number errorNumber
if errorNumber is -10000 then -- old original not found. link's dead Jim
display dialog "The original file for alias " & this_alias_file_name & " was not found."
else
display dialog "An unknown error occurred: " & errorNumber as text
end if
end try
else
display dialog "An unknown error occurred: " & errorNumber as text
end if
end try
end tell
end if
end repeat
on replaceText(find, replace, subject)
set prevTIDs to text item delimiters of AppleScript
set text item delimiters of AppleScript to find
set subject to text items of subject
set text item delimiters of AppleScript to replace
set subject to "" & subject
set text item delimiters of AppleScript to prevTIDs
return subject
end replaceText
Any help would be greatly appreciated.
Edit: I think the problem with the applescript for me is that I have folders further down the path that all are different, and THOSE each contain the individual alias files. IE:
"/users/joel/Music/Ableton Projects/Warped Tracks/Folder A/file.alias",/users/joel/Music/Ableton Projects/Warped Tracks/Folder B/file2.alias", etc, etc
I had same issue years ago (transfer between 2 media centers), and I made this program : it asks for folder were all broken alias are and then try to find again original path to rebuild them.
the thing is that any applescript instruction about alias gives error when link is broken, so you must use Finder info window to read original path without error when the link is already broken:
(this program assumes that original file name is unique)
-- Select main folder
tell application "Finder" to set Mon_Dossier to ((choose folder with prompt "Select top folder:" without invisibles) as alias) as string
-- repair alias in this folder and all subsequent folders (entire contents)
tell application "Finder" to set Mes_Alias to every file of entire contents of folder Mon_Dossier whose class is alias file
-- loop on each alias of the folder
repeat with Mon_Alias in Mes_Alias
-- found the original file path of Mon_Alias
-- try first with standard alias call
set F_Source to ""
try
tell application "Finder" to set F_Source to original item of Mon_Alias
end try
if F_Source is "" then
-- the link to original file is broken, then use on windows info method
set F_Source to Origine_Alias(Mon_Alias)
set F_Original to Decompose(F_Source)
-- no need to look original file as is, becuase the link is broken (path changed ?)
-- then directly search for the same file without extension
set Cible to ((chemin of F_Original) as string) & ((Nom of F_Original) as string)
tell application "Finder"
if exists file Cible then
-- file is found without extension
-- then delete alias and create new alias with same name and in same folder
set A_Nom to name of Mon_Alias
set A_Dossier to folder of Mon_Alias
delete Mon_Alias
set Nouvel_Alias to make alias to Cible at A_Dossier
set name of Nouvel_Alias to A_Nom
else
SLog("Alias=" & (Mon_Alias as string) & " File not found=" & Cible)
end if
end tell
else
-- the alias link is still valid : nothing to do ! go to next alias..
end if
end repeat
-- end main program
-- sub routine to find passe of broken link (original path/file can't be found)
-- the result is a unix path like folder/sub_folder/file
on Origine_Alias(F_Alias)
set R to ""
tell application "Finder" to open information window of file (F_Alias as text)
tell application "System Events" to tell process "Finder" to set R to value of static text 19 of scroll area 1 of front window
tell application "Finder" to close front window
return R
end Origine_Alias
-- sub routine to extract, from unix file path, the path, the file name and its extension: result is sent back in a record
-- Warning : we can't use "Posix file of" becuase the path and the file are non longer valid ! (then Posix gives error)
on Decompose(Local_F)
--search the first "." from right to find extension
set X to length of Local_F
repeat while (character X of Local_F is not ".") and (X > 0)
set X to X - 1
end repeat
if X > 0 then
set L_Ext to text (X + 1) thru (length of Local_F) of Local_F
set Local_F to text 1 thru (X - 1) of Local_F
else
L_Ext = "" -- "." not found, then no extension !
end if
-- search first "/" from the right to extract file name
set X to length of Local_F
repeat while (character X of Local_F is not "/")
set X to X - 1
end repeat
set L_Nom to text (X + 1) thru (length of Local_F) of Local_F
set Local_F to text 1 thru (X) of Local_F
try
set L_Chemin to POSIX file Local_F
end try
return {chemin:L_Chemin, Nom:L_Nom, Ext:L_Ext}
end Decompose
-- sub routine log (text log file on desktop)
on SLog(msg)
set the my_log to ¬
((path to desktop) as text) & "My_logfile.txt"
try
-- open file. create it if not yet exist
open for access file the my_log with write permission
-- add text at end of file
write (msg & return) to file the my_log starting at eof
close access file the my_log
on error
try
close access file the my_log
end try
end try
end SLog

Applescript CS5 and CS6 export with save for web will not work

I am at my wit's end. I have tried all variations to get this script to work. The error I get is Adobe Photoshop CS6 got an error: Can’t get current document. and the highlighted script error is my "export in file newFileName.." block. I've tried putting alias in different positions, using file, not using file. Also I get this error message, but the actual script seems to stop working right after "set docName to name of docRef"
And basically I just copied this code from another script that was working fine and just changed a save this file... to a export this file...
-- set the folders that you want to use
set inputFolder to choose folder with prompt "Choose the folder of images to downsize."
set pathToDesktop to (path to desktop folder as string)
set outputFolder to pathToDesktop & "PhotoshopRetina:"
tell application "Finder"
set filesList to files in folder inputFolder
if not (exists folder outputFolder) then
make new folder at desktop with properties {name:"PhotoshopRetina"}
end if
end tell
with timeout of 86400 seconds
tell application "Adobe Photoshop CS6"
set display dialogs to never
close every document saving no
end tell
repeat with aFile in filesList
tell application "Finder"
-- The step below is important because the 'aFile' reference as returned by
-- Finder associates the file with Finder and not Photoshop. By converting
-- the reference below 'as alias', the reference used by 'open' will be
-- correctly handled by Photoshop rather than Finder.
set theFile to aFile as string
set theFileName to name of aFile
set theFileInfo to info for alias theFile
if kind of theFileInfo is "Adobe Photoshop JPEG file" then
my retinaDisplay(theFile)
end if
end tell
end repeat
end timeout
end
on retinaDisplay(theFile)
tell application "Adobe Photoshop CS6"
open alias theFile
set docRef to the current document
-- Convert the document to a document mode that supports saving as jpeg
if (mode of docRef is not RGB) then
change mode docRef to RGB
end if
tell docRef
set color profile kind to none
end tell
set infoRef to get info of docRef
set docName to name of docRef
set docBaseName to getBaseName(docName) of me
set newFileName to (my outputFolder as string) & docBaseName & ".jpg"
tell current document
export in file newFileName as save for web with options {class:save for web export options, web format:JPEG, embed color profile:false, quality:45} with copying
end tell
close current document without saving
end tell
end retinaDisplay
-- Returns the document name without extension (if present)
on getBaseName(fName)
set baseName to fName
repeat with idx from 1 to (length of fName)
if (item idx of fName = ".") then
set baseName to (items 1 thru (idx - 1) of fName) as string
exit repeat
end if
end repeat
return baseName
end getBaseName
end
If I open an image in photoshop I can run this code with no errors.
set f to (path to desktop as text) & "test.jpg"
tell application "Adobe Photoshop CS6"
tell current document
export in file f as save for web
end tell
end tell
However, if I additionally add your "with options" code then I get your error. I don't even know what the "with copying" part is. I don't think that means anything to photoshop. So the problem is not with the "current document". The problem is with your options. You must be doing that part wrong.
Good luck.

AppleScript: Create new folder from file name and move file into that folder

Basically, I'm trying to create a folder action in Automator so whenever a file is added to a specific folder, it will create a subfolder that matches the filename (without the extension), then move the file into that subfolder.
So far, I have successfully used a post from this site (Create new folder named with a specified file name in Automator) to create a script that will create the new folder. However, I have been unable to modify the script to move the original file into the new folder.
Any help would be appreciated. Here is the full script I am working with for reference:
on run {input, parameters} -- make new folders from base file names
set output to {}
repeat with anItem in the input -- step through each item in the input
set anItem to anItem as text
tell application "System Events" to tell disk item anItem
set theContainer to path of container
set {theName, theExtension} to {name, name extension}
end tell
if theExtension is in {missing value, ""} then
set theExtension to ""
else
set theExtension to "." & theExtension
end if
set theName to text 1 thru -((count theExtension) + 1) of theName -- the name part
tell application "Finder"
make new folder at folder theContainer with properties {name:theName}
set end of output to result as alias
end tell
end repeat
return input -- or output
end run
Thanks in advance!
Add this folder action to your target folder:
on adding folder items to theFolder after receiving theFiles
repeat with aFile in theFiles
tell application "System Events" to set {Nm, Ex, pPath} to aFile's {name, name extension, POSIX path of container}
set BN to text 1 thru ((get offset of "." & Ex in Nm) - 1) of Nm
set thePath to (pPath & "/" & BN & "/" as text)
do shell script "mkdir -p " & quoted form of thePath
delay 0.5
tell application "Finder" to move aFile to POSIX file thePath
end repeat
end adding folder items to

Resources