Set creation date using SetFile / date formatting - shell

I'd like to copy creation date from a file and apply it to the folder the file is sitting in. I'm using SetFile for this purpose. I"m getting error: Invalid date/time. My assumption is that it's the format of the date that is not working. How do I format the date properly? Could someone suggest solution? Thanks
set filesToProcess to choose folder with prompt "Select folders:" with multiple selections allowed
repeat with thisFile in filesToProcess
tell application "Finder"
try
set creationDate to creation date of (first file in the entire contents of thisFile whose name ends with "low_r.pdf")
set formattedCreationDate to --creationDate needs reformatting?
do shell script "SetFile -d " & formattedCreationDate & " " & quoted form of (POSIX path of thisFile)
on error fileNotFound
set label index of thisFile to 2
display dialog fileNotFound
end try
end tell
end repeat

Final working code:
set filesToProcess to choose folder with prompt "Select folders:" with multiple selections allowed
repeat with thisFile in filesToProcess
tell application "Finder"
try
set creationDate to creation date of (first file in the entire contents of thisFile whose name ends with "low_r.pdf")
set formattedCreationDate to quoted form of my stringForDate(creationDate)
set formattedFolderLocation to quoted form of (POSIX path of thisFile)
do shell script "SetFile -d " & formattedCreationDate & " " & formattedFolderLocation
on error errorMsg
set label index of thisFile to 2
--display dialog errorMsg
end try
end tell
end repeat
on stringForDate(aDate)
if aDate is "" then return null
if class of aDate is not date then return null
set {year:dYear, month:dMonth, day:dDay, hours:dHours, minutes:dMinutes, seconds:dSeconds} to aDate
set dMonth to dMonth as integer
if dMonth < 10 then set dMonth to "0" & dMonth
if dDay < 10 then set dDay to "0" & dDay
return ((dMonth & "/" & dDay & "/" & dYear & " " & dHours & ":" & dMinutes & ":" & dSeconds) as string)
end stringForDate
Thanks to everyone for contributions and #Zero for sharing the subroutine

Try this.
set filesToProcess to choose folder with prompt "Select folders:" with multiple selections allowed
repeat with thisFile in filesToProcess
tell application "Finder"
try
set theFileDate to (creation date of (first file in folder thisFile whose name ends with "low_r.pdf"))
set formattedCreationDate to (word 2 of short date string of theFileDate & "/" & word 1 of short date string of theFileDate & "/" & word 3 of short date string of theFileDate) & space & time string of theFileDate
--need to flip dd/mm/yyyy to be mm/dd/yyyy Ues this line -->>set formattedCreationDate to short date string of theFileDate & space & time string of theFileDate <<-- instead if your country's date format is already mm/dd/yyyy
my doCommand(formattedCreationDate, thisFile)
on error fileNotFound
set label index of thisFile to 2
display dialog fileNotFound
end try
end tell
end repeat
on doCommand(formattedCreationDate, thisFile)
do shell script "SetFile -d " & (quoted form of formattedCreationDate) & " " & quoted form of (POSIX path of thisFile)
end doCommand

Related

Export Apple photos library for importing it elsewhere

