Applescript timed out in iTunes - applescript

I wrote a simple applescript to automatically add files into iTunes and fill the metadata. When I run it directly from the editor it works but running it from iTunes and I will get "AppleEvent Timed Out".
Here's the code:
set mainFolder to choose folder
tell application "Finder"
-- Loop through all shows
set shows to every folder of mainFolder
repeat with show from 1 to count of shows
-- Set Show Name
set showName to name of item show of shows
-- Set Artist
display dialog "Who is the artist for " & showName & "?" default answer showName
set showArtist to the text returned of the result
-- Set Genre
display dialog "What is the genre for " & showName & "?" default answer ""
set showGenre to the text returned of the result
-- Loop through all season
set seasons to every folder in item show of shows
repeat with season from 1 to count of seasons
set seasonName to name of item season of seasons
-- Set Season Number
set seasonNumber to text 1 thru ((offset of "-" in seasonName) - 2) of seasonName as integer
-- Set Year
display dialog "What year was Season " & seasonNumber & " of " & showName & " in?" default answer "2012"
set showYear to the text returned of the result
-- Set Season Name
set seasonName to text ((offset of "-" in seasonName) + 2) thru ((offset of "." in seasonName) - 1) of seasonName as text
-- Set Total Episodes in Season
set totalEpisodes to count of every file in item season of seasons
-- Loop through all episodes
set episodes to every file in item season of seasons
repeat with episode from 1 to count of episodes
set episodeName to name of item episode of episodes
-- Set Episode Number
set episodeNumber to text 1 thru ((offset of "-" in episodeName) - 2) of episodeName as integer
-- Set Episode Name
set episodeName to text ((offset of "-" in episodeName) + 2) thru ((offset of "." in episodeName) - 1) of episodeName as text
tell application "iTunes"
set newAddition to (add (item episode of episodes as alias))
tell newAddition
set video kind to TV show
set name to episodeName
set album to seasonName
set track number to episodeNumber
set track count to totalEpisodes
set disc number to "1"
set disc count to "1"
set show to showName
set season number to seasonNumber
set episode number to episodeNumber
-- Manual Entries
set artist to showArtist
set genre to showGenre
set year to showYear
-- Change episode ID based on season and episode number
if (seasonNumber < 10) then
if (episodeNumber < 10) then
set episode ID to ("S0" & seasonNumber as text) & "E0" & episodeNumber as text
else
set episode ID to ("S0" & seasonNumber as text) & "E" & episodeNumber as text
end if
else
if (episodeNumber < 10) then
set episode ID to ("S" & seasonNumber as text) & "E0" & episodeNumber as text
else
set episode ID to ("S" & seasonNumber as text) & "E" & episodeNumber as text
end if
end if
end tell -- End newAddition
end tell -- End iTunes
end repeat -- End Episode Repeat
end repeat -- End Season Repeat
end repeat -- End Show Repeat
end tell -- End Finder Repeat

the code itself seems sound assuming you don't have any errors when calculating the offsets and different components of the file name. However I can see 2 possible sources of errors that may fix your problem.
First, you have your iTunes tell block of code inside your Finder tell block of code. Essentially you are telling the Finder to tell iTunes to do something. That is a source of possible errors. You should separate your tell blocks from each other. For example you have this...
tell application "Finder"
-- do something
tell application "iTunes"
-- do something
end tell
end tell
When you should have it like this...
tell application "Finder"
-- do something
end tell
tell application "iTunes"
-- do something
end tell
Second, you have a mistake in your "episode id" code with the parenthesis. For example this...
("S0" & seasonNumber as text)
Should be this...
"S0" & (seasonNumber as text)
As such I have separated out the iTunes stuff into a subroutine and fixed the parenthesis. Note that I haven't tested this code. I think I passed all of the proper variables to the subroutine but I can't be certain. I hope this helps.
set mainFolder to choose folder
tell application "Finder"
-- Loop through all shows
set shows to every folder of mainFolder
repeat with show from 1 to count of shows
-- Set Show Name
set showName to name of item show of shows
-- Set Artist
display dialog "Who is the artist for " & showName & "?" default answer showName
set showArtist to the text returned of the result
-- Set Genre
display dialog "What is the genre for " & showName & "?" default answer ""
set showGenre to the text returned of the result
-- Loop through all season
set seasons to every folder in item show of shows
repeat with season from 1 to count of seasons
set seasonName to name of item season of seasons
-- Set Season Number
set seasonNumber to text 1 thru ((offset of "-" in seasonName) - 2) of seasonName as integer
-- Set Year
display dialog "What year was Season " & seasonNumber & " of " & showName & " in?" default answer "2012"
set showYear to the text returned of the result
-- Set Season Name
set seasonName to text ((offset of "-" in seasonName) + 2) thru ((offset of "." in seasonName) - 1) of seasonName as text
-- Set Total Episodes in Season
set totalEpisodes to count of every file in item season of seasons
-- Loop through all episodes
set episodes to every file in item season of seasons
repeat with episode from 1 to count of episodes
set episodeName to name of item episode of episodes
-- Set Episode Number
set episodeNumber to text 1 thru ((offset of "-" in episodeName) - 2) of episodeName as integer
-- Set Episode Name
set episodeName to text ((offset of "-" in episodeName) + 2) thru ((offset of "." in episodeName) - 1) of episodeName as text
my addEpisodeToItunes((item episode of episodes) as alias, seasonName, seasonNumber, episodeName, episodeNumber, totalEpisodes, showName, showArtist, showGenre, showYear)
end repeat -- End Episode Repeat
end repeat -- End Season Repeat
end repeat -- End Show Repeat
end tell -- End Finder Repeat
on addEpisodeToItunes(theEpisode, seasonName, seasonNumber, episodeName, episodeNumber, totalEpisodes, showName, showArtist, showGenre, showYear)
tell application "iTunes"
set newAddition to add theEpisode
tell newAddition
set video kind to TV show
set name to episodeName
set album to seasonName
set track number to episodeNumber
set track count to totalEpisodes
set disc number to "1"
set disc count to "1"
set show to showName
set season number to seasonNumber
set episode number to episodeNumber
-- Manual Entries
set artist to showArtist
set genre to showGenre
set year to showYear
-- Change episode ID based on season and episode number
if (seasonNumber < 10) then
if (episodeNumber < 10) then
set episode ID to "S0" & (seasonNumber as text) & "E0" & (episodeNumber as text)
else
set episode ID to "S0" & (seasonNumber as text) & "E" & (episodeNumber as text)
end if
else
if (episodeNumber < 10) then
set episode ID to "S" & (seasonNumber as text) & "E0" & (episodeNumber as text)
else
set episode ID to "S" & (seasonNumber as text) & "E" & (episodeNumber as text)
end if
end if
end tell -- End newAddition
end tell -- End iTunes
end addEpisodeToItunes

Here is how I solved it:
Save as an app instead of a script.
I got the solution from here:
http://forums.ilounge.com/applescripts-itunes-mac/245120-need-help-add-tracks-files-via-applescript.html
I have no clue why it's doing that, I've tried using try-catch, timeout... still didn't work. It works as an app though?!

Related

How to append a random string to filenames using Script Editor [Mac OS]

I have a folder filled with pdf files.
filename_1.pdf
filename_2.pdf
filename_3.pdf
etc...
I am looking for a way to go from those filenames to something like :
filename_1973878763487.pdf
filename_27523765376346.pdf
filename_326537652376523.pdf
I came across the following script that changes filenames to random numbers :
tell application "Finder"
repeat with this_item in (get items of window 1)
set name of this_item to ((random number from 1000 to 9999) & "." & name extension of this_item) as string
end repeat
end tell
The script outputs something like this :
3598.pdf
7862.pdf
8365.pdf
So i need a way to append the random numbers to the original filename.
This should work for you
tell application "Finder"
repeat with thisItem in (get items of window 1)
set fileName to name of thisItem
tell current application
set theOffset to offset of "_" in fileName
end tell
set tempFileName to text 1 thru (theOffset + 1) of fileName
tell current application
set randomNumber to (random number from 1000 to 9999)
end tell
set name of thisItem to tempFileName & (randomNumber & "." & name extension of thisItem) as string
end repeat
end tell

applescript to create multiple sequentially numbered folders with a specific prefix

