Skip to content

Instantly share code, notes, and snippets.

@ninetwentyfour
Created March 1, 2012 19:17
Show Gist options
  • Save ninetwentyfour/1952432 to your computer and use it in GitHub Desktop.
Save ninetwentyfour/1952432 to your computer and use it in GitHub Desktop.
Hubot Soundcloud Play
require 'sinatra'
require 'json'
require 'net/http'
require 'open-uri'
require 'taglib'
get '/download/:url' do
client_id = "your client id here"
#pass in the url to the song and resolve it to get the song ID
url = "http://api.soundcloud.com/resolve.json?url=#{params[:url]}&client_id=#{client_id}"
resp = Net::HTTP.get_response(URI.parse(url))
data = resp.body
result = JSON.parse(data)
if result.has_key? 'Error'
raise "web service error"
end
#take the location and get the real song info
resp2 = Net::HTTP.get_response(URI.parse(result["location"]))
data2 = resp2.body
song_info = JSON.parse(data2)
if song_info.has_key? 'Error'
raise "web service error"
end
if song_info["downloadable"] == "true"
#follow the stram url and the redirect to the amazon asset
URL = "#{song_info["download_url"]}?client_id=#{client_id}"
open(URL) do |resp|
dl = resp.base_uri.to_s
filename = "/Path/to/save/location/#{song_info["permalink"]}.mp3"
open(filename, 'wb') do |file|
file << open(dl).read #save the file from amazon to computer
end
#open the file and add id3 tags
file = TagLib::MPEG::File.new(filename)
tag = file.id3v2_tag
tag.artist = artist = song_info["user"]["username"] #set the song artist
tag.title = song_info["title"] #set the song title
file.save
file.close
"file download complete"
end
else
"file not available for download"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment