Sha256: 7a3d8eb4ce3cbf0eaf6db2494ed6163904e787ce35411e0acf766db0e3359405

Contents?: true

Size: 1.4 KB

Versions: 7

Compression:

Stored size: 1.4 KB

Contents

module Onebox
  module Engine
    module StandardEmbed

      def raw
        return @raw if @raw
        response = fetch_response(url)

        html_doc = Nokogiri::HTML(response.body)

        # Determine if we should use OEmbed or OpenGraph
        oembed_alternate = html_doc.at("//link[@type='application/json+oembed']") || html_doc.at("//link[@type='text/json+oembed']")
        if oembed_alternate
          # If the oembed request fails, we can still try the opengraph below.
          begin
            @raw = Onebox::Helpers.symbolize_keys(::MultiJson.load(fetch_response(oembed_alternate['href']).body))
          rescue Errno::ECONNREFUSED, Net::HTTPError, MultiJson::LoadError
            @raw = nil
          end
        end

        open_graph = OpenGraph.new(response.body, false)
        if @raw
          @raw[:image] = open_graph.images.first if @raw[:image].nil? && open_graph && open_graph.images

          return @raw
        end

        @raw = open_graph
      end

      private

      def fetch_response(location, limit = 3)
        raise Net::HTTPError.new('HTTP redirect too deep', location) if limit == 0

        response = Net::HTTP.get_response(URI(location))
        case response
        when Net::HTTPSuccess     then response
        when Net::HTTPRedirection then fetch_response(response['location'], limit - 1)
        else
          response.error!
        end
      end

    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
onebox-1.2.6 lib/onebox/engine/standard_embed.rb
onebox-1.2.5 lib/onebox/engine/standard_embed.rb
onebox-1.2.4 lib/onebox/engine/standard_embed.rb
onebox-1.2.3 lib/onebox/engine/standard_embed.rb
onebox-1.2.2 lib/onebox/engine/standard_embed.rb
onebox-1.2.1 lib/onebox/engine/standard_embed.rb
onebox-1.2.0 lib/onebox/engine/standard_embed.rb