kylejginavan / youtube_it

An object-oriented Ruby wrapper for the YouTube GData API
http://groups.google.com/group/ruby-youtube-library
595 stars 223 forks source link

Getting videos from all pages #105

Closed mcasimir closed 11 years ago

mcasimir commented 12 years ago

Is there a smarter/default way to do this?

class YouTubeIt::Client
  def all_videos_by(*args)
    page = videos_by(*args)
    videos = page.videos

    while page = page.next_page
      videos += page.videos
    end

    videos
  end
end
chebyte commented 12 years ago

this looks fine for me, maybe we could add this method to the api

mcasimir commented 12 years ago

Well, thank you, anyway the example i submitted above is wrong.

In the end i've patched YouTubeIt::Client like that:

class YouTubeIt::Client

  def get_videos(opts)

    page = videos_by(opts.merge({:page => 1}))
    videos = page.videos

    while page.next_page && (page = videos_by(opts.merge({:page => page.next_page})) || true)
      videos += page.videos
    end

    videos
  end

  def get_page(*args)
    videos_by(*args).videos
  end

end

where get_videos returns all the videos, while get_page get only a page of results.

Let me go a little off topic here. Thanks to your library I just completed a job that involved youtube integration. Here is another patch to your code i've used. It returns the download stream url for a video. Probably I will not use youtube_it for a while, anyway i would like to share that patch with you, feel free to integrate it in your Gem if you wish.

class YouTubeIt::Model::Video

  class PlaybackInfo
    attr_accessor :mime, :url
  end

  def uid
    unique_id
  end

  def playback
    unless @playback_info
      playback_hash = get_video_download_url(self.uid)
      @playback_info = PlaybackInfo.new()
      @playback_info.url = playback_hash[:url]
      @playback_info.mime = playback_hash[:mime]
    end
    @playback_info
  end

  private

  def get_video_download_url(video_id)
    video_info = CGI.parse(open("http://www.youtube.com/get_video_info?&video_id=#{video_id}").read)
    video_info["url_encoded_fmt_stream_map"]

    uri_str = CGI.parse(video_info["url_encoded_fmt_stream_map"].first)["url"].first
    uri = URI.parse(uri_str)
    res = {}

    Net::HTTP.start(uri.host, uri.port) {|http|
      res = http.head(uri.request_uri)
    }

    mime     = res['content-type']
    {:url => uri_str, :mime => mime}
  end

end
chebyte commented 12 years ago

thanks for the changes I going to add these tomorrow!