Sha256: e64a86edfd87190c1c3dcdd0cef452acb26ac3cf6cb2a48226cc12bcdeab4576

Contents?: true

Size: 1.8 KB

Versions: 4

Compression:

Stored size: 1.8 KB

Contents

module Kagu

  class Playlist

    MANDATORY_ATTRIBUTES = %w(name)

    include AttributesInitializer
    include Enumerable

    attr_reader :name, :tracks

    delegate :each, to: :tracks

    def save
      create
      clear
      add_tracks
    end

    def to_s
      name
    end

    def tracks
      @tracks ||= []
    end

    private

    def add_tracks
      return if tracks.empty?
      Kagu.logger.info('Kagu') { "Adding #{tracks.size} track(s) to playlist #{name.inspect}" }
      Dir.mktmpdir do |directory|
        path = "#{directory}/#{name}.m3u"
        File.open(path, 'w') do |io|
          tracks.each { |track| io << "file://#{URI.escape(track.path.to_s)}\n" }
        end
        AppleScript.execute(%Q{
          tell application #{Kagu::OSX_APP_NAME.inspect}
            open #{path.inspect}
          end tell
        })
      end
      true
    rescue => e
      raise Error.new(e)
    end

    def clear
      Kagu.logger.info('Kagu') { "Removing all tracks from playlist #{name.inspect}" }
      AppleScript.execute(%Q{
        tell application #{Kagu::OSX_APP_NAME.inspect}
          delete tracks of playlist #{name.inspect}
        end tell
      })
      true
    rescue => e
      raise Error.new(e)
    end

    def create
      Kagu.logger.info('Kagu') { "Creating playlist #{name.inspect}" }
      AppleScript.execute(%Q{
        tell application #{Kagu::OSX_APP_NAME.inspect}
          if not (exists user playlist #{name.inspect}) then
            make new user playlist with properties { name: #{name.inspect} }
          end if
        end tell
      })
      true
    rescue => e
      raise Error.new(e)
    end

    def name=(value)
      @name = value.to_s.squish.presence
    end

    def tracks=(values)
      @tracks = [values].flatten.select { |value| value.is_a?(Track) }
    end

  end

end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
kagu-3.0.3 lib/kagu/playlist.rb
kagu-3.0.2 lib/kagu/playlist.rb
kagu-3.0.1 lib/kagu/playlist.rb
kagu-3.0.0 lib/kagu/playlist.rb