Created
July 5, 2009 08:32
-
-
Save oquno/140882 to your computer and use it in GitHub Desktop.
Ruby script to search own mt-daapd library and make playlist file of loved tracks on Last.fm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# /usr/local/bin/ruby | |
require 'nokogiri' | |
require 'open-uri' | |
require 'sqlite3' | |
$user = 'oquno' | |
$playlist_path = 'favorites.m3u' | |
$api_key = 'APIKEY HERE' | |
$sqlite_path = 'songs3.db' | |
def newtracks | |
lasttime = Time.at(File.mtime($playlist_path)) | |
url = 'http://ws.audioscrobbler.com/2.0/?method=user.getlovedtracks&user='+ $user +'&api_key='+$api_key | |
list = [] | |
xml = Nokogiri::XML(open(url)) | |
xml.xpath('//track').each do |track| | |
if track.xpath('.//date')[0]['uts'].to_i > lasttime.to_i | |
title = track.xpath('.//name')[0].content | |
artist = track.xpath('.//artist/name')[0].content | |
list.push([artist,title]) | |
else | |
break | |
end | |
end | |
if list.length != 0 | |
add(list) | |
end | |
end | |
def crawl | |
base_url = 'http://www.last.fm/user/' + $user + '/library/loved?sortBy=date&sortOrder=desc&page=' | |
page = 1 | |
while 1 | |
list = [] | |
doc = Nokogiri::HTML(open(base_url + page.to_s)) | |
if page == 1 | |
if doc.css('a.lastpage').length != 0 | |
lastpage = doc.css('a.lastpage')[0].content.to_i | |
else | |
lastpage = 1 | |
end | |
end | |
doc.css('td.subjectCell').each do |track| | |
artist = track.children[1].content | |
title = track.children[3].content | |
list.push([artist,title]) | |
end | |
add(list) | |
if page == lastpage | |
break | |
end | |
page+=1 | |
end | |
end | |
def add(list) | |
plist = [] | |
db = SQLite3::Database.open($sqlite_path) | |
list.each{|track| | |
q = 'select path from songs where artist="'+track[0]+'" and title="'+track[1]+'"' | |
db.query(q) do |row| | |
if row | |
row.each do |path| | |
plist.push(path) | |
end | |
end | |
end | |
} | |
db.close() | |
if File.exist?($playlist_path) | |
f = File.open($playlist_path,'a') | |
else | |
f = File.open($playlist_path,'w') | |
end | |
f.puts(plist.join("\n")) | |
f.close | |
end | |
if ARGV[0] == 'all' | |
crawl | |
elsif ARGV[0] == 'new' | |
newtracks | |
else | |
puts 'add "new" or "all"' | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment