Skip to content

Instantly share code, notes, and snippets.

@mugyu
Created February 25, 2012 13:09
Show Gist options
  • Save mugyu/1908429 to your computer and use it in GitHub Desktop.
Save mugyu/1908429 to your computer and use it in GitHub Desktop.
Rubyでニコ動のタイトルやサムネ画像URLを取得したりとか
#!/usr/bin/env ruby
# vim: fileencoding=utf-8
require 'open-uri'
module NicoVideo
GETTHUMBINFO_URL = "http://ext.nicovideo.jp/api/getthumbinfo"
OK_STRING = %q|<nicovideo_thumb_response status="ok">|
FAIL_STRING = %q|<nicovideo_thumb_response status="fail">|
ELEMENTS = [:title,
:description,
:thumbnail_url,
:watch_url]
THUMBINFO = Struct.new(*ELEMENTS)
def getthumbinfo(video_id)
doc = open("#{GETTHUMBINFO_URL}/#{video_id}"){|f|f.read}
if /#{OK_STRING}/ =~ doc
ELEMENTS.inject(THUMBINFO.new) do |result, element|
result[element] = doc.slice(%r|<#{element}>(.+?)</#{element}>|, 1)
result
end
# Ruby1.9系なら下記のコード
# ELEMENTS.each_with_object(THUMBINFO.new) do |element, obj|
# obj[element] = doc.slice(%r|<#{element}>(.+?)</#{element}>|, 1)
# end
else
false
end
end
module_function :getthumbinfo
end
if $0 == __FILE__
sm9 = NicoVideo.getthumbinfo(:sm9)
puts sm9.title #=> 新・豪血寺一族 -煩悩解放 - レッツゴー!陰陽師
puts sm9.description #=> レッツゴー!陰陽師(フルコーラスバージョン)
puts sm9.thumbnail_url #=> http://tn-skr2.smilevideo.jp/smile?i=9
puts sm9.watch_url #=> http://www.nicovideo.jp/watch/sm9
p NicoVideo.getthumbinfo(:smX) #=> false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment