Skip to content

Instantly share code, notes, and snippets.

@Gargron
Last active December 30, 2015 23:29
Show Gist options
  • Save Gargron/7900746 to your computer and use it in GitHub Desktop.
Save Gargron/7900746 to your computer and use it in GitHub Desktop.
Configure a list of YouTube channels, and you can run this regularly to download new videos.

Configure a list of YouTube channels, and you can run this regularly to download new videos.

Creates .check-youtube folder in the user's home directory, where configuration and videos are stored. Example config.yml:

channels:
  - bluexephos
  - YogscastSips

Uses Ruby and the YouTube DL command-line utility.

#! /usr/bin/ruby
require 'rubygems'
require 'json'
require 'open-uri'
require 'yaml'
require 'pty'
dir = Dir.home() + '/.check-youtube'
config = {'channels' => [], 'left_off_at' => {}}
config_file = dir + '/config.yml'
# Create folder if it doesn't exist
unless File.directory?(dir)
`mkdir #{dir}`
`mkdir #{dir}/videos`
File.open(config_file, 'w') do |file|
file.puts YAML::dump(config)
end
end
# Load configuration and old data
config = YAML::load(File.open(config_file))
channels = config['channels'] || []
json_url = 'https://gdata.youtube.com/feeds/base/users/%s/uploads?alt=json&orderby=published'
left_off_at = config['left_off_at'] || {}
new_videos_urls_total = []
# Check channels for new videos
channels.each do |channel|
channel_json_url = json_url % channel
videos = JSON.parse(open(channel_json_url).read)
new_videos_urls = []
videos['feed']['entry'].each do |video|
if left_off_at.has_key?(channel) && video['id']['$t'] == left_off_at[channel]
break
end
new_videos_urls << video['id']['$t']
end
if new_videos_urls.length > 0
left_off_at[channel] = new_videos_urls.first
new_videos_urls_total.concat new_videos_urls
end
end
# Download new videos to folder
puts "Need to download %d videos" % new_videos_urls_total.length
new_videos_urls_total.each do |url|
id = url.scan(/\/([^\/]+)\Z/).first.first
puts "Working on #{id}..."
# Download using youtube_dl
begin
PTY.spawn("youtube-dl --newline https://www.youtube.com/watch?v=#{id} -o \"#{dir}/videos/%(upload_date)s.%(title)s.%(ext)s\"") do |stdin, stdout, pid|
begin
# Output command progress in real-time
stdin.each { |line| print line }
rescue Errno::EIO
end
end
rescue PTY::ChildExited
"Done"
end
end
# Save updated configuration
File.open(config_file, 'w') do |file|
file.puts YAML::dump(config)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment