Setting the width of a variable in applescript - applescript

I am trying to write an apple script that sequentially names my TV shows with "S0XEYY" where YY is a two digit number. I have the following:
tell application "iTunes"
set p to selection
set c to count of p's items
set fixed indexing to true
repeat with i from 1 to c
set t to item i of p
try
set the episode number of t to i
set the episode ID of t to "S" & (text returned of a) & "E" & i
set the season number of t to text returned of a
end try
end repeat
However, I need the
(text returned of a)
as well as
i
to be of width 2, padded with a 0. How do I go about doing this?

Here is how I went about it:
if i ≀ 9 then
set the episode ID of t to episode ID of t & "0" & i
else
set the episode ID of t to episode ID of t & i
which I am sure is not the best way to do it, because it assumes no more then 2 characters are needed, but its the best solution I have, which works for this application because TV seasons never (that I have seen) exceed 20-30 episodes.

Related

Re. Outlook 16.50 , how can I get the event date of a single occurrence of a calendar events series using Applescript?

The code extracts a pre-selected event properties (attendees, subject, start time etc). All works fine, but I noticed that with recurring meetings a selected event always has the start property of the first meeting instance of the series (hope this makes sense!).
As per the dictionary: recurrence id (date, r/o) : The recurrence id of an event (the date at which the recurring event occurs).
When I use it as per the enclosed it doesn't work - reason is "recurrence id" always returns "missing value". No other property seems appropriate..
Any ideas? - it's driving me nuts!
tell application "Microsoft Outlook"
activate
if view of the first main window is equal to calendar view then
set calendarEvent to selection -- grabbing the selected event
-- if there are no events selected, warn the user and then quit
if calendarEvent is missing value then
display dialog "Please select a calendar event first and then run this script! πŸ˜€" with icon 1
return
end if
set eventTitle to subject of calendarEvent -- grabbing the event title
set the_properties to properties of calendarEvent
if is recurring of the_properties then
set eventStart to (recurrence id of the_properties)
else
set eventStart to start time of calendarEvent
end if
set startDate to date string of eventStart
set startTime to time string of eventStart
set docDay to second word of startDate
set docMonth to third word of startDate
set docYear to fourth word of startDate
set docHour to first word of startTime
set docMin to second word of startTime
set monthList to {January, February, March, April, May, June, July, August, September, October, November, December}
repeat with mth from 1 to 12
if docMonth = ((item mth of monthList) as string) then
set tempMonth to (characters -2 thru -1 of ("0" & mth))
exit repeat
end if
end repeat
set shortMonth to tempMonth
set shortYear to characters -2 thru -1 in docYear
set noteDateTime to docDay & "/" & shortMonth & "/" & shortYear & " " & docHour & ":" & docMin
set theOrganizer to the organizer of calendarEvent
set noteTitle to eventTitle & ", " & startDate
set emailList to get every email address of every attendee of calendarEvent
set nameList to ""
set ind to 0
repeat with theName in emailList
set ind to (ind + 1)
if (ind) = 1 then
if (name of theName) contains "," then -- "Surname, Firstname"
set (name of theName) to ((name of theName)'s second word & " " & (name of theName)'s first word)
end if
set nameList to nameList & " " & (name of theName)
else
if (name of theName) contains "," then -- "Surname, Firstname"
set (name of theName) to ((name of theName)'s second word & " " & (name of theName)'s first word)
end if
set nameList to nameList & ("\\par ") & " " & (name of theName)
end if
end repeat
else
display dialog "This is not calendar view! πŸ˜€" with icon 1
return
end if
end tell
Don't know if outlook has changed since the 2011 version but the missing value issue apparently endures. However, when I get properties of a recurrence, it includes icalendar data, which is a text blob of some 45 entries, one of which is recurrence-id. Here is one way to collect that entry:
tell application "Microsoft Outlook"
set rid to "RECURRENCE-ID"
set aa to calendar event id 1 -- original source
set ab to calendar event id 2 -- recurrence of aa
set icda to icalendar data of ab
set pi to paragraphs of icda
repeat with x in pi -- each property
if x contains rid then
set fulProp to contents of x
end if
end repeat
fulProp
--> "RECURRENCE-ID;TZID=\"Eastern Time (US & Canada)\":20210628T003000"
set valu to last word of fulProp
--> "20210628T003000"
end tell
The result looks like it could be parsed for its calendar event values.
I tried basically every attribute of a calendar event, and to my knowledge there is no way to get properties related to individual occurrences of a recurring event, other than the event id using the script Mockman linked to. Even the iCal exports are identical. Also, I couldn't find a way to grab the day of the currently selected event... however, when I tried that script, I realized that just the act of getting the occurrence of a recurring calendar event makes it no longer recurring, and after that the script works normally 🀯
so one possible logic is as follows:
is the event recurring?
if yes, is there an event today? (assuming that in most cases you are trying to access the event on the same day
3a) if yes, get occurrence at today's date and hour (this will break the recurrence of this event), then grab start time etc.
3b) if not, get start date of recurring event, event rate, day of the week etc, parse this information and get occurrence for all the events for one year or so (they will all become individual events), then grab dates.
If anyone knows how to grab the day of a selected calendar event (for example a recurrent one) then 3b is not needed...
Partial solution: this snippet will deal with recurring events by 'disconnecting' the event from the series, but only if run the same day. This is my use case 99% of the time (I run the script with Alfred right before a meeting), but it might not work for others. Add this snippet at line 24 of the previous script, or use the revised script.
set isRec to is recurring of calendarEvent
if isRec = true then
set tdate to current date
set sdate to start time of calendarEvent # because current date will have also current time, extract the time from the event (series)
tell me to set time of tdate to time of sdate
set myID to id of calendarEvent
try
set calendarEvent to get occurrence of calendar event id myID at tdate
set eventStart to start time of calendarEvent
on error
display dialog "❗This is a recurrent event, but I see no occurrences on " & tdate with icon 1
end try
end if

