thuai
6/12/2015 - 3:17 AM

WWDC_2015_downloader.rb

WWDC_2015_downloader.rb

require 'rubygems'
require 'mechanize'
 
if  !((ARGV[0] == 'SD' || ARGV[0] == 'HD' || ARGV[0] == 'ALL') && ARGV.size == 1)
	puts %q{Usage: ruby WWDC_2015_downloader.rb SD | HD | ALL}
	puts %q{Example: ruby  WWDC_2015_downloader.rb SD	- to download all SD videos}
	puts %q{Example: ruby  WWDC_2015_downloader.rb HD	- to download all HD videos}
	puts %q{Example: ruby  WWDC_2015_downloader.rb ALL	- to download videos in all resolutions}
	exit
end

needs_download_SD_videos = ARGV[0] == 'SD' || ARGV[0] == 'ALL'
needs_download_HD_videos = ARGV[0] == 'HD' || ARGV[0] == 'ALL'

agent = Mechanize.new
agent.user_agent_alias = 'Mac Safari'

agent.get('https://developer.apple.com/videos/wwdc/2015/') do |page|
	all_download_page_links = page.links_with(href: /\?id=\d{3}/).uniq! { |link| link.href }
	
	agent.redirect_ok = false
	
	all_download_page_links.each { |link|
		download_page = agent.click(link)
		
		video_link_SD = download_page.link_with(:text => /SD/)
		video_link_HD = download_page.link_with(:text => /HD/)
		
		file_regexp = /\d{3}_\w*\.mp4/
		
		video_file_path_SD = file_regexp.match(video_link_SD.href).to_s
		aria2_file_path_SD = video_file_path_SD + ".aria2"
		video_file_path_HD = file_regexp.match(video_link_HD.href).to_s
		aria2_file_path_HD = video_file_path_HD + ".aria2"
		
		did_SD_video_download = File.exist?(video_file_path_SD) && !File.exist?(aria2_file_path_SD)
		did_HD_video_download = File.exist?(video_file_path_HD) && !File.exist?(aria2_file_path_HD)
		
		should_download_SD_video = !did_SD_video_download && needs_download_SD_videos
		should_download_HD_video = !did_HD_video_download && needs_download_HD_videos
		
		if should_download_SD_video
    		system %Q{aria2c -c -s10 -x10 #{video_link_SD.href}}
		end
		
		if should_download_HD_video
    		system %Q{aria2c -c -s10 -x10 #{video_link_HD.href}}
		end
		
	}
end