Subversion Repositories mildred

Rev

Blame | Compare with Previous | Last modification | View Log | RSS feed

# given a list of mood names, artist names, and album titles, provides a list
# of unique tracks contained therein.
class Fetcher < Array

  @@logger = nil
  cattr_accessor :logger

  def initialize(mood_names, album_titles, artist_names)
    @albums = []
    @artists = []
    @cond = "(tracks.rating >= 2.0 OR tracks.rating = 0.0) AND tracks.time >= 45 AND NOT tracks.disabled"

    fetch_moods(mood_names)
    fetch_albums(album_titles)
    fetch_artists(artist_names)
    fetch_tracks
    check_size
  end

  private

  def check_size
    return unless self.size.zero? # go random!

    logger.debug("Loading default Fetcher, pure random!")
    Track.find(:all, :conditions => @cond, :include => [{:medium => {:album => :moods}}, :artist]).each {|t| self << t}
  end

  def fetch_moods(mood_names)
    mood_names.each do |name|
      m = Mood.find_by_name(name, :include => :albums)
      if m
        @albums += m.albums
      else
        logger.warn("WARN: Could not find mood with name: '#{name}'")
      end
    end
    @albums.uniq!
  end

  def fetch_albums(album_titles)
    album_titles.each do |title|
      a = Album.find_all_by_title(title, :include => [:artists, {:media => :tracks}])
      @albums += a
      logger.warn("WARN: Could not find album with title: '#{title}'") if a.empty?
    end
    @albums.uniq!
  end

  def fetch_artists(artist_names)
    artist_names.each do |name|
      a = Artist.find_all_by_name(name, :include => [:tracks, {:albums => {:media => :tracks}}])
      @artists += a
      logger.warn("WARN: Could not find artist with name: '#{name}'") if a.empty?
    end
    @artists.uniq!
  end

  def fetch_tracks
    artist_albums = @artists.collect {|a| a.albums}.flatten
    artist_albums.each do |a|
      a.tracks.find(:all, :conditions => @cond, :include => [{:medium => :album}, :artist]).each {|b| self << b}
    end
    @artists.collect do |a|
      a.tracks.find(:all, :conditions => @cond, :include => [{:medium => :album}, :artist]).each {|b| self << b}
    end

    @albums.each do |a|
      a.tracks.find(:all, :conditions => @cond, :include => [{:medium => :album}, :artist]).each {|b| self << b}
    end

    self.uniq!
  end
end