Created
September 2, 2014 18:07
-
-
Save sgnn7/91673f7903bfaf69e5ae to your computer and use it in GitHub Desktop.
RailsCasts download
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/bin/env ruby | |
# A script to download the latest episodes from railscasts.com | |
# | |
# modifications: sgnn7 <sgnn7@sgnn7.org> | |
# original author: modsaid <mahmoud@modsaid.com> | |
require 'rubygems' | |
require 'json' | |
require 'open-uri' | |
SUBSCRIPTION_ID = 'xxx' | |
PRO_MEDIA_LINK_PREFIX = "http://media.railscasts.com/assets/subscriptions/#{SUBSCRIPTION_ID}/videos/" | |
MEDIA_LINK_PREFIX = 'http://media.railscasts.com/assets/episodes/videos/' | |
EPISODES_API_ENDPOINT = 'http://www.railscasts.com/episodes.json' | |
MEDIA_TYPE = "webm" | |
TARGET_DIRECTORY = '.' | |
def parse_json_uri uri | |
result = nil | |
open(uri, "rb") do | file | | |
result = JSON.parse file.read | |
end | |
result | |
end | |
puts "Checking railscasts feeds for new episodes..." | |
episodes = parse_json_uri EPISODES_API_ENDPOINT | |
puts "Total episodes: #{episodes.count}" | |
downloaded_ids = Dir.new(TARGET_DIRECTORY).entries.select{ |f| f =~ Regexp.new("^(\\d){3}.*.#{MEDIA_TYPE}") }.collect{ |f| f.split('-').first.to_i } | |
puts "Downloaded #{downloaded_ids.count} episode(s)" | |
new_id_count = 0 | |
episodes.reject!{ |episode| downloaded_ids.include? episode['position'] } | |
puts "To download: #{episodes.count} episode(s)" | |
episodes.each_with_index do |episode, index| | |
filename = "#{"%03d" % episode['position']}-#{episode['permalink']}.#{MEDIA_TYPE}" | |
if episode['pro'] == true | |
media_link = "#{PRO_MEDIA_LINK_PREFIX}#{filename}" | |
else | |
media_link = "#{MEDIA_LINK_PREFIX}#{filename}" | |
end | |
puts "Downloading #{media_link}... (#{index + 1}/#{episodes.count})" | |
begin | |
open("#{TARGET_DIRECTORY}/#{filename}", "wb") do |output_file| | |
open(media_link, "rb") do |input_file| | |
output_file << input_file.read | |
end | |
end | |
rescue | |
File.remove "#{TARGET_DIRECTORY}/#{filename}" | |
exit 1 | |
end | |
new_id_count = new_id_count + 1 | |
end | |
puts "Done. #{new_id_count} new episodes were downloaded" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment