Applescript to sort files into folder based on British financial year - macos

I'm looking for way to move files based on UK financial year (runs from 6th April -5th April).
Files are named in pattern as
2014-08-26_Asda_lunch.pdf
2016-03-20_Tesco_sationary.pdf
The File needs to be moved to folders which are named, and so on
FY 2014-15
FY 2015-16
Just wondering if applescript/ shell script or automator action would help to achieve this. Also interface with hazel wud be even better
Thanks in advance
I have tried to modify the script
My first aim is get month right, then wud try dates;
the Output for Script
File 2019-07-26_Tesco_stationary -> FY 2020 ( expected FY 2019-20)
File 2019-03-15_Sainsbury -> FY 2019 ( expected FY 2018-19)
Please advise, also any pointers to add date in sorting wud be helpful
Thank you
set savedDelimiters to AppleScript's text item delimiters
set AppleScript's text item delimiters to {"-"}
tell application "Finder"
set filename to name of theFile
end tell
set expenseYear to (first text item of filename) as number
set expenseMonth to (second text item of filename) as number
set expenseDate to (third text item of filename) as number
-- Get the last two characters of the Year
set AppleScript's text item delimiters to savedDelimiters
set lastTwoCharactersOfYear to (characters 3 thru 4 of (expenseYear as text))
set RoundedExpYear to (lastTwoCharactersOfYear as text) as number
if expenseMonth ≥ 4 then
set LongString to expenseYear
set ShortString to RoundedExpYear + 1
else
set LongString to expenseYear - 1
set ShortString to RoundedExpYear
end if
set returnText to "FY" & " " & LongString & "-" & ShortString

There are many ways to parse dates but since your format is always the same (yyyy-mm-dd_xxxx) I used the easiest way. In script below the handler GetFY returns directly the format you're looking for "FY YYYY-YYYY" when you give parameter your file name:
set Fname to "2014-03-05_xxxx" -- value to test
set myfolder to GetFy(Fname)
log "myfolder=" & myfolder
on GetFy(Fname) -- return FY-(FY+1) based on Fname as YYYY-MM-DD_xxxxxx
set myear to (text 1 thru 4 of Fname) as integer
set mmonth to (text 6 thru 7 of Fname) as integer
set mday to (text 9 thru 10 of Fname) as integer
if mmonth < 4 then set Fy to myear - 1
if mmonth = 4 then set Fy to myear - ((mday ≤ 5) as integer)
if mmonth > 4 then set Fy to myear
return "FY " & Fy & "-" & (Fy + 1)
end GetFy

Related

How to convert an Apple Mail received date, month, to a string or number?

I am doing a simple step through messages in my inbox. I want to write out the date to a text file. The date is coming through as "Sunday April 2, 2017 at 12:12:12:. All I want to do is convert this to "4/2/17". I keep getting "April" as the month and cannot coerce it to "4" MM format.
tell application "Mail"
repeat with aMessage in messages of inbox
set sSender to (get aMessage's sender)
set recDate to (date received of aMessage)
set sMonth to month of recDate
set sDate to day of recDate & "/" & month of recDate & "/" & year of recDate
end tell
I have tried using a shell echo, or coercing sMonth to a string or integer. No matter what I keep getting "April" instead of a number and "rich text" instead of string.
I don't mind using a shell command, but I am not good with Linux and I do not want to convert the current date (I need to use the date of a past email). I know I must be missing something simple.
First of all to avoid the terminology confusion (rich text instead of text) move the code to create the date string into a handler.
To get 4 from the month just coerce it to integer, then coerce all components to text. To strip the 20 from the year just use only the last two characters.
tell application "Mail"
repeat with aMessage in messages of inbox
set sSender to (get aMessage's sender)
set sDate to my dateString(date received of aMessage)
end repeat
end tell
on dateString(theDate)
tell theDate to set {yr, mn, dy} to {year as text, its month as integer as text, day as text}
return mn & "/" & dy & "/" & text -2 thru -1 of yr -- 4/27/18
end dateString
If you want to add leading zeros to the day and month components use another handler to pad the values
on dateString(theDate)
tell theDate to set {yr, mn, dy} to {year as text, its month as integer as text, day as text}
return pad(mn) & "/" & pad(dy) & "/" & text -2 thru -1 of yr -- 04/27/18
end dateString
on pad(v)
return text -2 thru -1 of ("0" & v)
end pad
This works for me using the latest version of macOS High Sierra
property theShortDate : missing value
tell application "Mail"
repeat with aMessage in messages of inbox
set sSender to (get aMessage's sender)
set recDate to (date received of aMessage) as string
my shortDate(recDate)
log "This E-Mail Was Sent From: " & sSender & " " & "on" & " " & theShortDate
end repeat
end tell
on shortDate(recDate)
set AppleScript's text item delimiters to ","
set theLongDate to recDate
set currentMonth to (word 1 of text item 2 of theLongDate)
set currentDay to (word 2 of text item 2 of theLongDate)
set currentYear to (word 1 of text item 3 of theLongDate)
set monthList to {January, February, March, April, May, June, July, August, September, October, November, December}
repeat with x from 1 to 12
if currentMonth = ((item x of monthList) as string) then
set theRequestNumber to (text -2 thru -1 of ("0" & x))
exit repeat
end if
end repeat
set currentMonth to theRequestNumber
set currentDay to (text -2 thru -1 of ("0" & currentDay))
set theShortDate to (currentMonth & "/" & currentDay & "/" & currentYear) as string
end shortDate

Get date added of Finder items in Applescript

I can get files by date modified using this bit of code:
get (files of entire contents of folder "Macintosh HD:General Music:05 Reggae:" whose modification date is less than ((current date)) - modDate * days)
but I can't seem to get their date added (nor is it listed in Applescript dictionary for Finder that I can see). This is weird, 'cause I can do a smart folder that uses this property.
Any idea on how to get files who were added within 15 days? Otherwise I'm doing loads of weird stuff with GUI at the moment and I'd like to automate it further.
Thanks
Tardy
You can search Spotlight's metadata with the mdfind command, use the kMDItemDateAdded key:
set _15daysAgo to -15 * days -- number of seconds
set tFolder to quoted form of POSIX path of "Macintosh HD:General Music:05 Reggae:"
-- find files, not folders
do shell script "mdfind -onlyin " & tFolder & " 'kMDItemDateAdded>$time.now(" & _15daysAgo & ") && ! kMDItemContentType == public.folder'"
set tFiles to paragraphs of the result
repeat with i in tFiles
tell i to set contents to i as POSIX file as alias
end repeat
tFiles -- list of files who were added within 15 days
Or, use the methods of the NSFileManager Class to get the NSURLAddedToDirectoryDateKey of the files (require Yosemite or El Capitan),
Here's the AppleScript:
set _15daysAgo to -15 * days -- number of seconds
set f to POSIX path of "Macintosh HD:General Music:05 Reggae:"
do shell script "/usr/bin/python -c 'import sys; from Foundation import NSFileManager, NSURL, NSDate, NSDirectoryEnumerationSkipsHiddenFiles
def procFolder(tDir):
p = dfM.contentsOfDirectoryAtURL_includingPropertiesForKeys_options_error_(tDir, myKeys, NSDirectoryEnumerationSkipsHiddenFiles, None)[0]
for f in p:
myDict, error=f.resourceValuesForKeys_error_(myKeys, None)
if error is None:
if (myDict.get(\"NSURLIsDirectoryKey\")): procFolder(f)
elif (myDict.get(\"NSURLAddedToDirectoryDateKey\").compare_(d) == 1):
print f.path().encode(\"utf8\")
fold=NSURL.fileURLWithPath_isDirectory_(sys.argv[1].decode(\"utf8\"), True)
dfM=NSFileManager.defaultManager()
d=NSDate.dateWithTimeIntervalSinceNow_(" & _15daysAgo & ")
myKeys=[\"NSURLIsDirectoryKey\", \"NSURLAddedToDirectoryDateKey\"]
procFolder(fold)' " & f
set tFiles to paragraphs of the result
repeat with i in tFiles
tell i to set contents to i as POSIX file as alias
end repeat
tFiles -- list of files who were added within 15 days

Cannot pass handler parameter to code. Newbie

Background: I am trying to pass caller information from a telephony application (Phone Amego) to my Samsung tv using its AllShare feature. In order to do so I have to send a soap message with the caller information. Phone Amego provides an easy way to assign an applescript to call events. But, I have no programming experience whatsoever!
Sofar I have succeeded in making a script which reads a soap message, updates the required fields and sends it to my tv. Perfect, at least the result, the code may not be perfect but it works. Here is the code.
set callerID_string to "John Doe : 1-917-123-4567"
set AppleScript's text item delimiters to {":"}
set pieces to text items of callerID_string
set callerID_name to item 1 of pieces
set callerID_number to item 2 of pieces
set AppleScript's text item delimiters to {""}
set myDate to do shell script "date '+%d.%m.%Y'"
set myTime to do shell script "date '+%T'"
set total_Length to (length of callerID_name) + (length of callerID_number) + 780
set search_strings to {"Content-Length: 796", "2013-01-01", "00:00:00", "Mike", "777-777-7777"}
set replace_strings to {"Content-Length:" & total_Length, myDate, myTime, callerID_name, callerID_number}
tell application "Finder"
set theFile to alias "Macintosh HD:Users:Marc:Desktop:IncCallMBsTemplate.txt"
open for access theFile
set fileRef to open for access (theFile as alias)
set fileContents to (read fileRef)
close access theFile
end tell
set the clipboard to fileContents
repeat with i from 1 to (count search_strings)
set the_string to the clipboard
set the_string to my snr(the_string, item i of search_strings, item i of replace_strings)
end repeat
on snr(the_string, search_string, replace_string)
tell (a reference to my text item delimiters)
set {old_atid, contents} to {contents, search_string}
set {the_string, contents} to {the_string's text items, replace_string}
set {the_string, contents} to {"" & the_string, old_atid}
end tell
set the clipboard to the_string
-- Create a file handler for the file to write to.
set myFile to (open for access alias "Macintosh HD:Users:Marc:Desktop:Test.txt" with write permission)
try
-- Delete current contents of the file
set eof myFile to 0
-- Write to file
write the_string to myFile as «class utf8»
end try
-- Close the file
close access myFile
end snr
set cmd to "/Usr/bin/nc 10.0.1.7 52235 < /Users/Marc/Desktop/Test.txt"
do shell script cmd
Problem: In the script above I have set a value to the variable callerID_string, but I should obtain it from Phone Amego through the handler call_from(callerID_string). But whatever I try, I cannot pass that callerID_string to my code. It consists of 2 parts namely the caller's name and number. The code should start like:
on call_from(callerID_string)
Any help would be highly appreciated.
I assume your script is running with the other app at the same time and it needs that handler and therefore a little re-designing so we can call the (former main) code as a subroutine.
I'm not sure if I understood the situation correctly but here it is anyway:
I added the on call_from... handler which calls the rest of the code as subroutine (myAction).
First commented line in code can be uncommented and used to test-run it with AppleScript Editor. Remove the line when not needed anymore.
testFilePath is a property and globally visible. Also, I changed the hardcoded file-path-stuff so it finds the path to the desktop.
property testFilePath : ""
-- my myAction("John Doe : 1-917-123-4567")
on call_from(callerID_string)
my myAction(callerID_string)
end call_from
on myAction(CIS)
if CIS is "" then
tell me to activate
display dialog "Caller ID is empty." buttons {"Quit"} default button 1 with icon 0
return
end if
set pathToDesktop to (path to desktop) as text
set testFilePath to pathToDesktop & "Test.txt"
set callerID_string to CIS -- "John Doe : 1-917-123-4567"
set lastTextItemDelimeter to AppleScript's text item delimiters
set AppleScript's text item delimiters to {" : "}
set pieces to text items of callerID_string
set callerID_name to item 1 of pieces
set callerID_number to item 2 of pieces
set AppleScript's text item delimiters to {""} -- or lastTextItemDelimeter if you want to change it back to last
set myDate to do shell script "date '+%d.%m.%Y'"
set myTime to do shell script "date '+%T'"
set total_Length to (length of callerID_name) + (length of callerID_number) + 780
set search_strings to {"Content-Length: 796", "2013-01-01", "00:00:00", "Mike", "777-777-7777"}
set replace_strings to {"Content-Length:" & total_Length, myDate, myTime, callerID_name, callerID_number}
set templateFile to pathToDesktop & "IncCallMBsTemplate.txt"
tell application "Finder"
set theFile to templateFile as alias -- Macintosh HD:Users:Marc:Desktop:IncCallMBsTemplate.txt"
open for access theFile
set fileRef to open for access (theFile as alias)
set fileContents to (read fileRef)
close access theFile
end tell
set the clipboard to fileContents
repeat with i from 1 to (count search_strings)
set the_string to the clipboard
set the_string to my snr(the_string, item i of search_strings, item i of replace_strings)
end repeat
set cmd to "/usr/bin/nc 10.0.1.7 52235 < " & quoted form of (POSIX path of testFilePath)
do shell script cmd
end myAction
on snr(the_string, search_string, replace_string)
tell (a reference to my text item delimiters)
set {old_atid, contents} to {contents, search_string}
set {the_string, contents} to {the_string's text items, replace_string}
set {the_string, contents} to {"" & the_string, old_atid}
end tell
set the clipboard to the_string
-- Create a file handler for the file to write to.
set myFile to (open for access (testFilePath as alias) with write permission)
try
-- Delete current contents of the file
set eof myFile to 0
-- Write to file
write the_string to myFile as «class utf8»
on error the error_message number the error_number
-- display dialog "Error: " & the error_number & ". " & the error_message buttons {"Cancel"} default button 1
log "Error: " & the error_number & ". " & the error_message
end try
-- Close the file
close access myFile
end snr

Applescript to repeat complete script for files in a folder

I have managed to get all this code together now and just need the last step to work. Any help would be greatly appreciated.
I have setup this script to open an .xlsx file in a folder, change the date, save it then PDF to another folder. It then creates a mail by looking up the client code (found in the excel file) to subsequently look for this code in a Database.xlsx file and return the e-mail address of the client and add it to the "To" field in mail. It then attaches the newly created PDF to this mail and I can just click and send.
The script stops after the first .xlsx file has been opened, just so I can check the details is correct before it PDF's and creates the mail.
My question is: How do I get this process to repeat for each file in the initial folder? I have tried the repeat function, but to no avail.
Any help would be greatly appreciated.
Thank you.
--Complete script for updating invoice, saving (as PDF too in seperate folder) and e-mailing invoices
--Select the first file in a folder and then repeat for the next
set theFolder to POSIX path of (choose folder with prompt "Choose Folder containing .xlsx invoices")
set theFolderList to list folder theFolder without invisibles
repeat with x from 1 to count of theFolderList
set theFile to theFolder & item x of theFolderList
set theNewFile to theFolder & theFile
tell application "Microsoft Excel"
activate
open theFile
set ActiveClientCode to value of range ("B1")
end tell
--Change date of one cell to date of next month
tell application "Microsoft Excel"
activate
open "/Users/pienaar0/Documents/AdminAssist/" & ActiveClientCode & ".xlsx"
set d to value of cell ("A1")
set d to my MonthAdd(d)
set value of cell ("A1") to d
end tell
on MonthAdd(d)
set m to ((month of d as integer) + 1)
set ddd to day of d
if m > 12 then
set m to m - 12
set year of d to (year of d) + 1
end if
if {m} is in {4, 6, 9, 11} and ddd = 31 then --AppleScript treats "Apr 31" as May 1,
set day of d to 30
end if
set month of d to m
if m = 2 and month of d as integer = 3 then --AppleScript treats "Feb 31" as Mar 3,
set day of d to 1 -- Mar 1
set d to d - (1 * days) -- last day of Feb
end if
return d
end MonthAdd
property dialog_timeout : 36000
display dialog "Make sure the invoice is correct before clicking OK" buttons {"OK"} giving up after dialog_timeout
set the user_choice to the button returned of the result
--Save document and PDF
tell application "Microsoft Excel"
save active workbook
save active workbook in "Macintosh HD:Users:pienaar0:Documents:AdminAssistPDF:" & ActiveClientCode & ".pdf" as PDF file format
end tell
--Find e-mail address, and Name in Database (Check filepath and ranges)
tell application "Microsoft Excel"
open "Users/pienaar0/Documents/Database.xlsx"
set searchRange to range ("D2:D5")
set foundRange to find searchRange what ActiveClientCode with match case
set fRow to first row index of foundRange
set ClientEmail to value of range ("C" & fRow as text)
set ClientFirstname to value of range ("A" & fRow as text)
(* do something with the foundRange *)
end tell
--Create e-mail
tell application "Mail"
set theMessage to make new outgoing message with properties {visible:true, subject:"Your monthly invoice", content:"Dear " & ClientFirstname & ",
I trust this mail finds you well?
Please find attached your monthly invoice for your immediate consideration.
Regards,
AdminAssist
"}
set message signature of theMessage to signature "Replies & Forwards"
delay 1
tell content of theMessage
make new attachment with properties {file name:"/Users/pienaar0/Documents/AdminAssist/PDF/" & ActiveClientCode & " Sheet1.pdf"}
tell theMessage
make new to recipient at end of to recipients with properties {address:ClientEmail}
end tell
end tell
end tell
end repeat
You need to move your handler outside of the repeat block:
property dialog_timeout : 36000
--Complete script for updating invoice, saving (as PDF too in seperate folder) and e-mailing invoices
--Select the first file in a folder and then repeat for the next
set theFolder to POSIX path of (choose folder with prompt "Choose Folder containing .xlsx invoices")
tell application "System Events" to set theFolderList to name of every file of folder theFolder whose visible is true
repeat with x from 1 to count of theFolderList
set theFile to theFolder & item x of theFolderList
set theNewFile to theFolder & theFile
tell application "Microsoft Excel"
activate
open theFile
set ActiveClientCode to value of range ("B1")
end tell
--Change date of one cell to date of next month
tell application "Microsoft Excel"
activate
open "/Users/pienaar0/Documents/AdminAssist/" & ActiveClientCode & ".xlsx"
set d to value of cell ("A1")
set d to my MonthAdd(d)
set value of cell ("A1") to d
end tell
display dialog "Make sure the invoice is correct before clicking OK" buttons {"OK"} giving up after dialog_timeout
set the user_choice to the button returned of the result
--Save document and PDF
tell application "Microsoft Excel"
save active workbook
save active workbook in "Macintosh HD:Users:pienaar0:Documents:AdminAssistPDF:" & ActiveClientCode & ".pdf" as PDF file format
end tell
--Find e-mail address, and Name in Database (Check filepath and ranges)
tell application "Microsoft Excel"
open "Users/pienaar0/Documents/Database.xlsx"
set searchRange to range ("D2:D5")
set foundRange to find searchRange what ActiveClientCode with match case
set fRow to first row index of foundRange
set ClientEmail to value of range ("C" & fRow as text)
set ClientFirstname to value of range ("A" & fRow as text)
(* do something with the foundRange *)
end tell
--Create e-mail
tell application "Mail"
set theMessage to make new outgoing message with properties {visible:true, subject:"Your monthly invoice", content:"Dear " & ClientFirstname & ",
I trust this mail finds you well?
Please find attached your monthly invoice for your immediate consideration.
Regards,
AdminAssist
"}
set message signature of theMessage to signature "Replies & Forwards"
delay 1
tell content of theMessage
make new attachment with properties {file name:"/Users/pienaar0/Documents/AdminAssist/PDF/" & ActiveClientCode & " Sheet1.pdf"}
tell theMessage
make new to recipient at end of to recipients with properties {address:ClientEmail}
end tell
end tell
end tell
end repeat
on MonthAdd(d)
set m to ((month of d as integer) + 1)
set ddd to day of d
if m > 12 then
set m to m - 12
set year of d to (year of d) + 1
end if
if {m} is in {4, 6, 9, 11} and ddd = 31 then --AppleScript treats "Apr 31" as May 1,
set day of d to 30
end if
set month of d to m
if m = 2 and month of d as integer = 3 then --AppleScript treats "Feb 31" as Mar 3,
set day of d to 1 -- Mar 1
set d to d - (1 * days) -- last day of Feb
end if
return d
end MonthAdd

Loop Over Video Files in Folder to get video length

I have the following which returns how many seconds a selected video file is.
However I was after a way to just give it the movie folder and for it to then loop through all subdirectories and find all video file types.
Once it has these I would like to list the video length in "1 hour 53 seconds" type format as "7990 seconds" isn't too helpful.
Thanks
set macPath to (choose file) as text
tell application "System Events"
set ts to time scale of movie file macPath
set dur to duration of movie file macPath
set movieTime to dur / ts
end tell
You have several sub-questions involved in your question.
1) How do I get all of the files in a folder, including the sub folders
2) how do I filter that list to only include video files
3) How do I loop through that list of video files and extract information from each and
4) How do I convert seconds into a useable string of words
Normally I would ask that you break it down into those individual questions because it's a large task for someone to write the whole thing for you. However, in this case you're lucky because I had done this before myself... so you can have my script. I put lots of comments in the code to help you learn how it works.
-- I found these extensions for video files here http://www.fileinfo.net/filetypes/video
-- we can check the file extensions of a file against this list to evaluate if it's a video file
set video_ext_list to {"3g2", "3gp", "3gp2", "3gpp", "3mm", "60d", "aep", "ajp", "amv", "asf", "asx", "avb", "avi", "avs", "bik", "bix", "box", "byu", "cvc", "dce", "dif", "dir", "divx", "dv", "dvr-ms", "dxr", "eye", "fcp", "flc", "fli", "flv", "flx", "gl", "grasp", "gvi", "gvp", "ifo", "imovieproject", "ivf", "ivs", "izz", "izzy", "lsf", "lsx", "m1v", "m2v", "m4e", "m4u", "m4v", "mjp", "mkv", "moov", "mov", "movie", "mp4", "mpe", "mpeg", "mpg", "mpv2", "msh", "mswmm", "mvb", "mvc", "nvc", "ogm", "omf", "prproj", "prx", "qt", "qtch", "rm", "rmvb", "rp", "rts", "sbk", "scm", "smil", "smv", "spl", "srt", "ssm", "svi", "swf", "swi", "tivo", "ts", "vdo", "vf", "vfw", "vid", "viewlet", "viv", "vivo", "vob", "vro", "wm", "wmd", "wmv", "wmx", "wvx", "yuv"}
-- get the folder to check
set f to choose folder
-- notice the use of "entire contents" to also go through subfolders of f
-- use a "whose" filter to find only the video files
tell application "Finder"
set vidFiles to (files of entire contents of f whose name extension is in video_ext_list) as alias list
end tell
-- use a repeat loop to loop over a list of something
set vidList to {} -- this is where we store the information as we loop over the files
repeat with aFile in vidFiles
-- get some information from aFile
tell application "System Events"
set vidFile to movie file (aFile as text)
set ts to time scale of vidFile
set dur to duration of vidFile
end tell
-- add the information to the "storage" list we made earlier
set end of vidList to {POSIX path of aFile, secs_to_hms(dur / ts)}
end repeat
return vidList
(*=================== SUBROUTINES ===================*)
-- convert seconds into a string of words
-- the use of "mod" and "div" here makes it easy
-- we also make sure that each value is at least 2 places long to make it look nicer
on secs_to_hms(the_secs)
set timeString to ""
set hr to the_secs div hours
if hr is not 0 then set timeString to timeString & (text -2 thru -1 of ("0" & (hr as text))) & " hours "
set min to the_secs mod hours div minutes
if min is not 0 then set timeString to timeString & (text -2 thru -1 of ("0" & (min as text))) & " minutes "
set sec to the_secs mod minutes div 1
if sec is not 0 then
set fraction to text 2 thru 3 of ((100 + the_secs mod 1 * 100) as text)
set timeString to timeString & (sec as text) & "." & fraction & " seconds"
end if
if timeString ends with space then set timeString to text 1 thru -2 of timeString
return timeString
end secs_to_hms
I came across this post because I wanted to have a log of video files in a folder; something I could import in a spreadsheet, also to calculate the total duration but not only.
The posted script didn't work for me so I ended up importing the folder in Final Cut Pro, doing Batch Export on the folder and than File > Export > Batch List, which resulted in a plain text file I could import in a spreadsheet as the start of a log and to calculate the total duration.
Perhaps this helps others.

Resources