Sha256: 780dac6b0858a0d594a933b53ca5e49f190e40a6df59ce181fd4ea7c84840920

Contents?: true

Size: 1.82 KB

Versions: 3

Compression:

Stored size: 1.82 KB

Contents

require 'viddl-rb'
require 'typhoeus'
require 'wgif/download_bar'
require 'wgif/exceptions'
require 'wgif/video'
require 'wgif/video_cache'
require 'uri'
require 'cgi'

module WGif
  class Downloader

    def initialize
      @cache = WGif::VideoCache.new
    end

    def video_url youtube_url
      begin
        urls = ViddlRb.get_urls(youtube_url)
        urls.first
      rescue
        raise WGif::VideoNotFoundException
      end
    end

    def video_id youtube_url
      begin
        uri = URI(youtube_url)
        params = CGI.parse(uri.query)
        params['v'].first
      rescue
        raise WGif::InvalidUrlException
      end
    end

    def get_video youtube_url
      id = video_id youtube_url
      if cached_clip = @cache.get(id)
        return cached_clip
      else
        temp = load_clip(id, youtube_url)
        video = WGif::Video.new(id, temp.path)
        video
      end
    end

    private

    def create_progress_bar request, output_file
      size = nil
      download_bar = WGif::DownloadBar.new

      request.on_headers do |response|
        size = response.headers['Content-Length'].to_i
        download_bar.update_total(size)
      end

      request.on_body do |chunk|
          output_file.write(chunk)
          download_bar.increment_progress(chunk.size)
      end
    end

    def request_clip youtube_url, output_file
      clip_url = self.video_url youtube_url
      request = Typhoeus::Request.new clip_url
      create_progress_bar(request, output_file)
      request.run
    end

    def load_clip id, youtube_url
      FileUtils.mkdir_p "/tmp/wgif"
      temp = File.open("/tmp/wgif/#{id}", 'wb')
      begin
        clip = request_clip(youtube_url, temp)
        raise WGif::VideoNotFoundException unless clip.response_code == 200
      ensure
        temp.close
      end
      temp
    end

  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
wgif-0.2.0 lib/wgif/downloader.rb
wgif-0.0.1 lib/wgif/downloader.rb
wgif-0.0.1.pre lib/wgif/downloader.rb