Skip to content

Instantly share code, notes, and snippets.

@zachpendleton
Created July 5, 2012 20:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachpendleton/3056329 to your computer and use it in GitHub Desktop.
Save zachpendleton/3056329 to your computer and use it in GitHub Desktop.
Pianobar/LastFM Integration
#!/usr/bin/env ruby
# coding: utf-8
require 'digest/md5'
require 'net/http'
class LastFM
attr_reader :api_key, :secret, :session_key, :base_uri, :namespace
BASE_URI = URI('http://ws.audioscrobbler.com/2.0')
# Public: Return a new instance of the API object.
#
# api_key - LastFM API key.
# secret - LastFM secret token.
# session_key - Session token, if it's been cached.
def initialize(api_key, secret, session_key = nil)
@api_key = api_key
@secret = secret
@session_key = session_key unless session_key.nil?
end
# Public: Set the namespace for this interface.
#
# Returns self (for chaining).
def namespace!(namespace)
@namespace = namespace
self
end
def method_missing(method, *args, &block)
# If @namespace is nil, then we're just setting the namespace
# and returning self because the next call will have an actual
# LastFM method.
if @namespace.nil?
namespace!(method)
else
action = [@namespace, method.to_s].join('.')
params = args.first.merge(api_key: @api_key, sk: @session_key, method: action)
@namespace = nil
Net::HTTP.post_form(BASE_URI, params.merge(api_sig: signature(params)))
end
end
protected
# Internal: Generate an auth signature from a set of params.
#
# Returns a signature string.
def signature(params)
Digest::MD5.hexdigest(params.map { |p| p.join }.sort.join + @secret)
end
end
# Get track info from STDIN.
event = ARGV[0]
track = {}
STDIN.each_line { |l| track.store(*l.chomp.split('=', 2)) }
# Set up LastFM client.
fm = LastFM.new('api_key',
'secret',
'session_token')
# Handle events.
case event
# Scrobble songs on finish.
when 'songfinish'
fm.track.scrobble(artist: track['artist'], track: track['title'],
timestamp: Time.now.utc.to_i, chosenByUser: false)
# Love songs on thumbs up.
when 'songlove'
fm.track.love(artist: track['artist'], track: track['title'])
# Save current song to file for display in tmux and then update the now
# playing in LastFM.
when 'songstart'
fpath = File.join(File.expand_path(File.dirname(__FILE__)), 'current-song.txt')
File.open(fpath, 'w') do |f|
f.write("#[fg=colour39]⮂#[bg=colour39,fg=colour8]♫ #{track['title']} - #{track['artist']} @ #{track['stationName']} #[fg=default,bg=default]")
end
fm.track.updateNowPlaying(artist: track['artist'], track: track['title'])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment