Skip to content

Instantly share code, notes, and snippets.

@valeth
Created November 23, 2018 21:18
Show Gist options
  • Save valeth/77252977cfcb6e429d695c5f02651328 to your computer and use it in GitHub Desktop.
Save valeth/77252977cfcb6e429d695c5f02651328 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# frozen_string_literal: true
# rubocop:disable all
require "json"
require "active_support/core_ext/hash/keys"
FORMAT = " | Now Playing: %{title} by %{artist} in %{album}"
module MPD
class TrackInfo
DEFAULT_INFO = {
artist: "Unknown Artist",
album: "Unknown Album",
title: "Unknown Title"
}.freeze
attr_reader :info
def initialize(hash = {})
tmp = hash.symbolize_keys.reject { |_,v| v.empty? }
@info = DEFAULT_INFO.dup.update(tmp)
end
def to_s
@info.values.join(" - ")
end
def format(fmt)
Kernel.format(fmt, **@info)
end
def ==(other)
return false unless other.is_a?(self.class)
return info == other.info
end
def none?
@info[:title] == "Unknown Title"
end
end
module_function
def info
fmt = %{'{"artist":"%artist%","album":"%album%","title":"%title%"}'}
lines = `mpc -f #{fmt} status`.chomp.lines
return [TrackInfo.new({}), false] if lines.size < 3
[TrackInfo.new(JSON.parse(lines.first)), /^\[playing\]/.match?(lines[1])]
end
end
previous = MPD::TrackInfo.new
outfile = ARGV.first
cleared = false
loop do
current, playing = MPD.info
if (current.none? || !playing) && !cleared
puts "Clearing song info"
File.open(outfile, "w") { |f| f.write("") }
cleared = true
elsif previous != current
puts "Changing song to #{current}"
File.open(outfile, "w") { |f| f.write(current.format(FORMAT)) }
previous = current.dup
cleared = false
end
sleep(2)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment