Sha256: 876c803cb12a4a42e659fb3ac30c71c8583ffae10f66a6972d9c7b79d9804a76

Contents?: true

Size: 1.57 KB

Versions: 3

Compression:

Stored size: 1.57 KB

Contents

module Onebox
  module Engine
    class YoutubeOnebox
      include Engine
      include StandardEmbed

      matches_regexp(/^https?:\/\/(?:www\.)?(?:m\.)?(?:youtube\.com|youtu\.be)\/.+$/)

      # Try to get the video ID. Works for URLs of the form:
      # * https://www.youtube.com/watch?v=Z0UISCEe52Y
      # * http://youtu.be/afyK1HSFfgw
      # * https://www.youtube.com/embed/vsF0K3Ou1v0
      def video_id
        match = @url.match(/^https?:\/\/(?:www\.)?(?:m\.)?(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_\-]{11})$/)
        match && match[1]
      end

      def placeholder_html
        if video_id
          "<img src='http://i1.ytimg.com/vi/#{video_id}/hqdefault.jpg' width='480' height='270'>"
        else
          to_html
        end
      end

      def to_html
        if video_id
          # Avoid making HTTP requests if we are able to get the video ID from the
          # URL.
          html = "<iframe width=\"480\" height=\"270\" src=\"https://www.youtube.com/embed/#{video_id}?feature=oembed\" frameborder=\"0\" allowfullscreen></iframe>"
        else
          # Fall back to making HTTP requests.
          html = raw[:html] || ""
        end

        rewrite_agnostic(append_params(html))
      end

      def append_params(html)
        result = html.dup
        result.gsub! /(src="[^"]+)/, '\1&wmode=opaque'
        if url =~ /t=(\d+)/
          result.gsub! /(src="[^"]+)/, '\1&start=' + Regexp.last_match[1]
        end
        result
      end

      def rewrite_agnostic(html)
        html.gsub(/https?:\/\//, '//')
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
onebox-1.3.6 lib/onebox/engine/youtube_onebox.rb
onebox-1.3.5 lib/onebox/engine/youtube_onebox.rb
onebox-1.3.4 lib/onebox/engine/youtube_onebox.rb