I intented to export all my photos from Mac to any other environment and this suggestion finally provided the base to solve this with applescript. That way the photos are always scaled (getting bigger than the original) but at least it works.
I know it's long but as I struggled that long with this problem, so I post the whole working solution below as an answer. Maybe someone has a better suggestion. I have refused to reverse engineer the contents in sqlite tables Photos is using, as this just may change with the next version.
Problems are various
There is no guarantee how Photos walks through the albums and folders. And as it sometimes just stops working, you have to guarantee some order, or you will never finish. So I introduced a way to start at a particular album at a particular photo. The order within the album seems to be stable. The log output written shows the unique ids of album and photo (as names may not be unique) to be able to restart it at this point. Most of the time the second attempt just works.
I did not find a way to store photos in order, so I created one single directory for each photo and stored each photo in a separate directory, so I can reimport them in order. Problem is that Photos always uses the original file name and just counts upwards if the name exists already. Using different cameras just makes it worse.
All attributes I wrote into a text file per photo, so I can reimport them later.
Error handling is quite tricky. The photos library sometimes just requests the user to press a button, which makes it hard to script it.
That's unfortunately the best I was able to come up with, it is my 1st applescript. This worked on an old Mac with Sierra and it works on more recent versions with Catalina as well. I'm almost sure the newest version will not complain. I'm still searching for a better solution.
There is little support to run it from inside Apple's script editor, only command line provides all options.
#!/usr/bin/osascript
global startAlbum, startPhoto, match, dummy, match, photoCnt, infoFd
global errorIndicator
on writePhotoAndData(thePath, mediaItem, mediaAlbum)
set ind to "X"
using terms from application "Photos"
set fName to filename of mediaItem
set fId to id of mediaItem
set photoCnt to photoCnt + 1
-- export each media to separate directory -> only chance to keep the order
if dummy then
if infoFd ≠ missing value then
set s to id of mediaAlbum & tab & id of mediaItem & tab & thePath & linefeed as text
write s to infoFd as «class utf8»
end if
else
makeEmptyPosixPath(thePath)
set exportPath to POSIX file thePath
set infoFile to POSIX file (thePath & "/" & "info.txt")
set infoText to "id" & tab & id of mediaItem & linefeed & "file" & tab & filename of mediaItem & linefeed & "album" & tab & name of mediaAlbum & linefeed
if exists name of mediaItem then set infoText to infoText & "name" & tab & name of mediaItem & linefeed
if exists description of mediaItem then set infoText to infoText & "desc" & tab & description of mediaItem & linefeed
if exists date of mediaItem then
set d to date of mediaItem
set infoText to infoText & "date" & tab & short date string of d & space & time string of d & linefeed
end if
if exists altitude of mediaItem then set infoText to infoText & "alt" & tab & altitude of mediaItem & linefeed
if exists location of mediaItem then set infoText to infoText & "location" & tab & location of mediaItem & linefeed
if exists keywords of mediaItem then
tell mediaItem to set myKeywords to keywords
repeat with keyword in myKeywords
set infoText to infoText & "keyword" & tab & keyword & linefeed
end repeat
end if
set fd to open for access infoFile with write permission
set eof fd to 0 -- of fd?
write infoText to fd starting at eof as «class utf8»
close access fd
try
tell mediaAlbum
--Not sure whether this does anything, so removed
--set settings to "JPEG - Original Size"
export {mediaItem} to (exportPath as alias)
end tell
set errorIndicator to 0
on error errStr number errNum
if errNum = -1712 then --timeout
set ind to "E"
set errorIndicator to errorIndicator + 1
if errorIndicator >= 3 then
error "3 errors in a row - exiting"
end if
else
error errStr number errNum
end if
end try
end if
log ind & tab & photoCnt & tab & id of mediaAlbum & tab & id of mediaItem & tab & name of mediaAlbum & tab & filename of mediaItem
end using terms from
end writePhotoAndData
on walkAlbum(theAlbum, thePath)
if match = 0 then
if id of theAlbum = startAlbum then
set match to 1
if startPhoto is missing value then
set match to 2
end if
else
return
end if
else if match = 1 then
if id of theAlbum is not equal to startAlbum then
set match to 3
end if
end if
set photoNum to 0
using terms from application "Photos"
set albumPath to thePath & name of theAlbum & "/"
repeat with mediaItem in media items of theAlbum
set photoNum to photoNum + 1
if match = 1 then
if id of mediaItem = startPhoto then
set match to 2
end if
else if match = 2 then
set match to 3 --photo after the photo chosen
end if
if match = 3 then
writePhotoAndData(albumPath & photoNum, mediaItem, theAlbum)
end if
end repeat
end using terms from
end walkAlbum
on walkFolder(theFolder, thePath)
using terms from application "Photos"
repeat with containedFolder in folders of theFolder
walkFolder(containedFolder, thePath & name of containedFolder & "/")
end repeat
repeat with containedAlbum in albums of theFolder
walkAlbum(containedAlbum, thePath)
end repeat
end using terms from
end walkFolder
on makePosixPath(tPath)
do shell script "mkdir -p " & quoted form of tPath
end makePosixPath
on makeEmptyPosixPath(tPath)
do shell script "rm -rf " & quoted form of tPath & " && mkdir -p " & quoted form of tPath
end makeEmptyPosixPath
on makeFolder(tPath)
do shell script "mkdir -p " & quoted form of POSIX path of tPath
end makeFolder
on walkFile(fileName, fileOffset as integer)
set thisOffset to 0
set saveDelim to text item delimiters of AppleScript
set walkFd to open for access POSIX file fileName
set rawLine to read walkFd before linefeed as «class utf8»
repeat
set thisOffset to thisOffset + 1
if fileOffset = 0 or thisOffset ≥ fileOffset then
set thisLine to rawLine as text
set text item delimiters of AppleScript to tab
set splitLine to text items of thisLine
set text item delimiters of AppleScript to saveDelim
set albumIdString to item 1 of splitLine
set photoIdString to item 2 of splitLine
set pathString to item 3 of splitLine
tell application "Photos"
set thisAlbum to album id albumIdString
set thisMedia to media item id photoIdString
end tell
writePhotoAndData(pathString, thisMedia, thisAlbum)
log "O" & tab & thisOffset
end if
try
set rawLine to read walkFd before linefeed as «class utf8»
on error errTxt number errNum
if errNum = -39 then --end of file
exit repeat
else
error "Error reading inputfile: " & errTxt
end if
end try
end repeat
end walkFile
on run (args)
set caller to class of args as string
set errorIndicator to 0
set destPath to POSIX path of (get path to home folder) & "export/photos/"
set photoCnt to 0
set startAlbum to missing value
set startPhoto to missing value
set match to 3
set dummy to false
set walkFileName to missing value
set walkFileOffset to 0
set infoFd to missing value
set infoFileName to missing value
set chooseDestinationFolder to "Select start folder (defaults to " & destPath & ")"
set chooseStart to "Give start album and photo"
set chooseDryRun to "dry-run"
if caller = "script" then
log "Running in ScriptEditor:" & name of me
set options to choose from list {chooseDestinationFolder, chooseStart, chooseDryRun} with title "Configure run" with prompt "Select options" with multiple selections allowed and empty selection allowed
if options contains chooseDryRun then set dummy to true
if options contains chooseDestinationFolder then
try
set destFolder to choose folder with prompt "Choose export directory or cancel for default location" default location (get path to home folder as alias)
set destPath to POSIX path of destFolder
end try
end if
if options contains chooseStart then
set res to display dialog "Enter Id of album to start" default answer "" buttons {"OK"} default button 1
if length of text returned of res > 0 then
set startAlbum to text returned of res
set match to 0
end if
if match = 0 then
set res to display dialog "Enter id of photo to resume after (leave empty to start with album)" default answer "" buttons {"OK"} default button 1
if length of text returned of res > 0 then
set startPhoto to text returned of res
end if
end if
end if
else if caller = "list" then
log "Running on the command line:" & name of me
set cnt to 1
repeat while cnt ≤ length of args
if item cnt of args = "-t" then
set cnt to (cnt + 1)
set destPath to item cnt of args
set cnt to (cnt + 1)
else if item cnt of args = "-a" then
set match to 0
set cnt to (cnt + 1)
set startAlbum to item cnt of args
else if item cnt of args = "-p" then
set cnt to (cnt + 1)
set startPhoto to item cnt of args
else if item cnt of args = "-h" then
return name of me & " [-t target path] [-a start album id] [-a start photo id] [-d] [-i info file path]" & linefeed ¬
& name of me & "[-t target path] -f info file [-o offset]" & linefeed ¬
& name of me & " -h .. this help"
else if item cnt of args = "-d" then
set dummy to true
else if item cnt of args = "-i" then
set cnt to (cnt + 1)
set infoFileName to item cnt of args
else if item cnt of args = "-f" then
set cnt to (cnt + 1)
set walkFileName to item cnt of args
else if item cnt of args = "-o" then
set cnt to cnt + 1
set walkFileOffset to item cnt of args
else
error "Invalid option:" & item cnt of args & " - use -h for help"
end if
set cnt to (cnt + 1)
end repeat
end if
set mySettings to "Destination directory:" & destPath
if startAlbum is not missing value then set mySettings to mySettings & linefeed & tab & "Start album id:" & tab & startAlbum
if startPhoto is not missing value then set mySettings to mySettings & linefeed & tab & "Start photo id:" & tab & startPhoto
if infoFileName ≠ missing value then
set mySettings to mySettings & linefeed & tab & "Write file '" & infoFileName & "'" & linefeed
set dummy to true
end if
if dummy then set mySettings to mySettings & linefeed & tab & "Dry run only"
if caller = "script" then
display dialog mySettings with title "Start exporting?" with icon note
else if caller = "list" then
log mySettings
else
error "Internal error - caller interface unknown"
end if
if infoFileName ≠ missing value then
set infoFd to open for access POSIX file infoFileName with write permission
set eof infoFd to 1
end if
if walkFileName ≠ missing value then
walkFile(walkFileName, walkFileOffset)
else
walkFolder(application "Photos", destPath)
end if
if infoFd ≠ missing value then close access infoFd
return "Done!"
end run

