Tenderlove Making

Automatically Query iTunes Shares

Here’s a quick program I came up with to query iTunes shares as soon as they connect. It uses dnssd to query for iTunes over multicast dns, and Net::DAAP::Client (ruby iTunes client) to query the iTunes share. The program will wait until someone starts up iTunes and automatically queries the iTunes server.

require 'rubygems'
require 'dnssd'
require 'net/daap'

Thread.abort_on_exception = true

class ITunesResolver
  @@servers = {}
  def self.resolve(br, action = :add)
    Thread.new(br, action) { |br, action|
      DNSSD.resolve(br.name, br.type, br.domain) { |rr|
        tr = rr.text_record

        # Skip servers that have a password
        if ! tr.has_key? "Password" or tr["Password"] == "false"
          if action == :add
            @@servers[rr.target] = Thread.new(rr.target) { |t|

              # Connect to the server and list all songs
              daap = Net::DAAP::Client.new(t)
              daap.connect do |dsn|
                daap.databases do |db|
                  # Print song names
                  db.songs.sort.each { |s| puts s.name }
                end
              end # End DAAP Query
            }
          else
            (@@servers.delete rr.target).kill if @@servers.has_key? rr.target
          end
        end
        rr.service.stop
      }
    }
  end
end

browse_service = DNSSD.browse('_daap._tcp') do |browse_reply|
  if browse_reply.flags.add?
    ITunesResolver.resolve(browse_reply)
  else
    ITunesResolver.resolve(browse_reply, :del)
  end
end

$stdin.gets
browse_service.stop

It’s not perfect, but the bugs are left as an exercise for the reader to fix!

« go back