Multiple if conditions within nested repeat while in applescript

I've never used AppleScript before, so i'm quite unfamiliar with the language, but i'm doing my best.
Here's what i'm trying to accomplish:
Run a script while selecting a folder filled with .ARW and .JPG files. Iterate through the items in the folder. If the current item is .ARW, iterate through the folder starting from the beginning again. If this nested iteration lands on a file that has the same file name and a JPG extension, label the original ARW file with red.
TLDR: If an ARW file in a folder shares the same filename as a JPG file in the folder, highlight the ARW file in red, otherwise do nothing.
Here's the code i've written so far:
tell application "Finder"
set totalAlias to the entire contents of (selection as alias)
set totalCount to the count of items of totalAlias
set firstName to name of item 1 of totalAlias
set firstExtension to name extension of item 1 of totalAlias
set c to 1
repeat while c ≀ totalCount
set currentAlias to item c of totalAlias
set currentName to name of currentAlias
set currentExtension to name extension of currentAlias
if currentExtension is "ARW" then
set d to 1
set compareFile to currentAlias
set findName to currentName
set findExtension to currentExtension
repeat while d ≀ totalCount
if (name of item d of totalAlias = findName) and (name extension of item d of totalAlias is "JPG") then
tell application "Finder" to set label index of compareFile to 2
end if
set d to (d + 1)
end repeat
end if
set c to (c + 1)
end repeat
end tell
Any thoughts on what's going wrong? I believe it has to do with my IF AND condition.
Try this script:
tell application "Finder"
--Just get all the filenames of the target types:
set allJPG to the name of every file of (entire contents of (selection as alias)) whose name extension = "JPG"
set allARW to the name of every file of (entire contents of (selection as alias)) whose name extension = "ARW"
--Send the two lists to a handler to find all the common names
set targetJPGFiles to my CompareNames(allJPG, allARW)
--Loop through the common names, find the files, set the tags
repeat with eachTarget in targetJPGFiles
set fileToTag to (item 1 of (get every file of (entire contents of (selection as alias)) whose name is (eachTarget as text)))
set label index of fileToTag to 2
end repeat
end tell
targetJPGFiles -- This allows you to see the filenames that SHOULD have been tagged
to CompareNames(jp, pn)
--First, get rid of all the extensions in the ARW files
set cleanARWNames to {}
set neededJPGNames to {}
repeat with eachARWName in pn
set end of cleanARWNames to characters 1 thru -5 of (eachARWName as text) as text
end repeat
--Now, loop through JPG names to find a match
repeat with eachjpgName in jp
set searchName to characters 1 thru -5 of (eachjpgName as text) as text
if cleanARWNames contains searchName then
set end of neededJPGNames to (eachjpgName as text)
end if
end repeat
return neededJPGNames
end CompareNames
It takes a slightly different approach, in that it just compares two lists of filenames only, then goes back, finds the files with the names you want, and does the tagging.
It is based on a script I wrote for another project, so I hope it works for you.
I have never used the label index property in Finder before, and I found through some testing that I could not see the labels until I clicked on the folder after the script ran. All the target files had the correct tag after I did that, though.

Count number of iTunes songs by Artist with a name starting with a letter

