ニコニコ動画 削除された動画を視聴する

最新 → NicoProxy ニコニコ動画SP1に対応しました - unnecessary words

nico_proxy機能追加。
削除された動画のキャッシュがあれば視聴できるように変更。
キャッシュ呼ぶだけなので変なアクセスはしないです。あくまで一度視聴してキャッシュを保持してないと駄目。flvplayerの仕様変更されると簡単に使えなくなりそう。
詳しい使い方とWindows用バイナリは、こちらを参照。

#!/usr/bin/ruby
require 'webrick/httpproxy'

class NicoProxyServer < WEBrick::HTTPProxyServer
  def service(req, res)
    if req.unparsed_uri =~ %r!http://.*\.nicovideo\.jp/smile\?v=(.*)!
      id = $1
      f_name = "sm#{id.split('.')[0]}.flv"
      if File.exist?(f_name)
        STDERR << "LOCAL FILE: #{f_name}\n"
        open(f_name, "r"){|io| io.binmode; res.body = io.read}
      else
        super(req, res)
      end
    else
      super(req, res)
    end
  end
end

handler = Proc.new() do |req, res|
  if req.unparsed_uri =~ %r!http://.*\.nicovideo\.jp/smile\?v=(.*)!
    id = $1
    f_name = "sm#{id.split('.')[0]}.flv"
    if id =~ /low$/
      # エコノミーモード
      if File.exist?(f_name)
        open(f_name, "r"){|io| io.binmode; res.body = io.read}
        res.header.delete("content-length")
      end
    else
      # 通常モード
      if !File.exist?(f_name) || File.size(f_name) < res.header["content-length"].to_i
        open(f_name, "w"){|io| io.binmode; io.write(res.body)}
        STDERR << "FILE SAVE: #{f_name}\n"
      end
    end
  elsif req.unparsed_uri =~ %r!http://www\.nicovideo\.jp/api/getflv\?v=sm(.*)!
    s_id = $1
    f_name = "sm#{s_id}.flv"
    if File.exist?(f_name) && res.body.split('&').any?{|item| item =~ /^deleted=/}
      # 動画削除時にキャッシュがあれば取得する
      STDERR << "FILE DELETED --> RECOVER: #{f_name}\n"
      pattern = /url=http%3A%2F%2F.*\.nicovideo\.jp%2Fsmile%3Fv%3D.*?&/
      replace = "url=http%3A%2F%2Flocal.nicovideo.jp%2Fsmile%3Fv%3D#{s_id}.00000&"
      res.body.gsub!(pattern, replace)
    end
  end
end

config = {
  :BindAddress => '0.0.0.0',
  :Port => 8080,
  :ProxyContentHandler => handler,
}

s = NicoProxyServer.new(config)
[:INT, :TERM].each{|sig| Signal.trap(sig){s.shutdown}}
s.start