Created
December 10, 2012 18:49
-
-
Save cbojar/4252476 to your computer and use it in GitHub Desktop.
A ruby script to calculate the total amount of time of all videos on a YouTube channel.
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/ruby | |
## | |
# This script will calculate the total time for all videos on a user's channel | |
# It pulls from the channel's RSS feeds automatically, but is not particularly | |
# robust as it semi-scrapes out the time from the content area. | |
# | |
# (c) CBojar 2012, This is licensed under the MIT license. | |
## | |
require 'optparse' | |
require 'uri' | |
require 'net/http' | |
require 'rexml/document' | |
options = {} | |
optparser = OptionParser.new do |opts| | |
opts.banner = "Usage: yt-channel-time.rb [options] <channel_name>" | |
options[:verbose] = false | |
opts.on( '-v', '--verbose', 'Turn on verbose output' ) do | |
options[:verbose] = true | |
end | |
opts.on( '-h', '--help', 'Display this screen' ) do | |
puts opts | |
exit | |
end | |
end | |
optparser.parse! | |
channel = ARGV[0] | |
if channel.nil? | |
puts "Channel name required." | |
exit 1 | |
end | |
time = 0 | |
videos = 0 | |
url = "http://gdata.youtube.com/feeds/base/users/#{channel}/uploads?alt=atom&v=2&orderby=published" | |
puts "Fetching YouTube channel feed for #{channel}..." | |
while true | |
puts "Fetching #{url}" if options[:verbose] | |
response = Net::HTTP.get_response(URI.parse(url)) | |
break if response.code != '200' | |
atom = REXML::Document.new(response.body) | |
atom.elements.each('/feed/entry/content') do |content| | |
videos += 1 | |
content.to_s.scan(/((?:[0-9]{2}:){1,2}[0-9]{2})</) do |match| | |
match = match[0] | |
time += (match.slice -2..-1).to_i | |
time += (match.slice -5..-4).to_i * 60 | |
time += (match.slice -8..-7).to_i * 3600 | |
end | |
end | |
link = atom.elements.to_a('/feed/link[@rel=\'next\']')[0] | |
break if link.nil? | |
url = link.attribute('href').to_s.gsub /&/, '&' | |
sleep 1 | |
end | |
hours = (time / 3600).floor | |
time -= hours * 3600 | |
minutes = (time / 60).floor | |
time -= minutes * 60 | |
seconds = time | |
puts "#{videos} videos: #{hours} hours, #{minutes} minutes, #{seconds} seconds." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment