DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Youtube Url Code

09.03.2006
| 4611 views |
  • submit to reddit
        This is a part of a ruby-cocoa app I'm writing.
(TubeSock is just terrible)

require 'net/http'
require 'uri'

class YouTubeMovie
  attr_accessor :viewer_url, :movie_url, :get_params
  def initialize(url)
    @viewer_url = url
    setMovieURL
  end
  def setMovieURL
    # Get the viewer page html
    req = Net::HTTP::Get.new @viewer_url
    viewer_page = nil
    res = Net::HTTP.start(@viewer_url.host, @viewer_url.port) do |request|
      viewer_page = request.request(req)
    end
    # Extract the required info.
    # in the html there's a line like so:
    # var fo = new SWFObject("/player2.swf?video_id=AUnPDmmnF0U&l=1363&t=OEgsToPDskJUmKC_b_nXO_yUrNLKSY18&nc=13369344", "movie_player", "450", "370", 7, "#FFFFFF");
    # we want to extract the ?video_id=AUnPDmmnF0U&l=1363&t=OEgsToPDskJUmKC_b_nXO_yUrNLKSY18&nc=13369344
    # this regex does that...
    regex = Regexp.new(/\?video_id=[\w]+&l=[\w]+&t=[\w]+&nc=[\d]+/)
    @get_params = regex.match(viewer_page.body).to_s
    @movie_url = URI.parse('http://www.youtube.com/get_video' + @get_params)
    p 'movie url: ' + @movie_url.to_s
  end
end