I would like to create an applescript that will create multiple folders with the same root name but the numbers change? or at least a repeating folder creation script until the person has enough folders. So something that makes folders like this: JOYR-15-0035-00, JOYR-15-0036-00, JOYR-15-0037-00 and so on. Is that at all possible? I am just learning this. I am normally a graphic designer but I feel like I can get a lot from applescript.
Currently I just have this basic script:
tell application "Finder"
set KDID to text returned of (display dialog "Enter the KDID ID:" default answer "JOYR-")
set loc to choose folder "Choose Parent Folder Location"
set newfoldername to {name:KDID}
set newfo to make new folder at loc with properties {name:KDID}
reveal newfo
end tell
Try this, it assumes that the KDID is just the number 15 in the example, the syntax is always JOYR-<KDID>-<consecutive number>-00 and the leading JOYR as well as the trailing double zero don't change.
The script asks for the parent folder, the KDID and the number of sequential folders. Then it checks the parent folder for the greatest existing number (the 0035 part) and creates folders starting with the greatest number plus 1 or – if no existing folders are found – with 1. The number has always four digits.
property letterPrefix : "JOYR"
property KDID : "15"
property parentFolder : missing value
set parentFolder to choose folder "Choose Parent Folder Location"
tell application "Finder"
activate
set KDID to text returned of (display dialog "Enter the KDID ID:" default answer "15")
repeat
set howManyFolders to text returned of (display dialog "Enter the Number of Folders to create:" default answer "1")
try
set howManyFolders to howManyFolders as integer
if howManyFolders < 1 then error
exit repeat
on error
display dialog "Please enter an integer value greater than 0" default answer "1"
end try
end repeat
set currentNumber to my getGreatestFolderNumber()
repeat howManyFolders times
set folderName to letterPrefix & "-" & KDID & "-" & my pad(currentNumber) & "-00"
make new folder at parentFolder with properties {name:folderName}
set currentNumber to currentNumber + 1
end repeat
open parentFolder
end tell
on getGreatestFolderNumber()
tell application "Finder"
set {ASTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "-"}
try
set folderNames to name of folders of parentFolder whose name starts with (letterPrefix & "-" & KDID & "-")
set maxNumber to 0
repeat with aName in folderNames
set curNumber to (text item 3 of aName) as integer
if curNumber > maxNumber then set maxNumber to curNumber
end repeat
set AppleScript's text item delimiters to ASTID
return maxNumber + 1
on error
set AppleScript's text item delimiters to ASTID
return 1
end try
end tell
end getGreatestFolderNumber
on pad(v)
return text -4 thru -1 of ("000" & v)
end pad

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

applescript transforming a list into a txt file

I'm trying to write all the song names my iTunes to a txt document. The first issue I had was that I can't seem to correctly loop the operation. Here is my test case with the first 15 songs in my iTunes:
tell application "TextEdit"
make new document
end tell
tell application "iTunes"
set trNameID1 to name of track 1
set trNameID2 to name of track 2
set trNameID3 to name of track 3
set trNameID4 to name of track 4
set trNameID5 to name of track 5
set trNameID6 to name of track 6
set trNameID7 to name of track 7
set trNameID8 to name of track 8
set trNameID9 to name of track 9
set trNameID10 to name of track 10
set trNameID11 to name of track 11
set trNameID12 to name of track 12
set trNameID13 to name of track 13
set trNameID14 to name of track 14
set trNameID15 to name of track 15
tell application "TextEdit"
set text of document 1 to {trNameID1 & "
", trNameID2 & "
", trNameID3 & "
", trNameID4 & "
", trNameID5 & "
", trNameID6 & "
", trNameID7 & "
", trNameID8 & "
", trNameID9 & "
", trNameID10 & "
", trNameID11 & "
", trNameID12 & "
", trNameID13 & "
", trNameID14 & "
", trNameID15} as text
end tell
end tell
When I try to loop it, the txt document only contains the last song name, for instance:
tell application "TextEdit"
make new document
end tell
tell application "iTunes"
set trNum to 1
repeat 15 times
set trNameID to name of track (trNum)
tell application "TextEdit"
set text of document 1 to trNameID & "
"
end tell
end repeat
end tell
This will only output the fifteenth song's name onto the txt document.
I realize that this may be very basic, but I have literally been using applescript for about 48 hours, and I can't seem to figure this out. I would like all of the song names to be in a txt document so I can read and analyze the strings in c++. Does anyone have any ideas?
Also, I'm not sure if there is a way, in AppleScript, to look at the entire iTunes library and see the last song, record that song's id in iTunes, and then make a repeat loop that goes through that id. This way the loop would work for exactly the number of songs that are in the library.
Any ideas would be very much appreciated!
You don't really need a repeat loop at all. You can get track names directly from iTunes. You get it in list format so we just convert that list into a string separating the list items with a return character. Then we write it to TextEdit. So this code optimizes #Michele Percich's code by eliminating the repeat loop and using applescript's text item delimiters to convert the list to a string for use in TextEdit.
tell application "iTunes"
set trackNames to name of every track in (first playlist whose special kind is Music)
end tell
set text item delimiters to return
set trackNames to trackNames as text
set text item delimiters to ""
tell application "TextEdit"
make new document
set text of document 1 to trackNames
end tell
You need to increment the value of trNum variable at the end of your repeat loop:
set trNum to trNum + 1
Or better use a different repeat syntax:
repeat with trNum from 1 to 15
And also to add (and not replace) the track name to the document:
set text of document 1 to text of document 1 & trNameID & return
However, this probably is a better way to do what you want:
tell application "iTunes"
set trackList to ""
set allTracks to every track in (first playlist whose special kind is Music)
repeat with currentTrack in allTracks
set trNameID to name of currentTrack
set trackList to trackList & trNameID & return
end repeat
end tell
tell application "TextEdit"
make new document
set text of document 1 to trackList
end tell
i see you all use the:
tell application "TextEdit"
make new document
set text of document 1 to trackNames
end tell
command
You can use a faster way:
set textlocation to "/users/yourusername/desktop/test.txt"
set Line_1 to "Hello this is line one, if you want more lines just copy > this script and change the variables."
do shell script "echo " & quoted form of Line_1 & " >> " & quoted form of textlocation
You can see in the script the 2 ">>" signs, this will add each textline in a new line in a txt file.
If there is only one ">" the text will replace the other text.
Here is an example:
First with 2 ">>" lines
do shell script "echo Hey this is one line. >> /Users/Yourusername/desktop/Add.txt"
do shell script "echo And this is the second one. >> /Users/Yourusername/desktop/Add.txt"
This script will make a txt file like this:
Hey this is one line.
And this is the second one.
Now with 2 ">" lines
do shell script "echo Hey this is one line > /Users/Zl109819/desktop/Add.txt"
do shell script "echo And this is the second one > /Users/Zl109819/desktop/Add.txt"
This script will make a txt file like this:
And this is the second one.

can i add several attachments from subfolders to Mail?

trying to send several mails with specific attachments for each address. every address has its own subfolder for attachments. the "grab attachments part" does not work and I am not sure if the handler is set up right: should I pass the subfolder to mail inside the handler or keep it as I have it. This is my first long script so please don't be too harsh ;-)
I'm thinking that i get closer to the working solution, I still don't get it to function. here is my script so far:
` with timeout of 600 seconds
-- Liste: Alle Empfänger
tell application "Contacts"
set emailList to {}
set testPersons to every person of group "Test"
repeat with thisTestPerson in testPersons
set end of emailList to (value of email of thisTestPerson) as string
end repeat
end tell
-- Liste fuer die Übergabe alphabetisch sortieren
set the_list to emailList
set otid to AppleScript's text item delimiters
set AppleScript's text item delimiters to {ASCII character 10} -- always a linefeed
set list_string to (the_list as string)
set new_string to do shell script "echo " & quoted form of list_string & " | sort -f"
set new_list to (paragraphs of new_string)
set AppleScript's text item delimiters to otid
-- Liste: Alle Subfolder
tell application "Finder"
set mainfolder to choose folder "select a folder"
set folderList to {}
set myFolders to every folder of mainfolder
repeat with attachFolder from 1 to (count of myFolders)
set end of folderList to attachFolder as string
end repeat
end tell
-- Sicherheits-Check
set count1 to count of myFolders
set count2 to count of new_list
if count1 is not equal to count2 then
display dialog "Houston, we have a problem:" & return & "Die beiden Listen sind nicht gleich lang..." buttons {"ok"} with icon 2
return
end if
end timeout
--handler processfolder(myFiles)
on processfolder(myFiles)
tell application "Mail"
activate
set theAddress to (item i of emailList)
set theMex to (make new outgoing message at end of outgoing messages with properties {visible:true, subject:"Subjectheader", content:"email body"})
tell content of theMex
make new attachment with properties {file name:FileList} at after last paragraph
end tell
tell theMex
make new to recipient at end of to recipients with properties {address:theAddress}
end tell
send theMex
end tell
end processfolder
-- grab attachments and send mail
tell application "Finder"
repeat with myFolder from 1 to (count of folderList)
set FileList to {}
set myFiles to entire contents of myFolder
repeat with thisFile in myFiles
set end of FileList to thisFile as string
end repeat
my processfolder(myFiles)
end repeat
end tell
display dialog (count1 as string) & " Nachrichten verschickt."
end`
i believe the handler should work alright. Matching the subfolder list with the address list still seems to be a problem, I am not sure if my repeat loop "grab attachment und send mail" does the trick. It is a tricky use of repeat loops and I am still struggling with it. any quick thoughts about what I am still doing wrong?
thanks for being helpful! i really appreciate this!
marco
You must pass the variables as parameters in the handler :
1- (item i of emailList) : i and emailList is not defined in the handler.
2- {file name:FileList} : FileList is not defined in the handler, file name must be a path of type alias or string, not a list of path.
set myFiles to entire contents of myFolder : the myfolder variable is an integer, entire contents will contains the folders and files, if the folder doesn't contains subfolders, entire contents is useless, use files of xFolder.
The rest is okay, but contains unnecessary lines.
Here is the script:
with timeout of 600 seconds
-- Liste: Alle Empfänger
tell application "Contacts"
set emailList to value of email 1 of every person of group "Test"
end tell
-- Liste fuer die Übergabe alphabetisch sortieren
set otid to AppleScript's text item delimiters
set AppleScript's text item delimiters to {linefeed}
do shell script "echo " & (quoted form of (emailList as string)) & " | sort -f"
set emailList to (paragraphs of the result)
set AppleScript's text item delimiters to otid
-- Liste: Alle Subfolder
activate
set mainfolder to choose folder "select a folder"
tell application "Finder" to set folderList to folders of mainfolder
-- Sicherheits-Check
set count1 to count folderList
if count1 is not equal to (count emailList) then
display dialog "Houston, we have a problem:" & return & "Die beiden Listen sind nicht gleich lang..." buttons {"ok"} cancel button "ok" with icon 2
end if
end timeout
-- grab attachments and send mail
repeat with i from 1 to count1
try
tell application "Finder" to set myFiles to (files of entire contents of (item i of folderList)) as alias list
my processfolder(myFiles, item i of emailList)
end try -- no error on empty folder
end repeat
display dialog (count1 as string) & " Nachrichten verschickt."
on processfolder(tFiles, theAddress)
tell application "Mail"
activate
tell (make new outgoing message at end of outgoing messages with properties {visible:true, subject:"Subjectheader", content:("email body" & linefeed & " ")})
make new to recipient at end of to recipients with properties {address:theAddress}
tell content to repeat with tFile in tFiles
make new attachment with properties {file name:tFile} at after last paragraph
make new character with data linefeed at after last paragraph
end repeat
send
end tell
end tell
end processfolder
it is done! Thanks to you and one or two other pros I now have a beautiful bulk mailing script routine using automator, a bash line and (mainly) applescript. I use it for job applications but you can use it for any case where you want individualised bulk emailing with Mail, MS Word and any given list of contacts in Excel (or Address Book for that matter). For the sake of being complete I will add all necessary steps. with any given list of x names, email addresses, personal addresses you can generate x subfolders, containing x personalized letters and not-personalized documents (thanks, Jack! adding the docs works perfectly). once you start the last script and select the folder you can watch mail sending them all out, addressing the person by name and attaching the right personalized letter! It corrects for foreign name spelling that is rendered differently in the email address. It works best for email addresses using the last name before the "#" and can now ignore the first name if it is set in front of the last name (i.e. firstname.lastname#company.com). Thank you all very much for the assistance! this was great team effort.
I shall post it as soon as I am home, should I post it up here and in the other related question or is there a sharing forum?

Resources