[ruby] ruby with mechanizeでニコニコ動画のダウンローダーを作ってみた
まずはmechanizeをインストール
$ sudo gem install mechanize -y
で、スクリプトがこんな感じ
require 'yaml' require 'rubygems' require 'mechanize' require 'uri' require 'tempfile' class NicoVideo attr_reader :email, :password AGENT_ALIAS = 'Linux Mozilla' def initialize(*args) case args.length when 1 fname = args[0] raise unless File.exists?(fname) YAML.load_file(fname).each do |sym, value| instance_variable_set('@' + sym, value) end end @agent = WWW::Mechanize.new @agent.user_agent = AGENT_ALIAS end def login @agent.post("https://secure.nicovideo.jp/secure/login?site=niconico", {'email' => @email, 'password' => @password}) @login = true end def login? @login end def get_flv(id) Video.new(id) api = { } URI.decode(@agent.get("http://www.nicovideo.jp/api/getflv?v=" + id).body).split('&').each do |query| query =~ /^([^=]+)=(.+)/ api[$1.to_sym] = $2 end @agent.get("http://www.nicovideo.jp/watch/#{id}") dir = "/tmp/nicovideo" Dir.mkdir dir unless File.exists?(dir) path = "#{dir}/#{id}.flv" File.open(path, 'w') do |f| f.write @agent.get(api[:url]).body end unless File.exists?(path) Video.new(path) end class Video attr_reader :tmpfile def initialize(path) @tmpfile = path end end end if $0 == __FILE__ NicoVideo.new(File.expand_path(File.dirname(__FILE__) + '/account.yml')).get_flv(ARGV[0]) end
使いかたはnicovideo.rbと同じディレクトリにaccount.ymlというファイル名で
email: account@hostname.net password: hogepassword
アカウントの設定を書いて
$ ruby nicovideo.rb [video_id]
こんな感じ。
このあとipodで見れるように変換とかするようにしようと思ってるところ。
追記: ちょっと修正しました。
http://d.hatena.ne.jp/rudeboyjet/20071126/p1