Sha256: d950e396df1c9ec0b895fcfa8d7bd194cacdaba7dc0c3f4246f2e01857a153e0

Contents?: true

Size: 1.97 KB

Versions: 1

Compression:

Stored size: 1.97 KB

Contents

require 'base64'
require 'RMagick'
require 'html/pipeline/filter'
require 'uri'

module HTML
  class Pipeline
    class Gitlab
      # HTML filter that replaces linked images with inline images in emails.
      class GitlabEmailImageFilter < Filter
        def call
          doc.search('img').each do |img|
            next if img['src'].nil?

            src = img['src'].strip
            next unless src.start_with?(context[:base_url])

            file_path =
              get_file_path(src, context[:upload_path], context[:base_url])
            next unless File.file?(file_path)
            encoded_image = base64_encode_image(file_path)
            next unless encoded_image.present?

            img['src'] = encoded_image
          end

          doc
        end

        def base64_encode_image(file_path)
          img = Magick::Image.read(file_path).first
          # Strip profiles and comments from file
          img.strip!
          if img.filesize > 100_000
            img.format = 'JPG'
            # Resize it to be maximum 600px * 600px.
            img.resize_to_fit!(600, 600)
            encoded_image = Base64.encode64(img.to_blob { self.quality = 60 })
          else
            encoded_image = Base64.encode64(img.to_blob)
          end

          "data:image/jpg;base64,#{encoded_image}"
        end

        def get_file_path(url, upload_path, base_url)
          # replace base url with location in file system
          url.gsub!(base_url, '')
          file_path = prevent_path_traversal(url)
          File.join(upload_path, file_path)
        end

        def prevent_path_traversal(file_path)
          # decode the url. We don't want encoded chars in our file path
          file_path = URI.decode(file_path).to_s
          # remove all occurences of ".." from the url
          # to prevent path traversing
          file_path = file_path.gsub('..', '')
          # replace unnecessary double slashes
          file_path.gsub('//', '/')
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
html-pipeline-gitlab-0.1.6 lib/html/pipeline/gitlab/gitlab_email_image_filter.rb