#!/usr/bin/env ruby # # Author: IKARASHI Yoshinori # Createed: 2006-07-07 22:41:38 # Modified: 2006-07-11 07:22:12 # # ** Based on http://hanagasira.s25.xrea.com/php/video.php # require 'uri' require 'net/http' require 'open-uri' require 'progressbar' require 'nkf' def filename_locale_encoding nkf_encoding_option = '-e' # default begin charmap = `locale -k charmap` rescue charmap = 'charmap="EUC-JP"' # also default end if charmap =~ /charmap=\"([^\"]+)\"/ case $1 when "UTF-8" nkf_encoding_option = '-w' when "SJIS", "Shift_JIS" nkf_encoding_option = '-s' when "JIS" nkf_encoding_option = '-j' when "EUC-JP" nkf_encoding_option = '-e' end end return nkf_encoding_option end def youtube_download_uri(url_string) uri=URI.parse(url_string) video_id = '' if /\/v\/([^&]+)&?/ =~ uri.path video_id = $1 elsif /v=([^&]+)&?/ =~ uri.query video_id = $1 else raise "no video_id found" end filename = video_id + '.flv' page = timeout(10) do uri.open do |f| f.read end end nkf_option = filename_locale_encoding() if /]*>(.+)<\/title>/i =~ page filename = NKF.nkf(nkf_option, $1.gsub(/\n/, '')).gsub(/YouTube - ?/, ''). gsub(/^\s+/, '').gsub(/ /, '_').gsub(/\//, '_') + '.flv' end redirect_url = '' Net::HTTP.start(uri.host, 80) do |http| r= http.get("/watch_video?v=#{video_id}") redirect_url = r["location"] # if r == Net::HTTPRedirection end query = Hash.new('') redirect_url.split(/\?/,2)[1].split(/&/).each do |q| key, value = q.split(/=/) query[key] = value end flv_url = "#{uri.scheme}://#{uri.host}/get_video?video_id=#{query['video_id']}&t=#{query['t']}" return flv_url, filename end def get_content(download_url, filename) pbar = nil open(filename, "w") do |file| open(download_url, :content_length_proc => lambda {|t| if t && 0 < t pbar = ProgressBar.new(filename, t) pbar.file_transfer_mode end }, :progress_proc => lambda {|s| pbar.set s if pbar }) do |f| file.puts f.read end end return filename end def usage puts "usage: getmovie [url]" puts " * url should contain video_id ( v=... or /v/... )" exit end if $0 == __FILE__ url = ARGV.shift usage unless url puts "opening #{url}" begin download_uri, filename = youtube_download_uri(url) if (FileTest.exist?(filename)) puts "#{filename} already exists." exit end puts "download movie file: #{filename}" get_content(download_uri, filename) rescue p $!, $@ end end