Sha256: 033b8a0697dbed1628e35d7c5c2e31a103aeceec4bdb7b9896a1f532d67a8793

Contents?: true

Size: 1.77 KB

Versions: 2

Compression:

Stored size: 1.77 KB

Contents

require 'base64'
require 'mime-types'
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)
          mime_type = MIME::Types.type_for(file_path).first
          return nil if mime_type.nil?

          content_type = mime_type.content_type
          img = File.read(file_path)
          encoded_image = Base64.encode64(img)
          "data:#{content_type};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

2 entries across 2 versions & 1 rubygems

Version Path
html-pipeline-gitlab-0.2.0 lib/html/pipeline/gitlab/gitlab_email_image_filter.rb
html-pipeline-gitlab-0.1.7 lib/html/pipeline/gitlab/gitlab_email_image_filter.rb