Sha256: 77d3f4b04f4658fc769d03568a645281cd3e5736ef6ba34ee1f3877162a36418

Contents?: true

Size: 1.86 KB

Versions: 21

Compression:

Stored size: 1.86 KB

Contents

module Onebox
  class Preview
    attr_reader :cache

    # see https://bugs.ruby-lang.org/issues/14688
    client_exception = defined?(Net::HTTPClientException) ? Net::HTTPClientException : Net::HTTPServerException
    WEB_EXCEPTIONS ||= [client_exception, OpenURI::HTTPError, Timeout::Error, Net::HTTPError, Errno::ECONNREFUSED]

    def initialize(link, parameters = Onebox.options)
      @url = link
      @options = parameters
      @cache = options.cache
      @engine_class = Matcher.new(@url).oneboxed
    end

    def to_s
      return "" unless engine
      sanitize process_html engine_html
    rescue *WEB_EXCEPTIONS
      ""
    end

    def placeholder_html
      return "" unless engine
      sanitize process_html engine.placeholder_html
    rescue *WEB_EXCEPTIONS
      ""
    end

    def options
      OpenStruct.new(@options)
    end

    private

    def engine_html
      engine.to_html
    end

    def process_html(html)
      return "" unless html

      if @options[:max_width]
        doc = Nokogiri::HTML::fragment(html)
        if doc
          doc.css('[width]').each do |e|
            width = e['width'].to_i

            if width > @options[:max_width]
              height = e['height'].to_i
              if (height > 0)
                ratio = (height.to_f / width.to_f)
                e['height'] = (@options[:max_width] * ratio).floor
              end
              e['width'] = @options[:max_width]
            end
          end
          return doc.to_html
        end
      end

      html
    end

    def sanitize(html)
      Sanitize.fragment(html, @options[:sanitize_config] || Sanitize::Config::ONEBOX)
    end

    def engine
      return nil unless @engine_class
      return @engine if @engine

      @engine = @engine_class.new(@url, cache)
      @engine.options = @options
      @engine
    end

    class InvalidURI < StandardError; end
  end
end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
onebox-1.8.89 lib/onebox/preview.rb
onebox-1.8.88 lib/onebox/preview.rb
onebox-1.8.87 lib/onebox/preview.rb
onebox-1.8.86 lib/onebox/preview.rb
onebox-1.8.85 lib/onebox/preview.rb
onebox-1.8.84 lib/onebox/preview.rb
onebox-1.8.83 lib/onebox/preview.rb
onebox-1.8.82 lib/onebox/preview.rb
onebox-1.8.81 lib/onebox/preview.rb
onebox-1.8.80 lib/onebox/preview.rb
onebox-1.8.79 lib/onebox/preview.rb
onebox-1.8.78 lib/onebox/preview.rb
onebox-1.8.77 lib/onebox/preview.rb
onebox-1.8.76 lib/onebox/preview.rb
onebox-1.8.75 lib/onebox/preview.rb
onebox-1.8.74 lib/onebox/preview.rb
onebox-1.8.73 lib/onebox/preview.rb
onebox-1.8.72 lib/onebox/preview.rb
onebox-1.8.71 lib/onebox/preview.rb
onebox-1.8.70 lib/onebox/preview.rb