Last active
December 29, 2015 18:09
-
-
Save danhigham/7708888 to your computer and use it in GitHub Desktop.
Download a mixcloud stream!
This file contains hidden or 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/bin/env ruby | |
require 'httparty' | |
require 'json' | |
require 'nokogiri' | |
require 'open-uri' | |
class Numeric | |
def percent_of(n) | |
self.to_f / n.to_f * 100.0 | |
end | |
end | |
user = ARGV[0] | |
response = HTTParty.get("http://api.mixcloud.com/#{user}/cloudcasts/") | |
mixes = JSON.parse(response.body) | |
mixes["data"].each do |m| | |
mix_url = m["key"] | |
mix_response = HTTParty.get("http://api.mixcloud.com#{mix_url}") | |
mix = JSON.parse(mix_response.body) | |
url = mix["url"] | |
mix_name = mix["name"] | |
doc = Nokogiri::HTML(open(url)) | |
preview_url = doc.css('//*[@id="player-play"]').first.attributes["data-preview-url"].value | |
puts "Preview : #{preview_url}" | |
stream_id = preview_url.scan(/previews([^\.]+)/)[0][0] | |
stream_url = "/cloudcasts/m4a/64#{stream_id}.m4a" | |
f = File.open("#{mix_name}.m4a", "wb") | |
begin | |
(15..30).each do |x| | |
puts "Trying stream#{x}.mixcloud.com" | |
Net::HTTP.start("stream#{x}.mixcloud.com") do |http| | |
http.request_get(stream_url) do |resp| | |
if resp.code != "404" | |
content_length = resp['Content-Length'].to_i | |
done = 0 | |
puts "Writing to #{mix_name}.m4a (#{content_length} bytes)" | |
resp.read_body do |segment| | |
f.write(segment) | |
done = done + segment.length | |
print "#{done} bytes - " | |
print "%.2f%%" % done.percent_of(content_length) | |
print 13.chr | |
end | |
puts "Done!" | |
break | |
end | |
end | |
end | |
end | |
ensure | |
f.close | |
end | |
end |
This file contains hidden or 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
source 'http://rubygems.org' | |
gem 'httparty' | |
gem 'nokogiri' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment