Automatically ‘mounting’ shared playlists in iTunes

The ProHaxors are working on a sweet project called Dukejour, which is a more pro version of the railscamp jukebox, Duke. We’ll blog about it soon, but it uses iTunes sharing to discover all the available tracks on the network. Unfortunately, there’s no applescript API for iTunes to ‘mount’ a shared playlist. You can browse the libraries already mounted, but mounting was a manual process.

So I schooled up a bit on applescript’s System Events, and using rubyosa, and using UI Browser was able to determine how to get the key information required - a list of all the rows down the left of the window.

From there, the shared libraries can be found in between ‘SHARED’ and ‘PLAYLISTS’. I couldn’t get any click method to work but calling the AXShowMenu then sending the escape char works ok. If there’s a password or any other problem any dialog box is dismissed by pressing escape and space. And it works!

require 'rbosa'
itunes = OSA.app('iTunes')
itunes.activate

sys = OSA.app("System Events")
process = sys.processes.find { |p| p.name == "iTunes" }

rows = process.windows[0].splitter_groups[0].scroll_areas[0].outlines[0].rows
row_names = rows.map { |r| r.static_texts[0].name }
shared_index = row_names.index("SHARED")
if shared_index.nil?
  puts "No shared libraries available!"
else
  ((shared_index + 1)..(row_names.index("PLAYLISTS") - 1)).each { |r_index|
    puts "Adding library #{row_names[r_index]}"
    rows[r_index].actions.select { |a| a.name == "AXShowMenu" }.first.perform
    sleep(1)
    sys.key_code 53 # escape the right-click menu
    sleep(1)
    sys.key_code 53 # escape the password prompt, if it appeared
    sys.key_code 100 # dismiss an error dialog, e.g. 'too many connections', if it appeared
    sleep(1)
    puts "Done."
  }
end