summaryrefslogtreecommitdiff
path: root/lib/banzai/filter/upload_link_filter.rb
blob: c0f503c9af3a859153d94da6a70fd8570d18da38 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
require 'uri'

module Banzai
  module Filter
    # HTML filter that "fixes" relative upload links to files.
    # Context options:
    #   :project (required) - Current project
    #
    class UploadLinkFilter < HTML::Pipeline::Filter
      def call
        return doc unless project

        doc.search('a').each do |el|
          process_link_attr el.attribute('href')
        end

        doc.search('img').each do |el|
          process_link_attr el.attribute('src')
        end

        doc
      end

      protected

      def process_link_attr(html_attr)
        return if html_attr.blank?

        uri = html_attr.value
        if uri.starts_with?("/uploads/")
          html_attr.value = build_url(uri).to_s
        end
      end

      def build_url(uri)
        File.join(Gitlab.config.gitlab.url, project.path_with_namespace, uri)
      end

      def project
        context[:project]
      end

      # Ensure that a :project key exists in context
      #
      # Note that while the key might exist, its value could be nil!
      def validate
        needs :project
      end
    end
  end
end