Ruby

ニコニコ動画ダウンロードするやつ

More than 5 years have passed since last update.

# -- coding: utf-8

require "rubygems"
require "grill"

Grill.implant <<-G
source :rubygems

gem "mechanize"
gem "nokogiri"
gem "trollop"
G

ID="mail@example.com"
PW="password"

opts = Trollop.options do
opt :dir, "save dir", :default => File.expand_path("../", __FILE__)
end

agent = Mechanize.new
agent.post("https://secure.nicovideo.jp/secure/login?site=niconico", "mail" => ID, "password" => PW)

ARGV.each do |url_or_id|
id = url_or_id[%r![^/]+$!]
# for get nicohistory cookie
# http://www.trinity-site.net/blog/?p=225
agent.get("http://www.nicovideo.jp/watch/#{id}")

s = agent.post('http://flapi.nicovideo.jp/api/getflv', :v => id)
result = Hash[URI.decode_www_form s.body]
video_url = result["url"]
ext = case video_url[/smile\?(.)=/, 1]
when "m"; "mp4"
when "s"; "swf"
else "flv"
end
title = (Nokogiri::HTML.parse agent.get(result["link"]).body).at_css('.video_title').text
# ダメ文字全角化 http://ja.wikipedia.org/wiki/%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E5%90%8D
title = title.gsub(/[\/\\?*:|><]/) {|m| [m.ord + 65248].pack('U*')}

cookie = agent.cookies.map(&:to_s).join("; ")
save_path = "#{opts[:dir]}/#{id}-#{title}.#{ext}"
cmd = %Q!wget -c -O '#{save_path}' --header="Cookie: #{cookie}" "#{video_url}"!
Process.spawn(cmd)
end

Process.waitall

適当に作ったのでバグってたら各自で直すなりして適当に使ってください。