Class: HTML::Pipeline::Gitlab::GitlabEmailImageFilter

Inherits:
Filter
  • Object
show all
Defined in:
lib/html/pipeline/gitlab/gitlab_email_image_filter.rb

Overview

HTML filter that replaces linked images with inline images in emails.

Instance Method Summary collapse

Instance Method Details

#base64_encode_image(file_path) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/html/pipeline/gitlab/gitlab_email_image_filter.rb', line 30

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

#callObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/html/pipeline/gitlab/gitlab_email_image_filter.rb', line 11

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

#get_file_path(url, upload_path, base_url) ⇒ Object



46
47
48
49
50
51
# File 'lib/html/pipeline/gitlab/gitlab_email_image_filter.rb', line 46

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

#prevent_path_traversal(file_path) ⇒ Object



53
54
55
56
57
58
59
60
61
# File 'lib/html/pipeline/gitlab/gitlab_email_image_filter.rb', line 53

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