Renaming PDF File with Apple Script

I'm trying to rename a finder item called "Invoice Template.pdf" when it is added to my folder with Automator. However, every time the script runs, I get Finder got an error: Can’t set file "Invoice Template.pdf" to "Invoice 11.08.2021.pdf". Any ideas why?
tell application "Finder"
set dateObj to (current date)
set theMonth to text -1 thru -2 of ("0" & (month of dateObj as number))
set theDay to text -1 thru -2 of ("0" & day of dateObj)
set theYear to year of dateObj
set dateStamp to "" & theMonth & "." & theDay & "." & theYear
set theFile to "DBF Invoice Template.pdf"
set theName to "Invoice"
set the name of file theFile to theName & " " & dateStamp & ".pdf"
end tell
set dateObj to (current date)
set theMonth to text -1 thru -2 of ("0" & (month of dateObj as number))
set theDay to text -1 thru -2 of ("0" & day of dateObj)
set theYear to year of dateObj
set dateStamp to "" & theMonth & "." & theDay & "." & theYear
set theFileHFS to (choose file of type "com.adobe.pdf") as text
set theName to "Invoice"
tell application "Finder"
set the name of file theFileHFS to theName & " " & dateStamp & ".pdf"
end tell
You need to tell Finder where the file is:
property myFolder: "/Users/MYUSERNAME/Dropbox/Invoices" as POSIX file
tell application "Finder"
...
set theFile to "DBF Invoice Template.pdf"
set theName to "Invoice"
set the name of file theFile of folder myFolder to theName & " " & dateStamp & ".pdf"
end tell

