5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ニコ動のタイトルやサムネ画像URLを取得したりとか

Last updated at Posted at 2012-04-28
#!/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

  class TEST_NicoVideo
    include NicoVideo

    def test
      puts getthumbinfo(:sm9).title
    end
  end

  TEST_NicoVideo.new.test
end

XMLなんかマトモにパースしない。
Struct の使い方がイケテナイ気がするけど…
Ruby1.9系ならinjectの代わりにeach_with_objectの方が便利と、
というか、injectは本来の趣旨と、この使い方とは違っているような気もする

5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?