Sha256: a3b483165c50c3c4bd8d776aa13eb95c7964ba33e728e9a9480a3000392c6335

Contents?: true

Size: 1.92 KB

Versions: 1

Compression:

Stored size: 1.92 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
      Kagu.logger.info('Kagu') { "Adding #{tracks.size} track(s) to playlist #{name.inspect}" }
      tracks.map(&:id).each_slice(500) do |ids|
        AppleScript.execute(%Q{
          tell application "Music"
            set playlistToPush to user playlist #{name.inspect}
            set idsToAdd to {#{ids.join(',')}}
            repeat with idToAdd in idsToAdd
              duplicate (tracks of library playlist 1 whose database ID is idToAdd) to playlistToPush
            end repeat
          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 "Music"
          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 "Music"
          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

    def xml_name=(value)
      @@html_entities ||= HTMLEntities.new
      self.name = @@html_entities.decode(value)
    end

  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
kagu-2.0.2 lib/kagu/playlist.rb