Export from Mac Photos app to folders by date ("YYYY-MM-DD")

I'm attempting to get all my pictures out of the iPhotos and Photos app.
I found this script to export all the pictures from iPhotos. But it doesn't work when i change it to use the Photos app.
set destination to quoted form of POSIX path of (path to pictures folder)
tell application "iPhoto"
repeat with i in (get selection)
tell i to my copyPhoto(date, image path, title, destination)
end repeat
end tell
on copyPhoto(d, p, t, dest) -- the name of the file is the title of the photo in iPhoto, date format for folder name = 2014-09-25
tell d to set d to "" & its year & "-" & text -2 thru -1 of ("0" & ((its month) as integer)) & "-" & text -2 thru -1 of ("0" & its day)
try -- create folder if neccessary, check to not overwrite any files in the subfolder, copy the file, rename with the title
do shell script "f=" & d & ";t=" & (quoted form of t) & ";tFile=" & (quoted form of p) & "; e=${tFile##*.}; cd " & dest & ";mkdir -p \"$f\"; while [ -e \"$f/$t.$e\" ];do t=\"$t _\";done; cp -a \"$tFile\" \"$f/$t.$e\""
end try
end copyPhoto
(from https://discussions.apple.com/thread/6565154?start=0&tstart=0)
Would someone be able to help me figure out how to do this with the Photos app?
The format that the script uses it perfect, pictures organized by folder:
2014-12-30
2015-01-01
2015-01-02
...
THANKS!!!!
Vadian is right, no "image path" in Photos (thanks Apple !), so must use Export. see script bellow which does this, also formatting date and creating folder if required.
set TopFolder to (path to desktop folder from user domain) as string -- your main destination folder
tell application "Photos"
repeat with aPhoto in (get selection)
set SName to filename of aPhoto
set theDate to date of aPhoto
-- convert date to string yyyy-mm-dd
set SY to (year of theDate) as string
set SM to text -2 thru -1 of ("0" & ((month of theDate) as integer))
set SD to text -2 thru -1 of ("0" & ((day of theDate) as string))
set DestFolder to SY & "-" & SM & "-" & SD -- DestFolder = folder "date"
-- check if folder DestFolder exists : if not creation
tell application "Finder"
if not (folder (TopFolder & DestFolder) exists) then
make new folder in TopFolder with properties {name:DestFolder}
end if
end tell
-- you may have to add a check if file (TopFolder & DestFolder & SName) already exists
-- and take appropriate action (add index, add word "copy",...)
export {aPhoto} to (TopFolder & DestFolder)
end repeat
end tell
During tests, I discovered that Photos is much slower than iPhoto. Just to get Date or filename property it takes time ! Also "Export" does. the script itself could be optimized using shell functions for date formatting or folder check/creation (I am not shell expert), but the speed bottleneck remains Photos !

AppleScript error: 'Expected "else", etc. but found unknown token'

I'm new to AppleScript. The editor isn't giving me syntax highlighting so I'm a bit stuck with this error.
set exportPath to path to documents folder as text
with timeout of (30 * 60) seconds
tell application "Evernote"
repeat with nb in every notebook of application "Evernote"
set theName to the name of nb
set matches to find notes "notebook:" & "\"" & theName & "\""
set f to exportPath & theName & ".enex"
export matches to f
if (count of matches) > 0 then
set p to POSIX path of f
do shell script "/usr/bin/gzip -f " & quoted form of p
end if
end repeat
end tell
end timeout
When I click OK on the error the cursor position is changed to before the end in the end if line.
You have some weird, unknown character just before end if.
Take that line out and re-type it and it will work.
set exportPath to path to documents folder as text
with timeout of (30 * 60) seconds
tell application "Evernote"
repeat with nb in every notebook of application "Evernote"
set theName to the name of nb
set matches to find notes "notebook:" & "\"" & theName & "\""
set f to exportPath & theName & ".enex"
export matches to f
if (count of matches) > 0 then
set p to POSIX path of f
do shell script "/usr/bin/gzip -f " & quoted form of p
end if
end repeat
end tell
end timeout

Applescript: Passing track metadata from text file to broadcast streaming app

I know virtually nothing about AppleScript and could do with some help.
While running, my broadcast playout system (MegaSeg) writes details of the track currently playing to a textfile called "NowPlaying" which contains solely the following contents, each on its own line and without square brackets:
Title: [title]
Artist: [artist]
Album: [album]
Time: [time in some format or other]
I want to pass this to my broadcast streamer LadioCast, which can be addressed via AppleScript, so that it sends info on what is playing to the streaming server.
MegaSeg doesn't support Applescript calls like 'tell application "MegaSeg"... set trackName to name of current track' so I can't do it that way. I have no idea about how to do this.
If we imagine that I was able to grab that info, this is what I would do with it:
set lastName to ""
set lastArtist to ""
set lastAlbum to ""
repeat
** insert missing file reading section here
** in the following, "title", "artist" and "album" are from the text file **
set trackName to title
set trackArtist to artist
set trackAlbum to album
** end of missing section
if trackName is not lastName and trackArtist is not lastArtist and trackAlbum is not lastAlbum then
set lastName to trackName
set lastArtist to trackArtist
set lastAlbum to trackAlbum
tell application "LadioCast"
set metadata song to trackName & " – " & trackArtist & " – " & trackAlbum
end tell
end if
delay 15
end repeat
Thanks in advance.
--Richard E
===
I tried the suggestions from #DigiMonk and they were very helpful, but not all of them worked. First, the file is in a specific location and not on the desktop; second, I could not get 'trim_line' to work at all - I got "script does not understand trim_line message". However the text in the file seems to be already trimmed.
The script below nearly works; when run from the Applescript Editor it does seem to get the Title, Artist and Album into the variables. However when I try running it from LadioCast I get an EOF -39 error. More importantly, as soon as I run this, MegaSeg stops updating the file, forever. I am presumably locking the file to read from it and stopping MegaSeg writing to it. How do I avoid this?
set lastName to ""
set lastArtist to ""
set lastAlbum to ""
set lastTime to ""
set trackName to ""
set trackArtist to ""
set trackAlbum to ""
set sourcePath to ""
repeat
set sourcePath to open for access file "Library:MegaSeg User Data:Logs:Logs for MegaSeg System (4):NowPlaying"
set thisText to read sourcePath as text
close access file "Library:MegaSeg User Data:Logs:Logs for MegaSeg System (4):NowPlaying"
set the paragraphList to every paragraph of thisText
repeat with i from 1 to number of items in paragraphList
set thisItem to item i of paragraphList
if thisItem starts with "Title:" then
set x to the offset of "Title:" in thisItem
set trackName to (text (x + 6) thru -1 of thisItem)
else if thisItem starts with "Artist:" then
set x to the offset of "Artist:" in thisItem
set trackArtist to (text (x + 7) thru -1 of thisItem)
else if thisItem starts with "Album:" then
set x to the offset of "Album:" in thisItem
set trackAlbum to (text (x + 6) thru -1 of thisItem)
end if
end repeat
if trackName is not lastName and trackArtist is not lastArtist and trackAlbum is not lastAlbum then
set lastName to trackName
set lastArtist to trackArtist
set lastAlbum to trackAlbum
tell application "LadioCast"
set metadata song to trackName & " – " & trackArtist & " – " & trackAlbum
end tell
end if
delay 15
end repeat
May be this helps: (feed sourcePath with the path to your NowPlaying.txt file)
set sourcePath to (path to desktop) & "NowPlaying.txt" as text
set thisText to my readFile(sourcePath)
set the paragraphList to every paragraph of thisText
set lastName to ""
set lastArtist to ""
set lastAlbum to ""
set lastTime to ""
repeat with i from 1 to number of items in paragraphList
set thisItem to item i of paragraphList
--log thisItem
if thisItem starts with "Title:" then
set x to the offset of "Title:" in thisItem
set y to (text (x + 6) thru -1 of thisItem)
set lastName to my trim_line(y, " ", 2)
else if thisItem starts with "Artist:" then
set x to the offset of "Artist:" in thisItem
set y to (text (x + 7) thru -1 of thisItem)
set lastArtist to my trim_line(y, " ", 2)
else if thisItem starts with "Album:" then
set x to the offset of "Album:" in thisItem
set y to (text (x + 6) thru -1 of thisItem)
set lastAlbum to my trim_line(y, " ", 2)
else if thisItem starts with "Time:" then
set x to the offset of "Time:" in thisItem
set y to (text (x + 5) thru -1 of thisItem)
set lastTime to my trim_line(y, " ", 2)
end if
end repeat
log "lastName = '" & lastName & "'"
log "lastArtist = '" & lastArtist & "'"
log "lastAlbum = '" & lastAlbum & "'"
on readFile(thisFile)
set thisFile to thisFile as text
if thisFile is "" then return ""
try
set fi to open for access file the thisFile
set myData to read fi as text
close access file the thisFile
return myData
on error
try
close access file the thisFile
return ""
end try
end try
end readFile
on trim_line(this_text, trim_chars, trim_indicator)
-- 0 = beginning, 1 = end, 2 = both
set x to the length of the trim_chars
-- TRIM BEGINNING
if the trim_indicator is in {0, 2} then
repeat while this_text begins with the trim_chars
try
set this_text to characters (x + 1) thru -1 of this_text as string
on error
-- the text contains nothing but the trim characters
return ""
end try
end repeat
end if
-- TRIM ENDING
if the trim_indicator is in {1, 2} then
repeat while this_text ends with the trim_chars
try
set this_text to characters 1 thru -(x + 1) of this_text as string
on error
-- the text contains nothing but the trim characters
return ""
end try
end repeat
end if
return this_text
end trim_line

Resources