I am brand new to Applescript. I would like a script that would list the artist and the number of songs in that artist's folder. I would like to do it just for artists whose names starts with A. When I am ready, I would then get the list for artist whose names starts with B, and so on. I did find this post: "What's the fastest way in iOS to retrieve the number of songs for a specific artist?" Maybe that script would work but I don't know how to modify this line "if (artistName != nil)" to get what I want. Also, I don't know where the information is stored so I can retreive it "// store the new count
[artists setObject:[NSNumber numberWithInt:numSongs] forKey:artistName]; Oh, and I am not using iOS I will be using osx. Perhaps I could modify this script that I found. It gets the number of albums by artist.
MPMediaQuery *albumQuery = [MPMediaQuery albumsQuery];
NSArray *albumCollection = [albumQuery collections];
NSCountedSet *artistAlbumCounter = [NSCountedSet set];
[albumCollection enumerateObjectsUsingBlock:^(MPMediaItemCollection *album, NSUInteger idx, BOOL *stop) {
NSString *artistName = [[album representativeItem] valueForProperty:MPMediaItemPropertyArtist];
[artistAlbumCounter addObject:artistName];
}];
NSLog(#"Artist Album Counted Set: %#", artistAlbumCounter);
I appreciate any help that you can offer. Thanks!
It makes no sense to look at iOS code and ObjectiveC at that in order to figure out what you should do with Applescript! In any case, here is what you want.
tell application "iTunes"
# Get playlist currently selected
set myPlayList to view of window 1
set s to (every track in myPlayList whose artist begins with "g")
repeat with t in s
log name of t
end repeat
log (count of s)
end tell
This one uses the selected playlist (or, if that fails for some reason, the whole library) and goes from A to Z. Replace the log parts with your code. To see how it works make sure in Script-Editor it shows the Log and for a better view select the Messages tab. Only file tracks are handled.
tell application "iTunes"
try
set selectedPlayList to view of window 1
on error
beep
set selectedPlayList to (container of browser window 1) -- whole library (I think)
end try
end tell
set totalItems to 0
repeat with i from (id of "A") to (id of "Z")
set thisLetter to (character id i)
log "-----------------------------------------------------------"
tell application "iTunes"
try
set currentItems to (file tracks in selectedPlayList whose artist begins with thisLetter)
set countItems to number of items in currentItems
set totalItems to totalItems + countItems
set s to "s"
if countItems = 1 then set s to ""
log (countItems as text) & " item" & s & " for artists starting with the letter " & quoted form of thisLetter
log "-----------------------------------------------------------"
repeat with i from 1 to countItems
set thisItem to item i of currentItems
tell thisItem -- this is like "tell file track x". Shortens the code because we can use "artist" instead of "artist of thisItem"
log (i as text) & ". " & quoted form of (get artist) & " | " & quoted form of (get name) & " [ " & time & " ] "
end tell
end repeat
on error the error_message number the error_number
beep
display dialog "Error: " & the error_number & ". " & the error_message buttons {"OK"} default button 1
return
end try
end tell
end repeat
log "-----------------------------------------------------------"
log "Items: " & totalItems as text

Find text from a file and set it as a variable in applescript?

I am trying to build a script that sends me updates and notifications from cex.io. Please keep on reading below, so I may guide you until the point I have trouble with.
The first simple script in this operation goes to cex.io's trading page for BTC/GHS. It records ands saves the text to a file every 4 seconds. It works great. It doesn't need to have safari refresh because the site pushes info to the browser live.
repeat
set the webpage_content to ""
tell application "Safari" to set the webpage_content to the text of document 1
set theText to webpage_content
set a to "Macintosh HD:Users:PRIVATE:Desktop:CEX:"
set theFile to (open for access file ((a) & "CEXRaw") with write permission)
write theText to theFile
close access theFile
delay 4
end repeat
-
And it returns this in a main file every 4 seconds: (note I cut off a chunk from the bottom and the top of the file, because they are unimportant)
GHS:
0.05233439
BTC:
0.00000223
NMC:
0.00002939
LTC:
0.00000000
GHS/BTC
0.02362958 LTC/BTC
0.02438131 NMC/BTC
0.00597565 GHS/NMC
3.96951800 BF1/BTC
1.67000000 Fund Account
GHS/BTC
Last price:
0.02362958
Daily change:
-0.00018042
Today's open:
0.02381000
24h volume:
73812.35539255
-
I now need an applescript to read that file, and return wanted values. But I'm lost on how to write it.
It needs to find the number under BTC, and set it as a variable.
It needs to find the number under GHS, and set it as a variable.
It needs to find the number under Last Price, and set it as a variable.
If anyone could script that really quick for me, or tell me how to do it, that would be amazing. Thank you so much!
Well, if those values will always be in the same paragraph counts, you could just pull them by line number.
set theCEXRaw to read file "Macintosh HD:Users:PRIVATE:Desktop:CEX:CEXRaw"
set theGHS to paragraph 2 of theCEXRaw
set theBTC to paragraph 4 of theCEXRaw
set thePRICE to paragraph 17 of theCEXRaw
You'd need to adjust the paragraph numbers. But, assuming that paragraph numbers aren't reliably consistent, in pure Applescript, you'd use Applescript's Text Item Delimiters.
set theCEXRaw to read file "Macintosh HD:Users:PRIVATE:Desktop:CEX:CEXRaw"
set AppleScript's text item delimiters to {("GHS:
"), ("BTC:
"), ("Last price:
")}
set theCEXRaw to text items of theCEXRaw
set theGHS to paragraph 1 of item 2 of theCEXRaw
set theBTC to paragraph 1 of item 3 of theCEXRaw
set thePRICE to paragraph 1 of item 4 of theCEXRaw
Note that the three delims include a return character inside the quotes. You will want to capture the old delimiter first, so you can restore it, and hopefully you can do the setting of the delimiter outside your repeat loop to save juice.
You could also use do shell script with sed or grep to strip each value.
You could get those values using the offset which searches a string for a substring and returns it's character position.
eg, set pos to the offset of "world" in "hello world" -- returns 7
Here is a solution that uses this principal to find your values and convert them into the Applescript floating point type Number
property line_delimiter : linefeed -- OR return OR return & linefeed pending your data
set results to "GHS:
0.05233439
BTC:
0.00000223
NMC:
0.00002939
LTC:
0.00000000
Last price:
0.02362958"
processCEX(results)
on processCEX(in_text)
set btc_val to searchNumberValueLine("BTC:" & line_delimiter, in_text)
set ghs_val to searchNumberValueLine("GHS:" & line_delimiter, in_text)
set last_price_val to searchNumberValueLine("Last price:" & line_delimiter, in_text)
display dialog ("btc = " & btc_val & return & "ghs = " & ghs_val & return & " last price = " & last_price_val)
end processCEX
on searchNumberValueLine(key_name, input_str)
set start_index to the offset of key_name in input_str
if (start_index is not 0) then
set input_str to text (start_index + ((length of key_name))) thru -1 of input_str
set end_index to the offset of line_delimiter in input_str
if (end_index is 0) then
return input_str as number
else
return (text 1 thru (end_index - 1) of input_str) as number
end if
else
return -1
end if
end searchNumberValueLine
Also i'd recommend against writing to a text file if you don't need to, to avoid any file io issues when reading the same file from a different script, given you are modifying it every 4 seconds.
You could change your code to something like this:
repeat
set the webpage_content to ""
tell application "Safari" to set the webpage_content to the text of document 1
processCEX(webpage_content)
delay 4
end repeat

How to loop through all rows in Excel using Applescript?

I'm trying to loop through all rows in Excel and run some command on each row, but I can't figure out how!
I tried initially doing that in rb-appscript (the Ruby wrapper for AppleScript) but decided that I'd be better off trying to get it working first in Applescript before adding another DSL. Any tips? (the rb-appscript version would be nice, too, though not required).
Thanks!
The coordinates of a range is a string that you can create dynamically. The simplest way to loop through your rows would be something like this:
repeat with thisRow from 1 to 10
tell application "Microsoft Excel"
set theRange to "A:" & thisRow & "Z:" & thisRow
set theValue to (get value of range theRange) as list
-- do something with the row's data
end tell
end repeat
Update per comments: To get the number of rows needing calculation, I wrote a subroutine ages ago to help with this. Be sure you have some kind of "key" column that is consistently populated (in other words, there are no skipped cells). This currently takes into account a header row since all of my spreadsheets have them:
on GetItemCount(KeyColumn)
set RowNumber to 1
set theText to "cSyoyodylg" -- dummy value
tell application "Microsoft Excel"
repeat until theText is ""
set RowNumber to RowNumber + 1
set theRange to KeyColumn & RowNumber & ":" & KeyColumn & RowNumber
set dataRange to range theRange of sheet 1
set theText to (get value of range theRange)
end repeat
end tell
set rowCount to RowNumber - 1
return rowCount
end GetItemCount
To use simply do this:
set lastRow to GetItemCount("A") of me
repeat with thisRow from 2 to lastRow + 1
-- go attack Excel
end repeat

Resources