Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 46 lines (35 sloc) 1.18 KB
#!/usr/bin/env ruby
# frozen_string_literal: true
# albumart.rb
# Author: William Woodruff
# ------------------------
# Fetch an album's cover art using Last.fm's search API.
# Only retrieves large and extralarge images.
# ------------------------
# This code is licensed by William Woodruff under the MIT License.
# http://opensource.org/licenses/MIT
require "net/http"
require "json"
QUERY = ARGV.shift
KEY = ENV["LASTFM_API_KEY"]
URL = "http://ws.audioscrobbler.com/2.0/?method=album.search" \
"&album=%<query>s" \
"&api_key=%<key>s" \
"&format=json"
abort("Usage: #{$PROGRAM_NAME} <query>") unless QUERY
abort("Fatal: Missing environment: LASTFM_API_KEY.") unless KEY
url = URL % { query: QUERY, key: KEY }
begin
response = JSON.parse Net::HTTP.get(URI(url))
rescue OpenURI::HTTPError => e
abort "Fatal: #{e}"
end
images = response["results"]["albummatches"]["album"].first["image"]
image = images.find { |i| i["size"] == "extralarge" }
image ||= images.find { |i| i["size"] == "large" }
abort("Fatal: Couldn't find a sufficiently large image.") unless image
begin
File.write("cover.png", Net::HTTP.get(URI(image["#text"])))
rescue Net::HTTPError => e
abort "Fatal: #{e}"
end