Skip to content

Instantly share code, notes, and snippets.

@ip2k
Created January 25, 2013 07:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ip2k/4632486 to your computer and use it in GitHub Desktop.
Save ip2k/4632486 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'nokogiri'
require 'pp'
require 'open-uri'
require 'sqlite3'
# set our filename and path names up
DBNAME = 'favdb.sqlite' # filename for SQLite DB
DBPATH = '~/.pandora-favdb/' # with trailing slash
# computed paths
FULL_PATH = File.expand_path( DBPATH )
FULL_NAME = File.expand_path( DBPATH + DBNAME )
# sort our our directory
begin
Dir.mkdir( FULL_PATH ) unless File::directory?( FULL_PATH )
rescue
abort "Can't create directory: #{FULL_PATH}. Maybe it's already a file or exists but isn't writable by you?"
end
# sqlite DB init and create table if it's not already there
db = SQLite3::Database.new( FULL_NAME )
db.transaction do |db| # wrap it in a nice clean transaction that rolls back upon failure
db.execute( 'CREATE TABLE IF NOT EXISTS bookmarks (id INTEGER PRIMARY KEY, time INTEGER, artist TEXT, track TEXT, album TEXT, bookmarked_at TEXT )' ) # set up the table if it isn't there
end
doc = Nokogiri::XML( open ( "http://feeds.pandora.com/feeds/people/pandora223753/favorites.xml?max=100" ) ) # open our XML and parse it with nokogiri
songs = Array.new # songs will be an array of hashes; each hash will be all info for one track
doc.xpath( '//item' ).each do |item| # select each item (track)
# build our hash for this one track and push it onto the songs array
songs.push(
{ "track" => item.xpath('./mm:Track/dc:title').text,
"artist" => item.xpath('./mm:Artist/dc:title').text,
"album" => item.xpath('./mm:Album/dc:title').text,
"bookmarked_at" => item.xpath('./pubDate').text }
)
end
songs.each do |song| # for each track info hash inside the array of them we just built...
db.transaction do |db|
db.execute( 'INSERT INTO bookmarks (time,artist,track,album,bookmarked_at) VALUES (?,?,?,?,?)', Time.now.to_i, song["artist"], song["track"], song["album"], song["bookmarked_at"] )
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment