Class: InlineUploads

Inherits:
Object
  • Object
show all
Defined in:
app/services/inline_uploads.rb

Constant Summary collapse

PLACEHOLDER =
"__replace__"
PATH_PLACEHOLDER =
"__replace_path__"

Class Method Summary collapse

Class Method Details

.match_anchor(markdown, external_href: false) ⇒ Object



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'app/services/inline_uploads.rb', line 187

def self.match_anchor(markdown, external_href: false)
  markdown.scan(%r{((<a[^<]+>)([^<\a>]*?)</a>)}i) do |match|
    node = Nokogiri::HTML5.fragment(match[0]).children[0]
    href = node.attributes["href"]&.value

    if href && (external_href || matched_uploads(href).present?)
      has_attachment = node.attributes["class"]&.value
      index = $~.offset(0)[0]
      text = match[2].strip.gsub("\n", "").gsub(/ +/, " ")
      text = "#{text}|attachment" if has_attachment

      yield(match[0], href, +"[#{text}](#{PLACEHOLDER})", index) if block_given?
    end
  end
end

.match_bbcode_img(markdown, external_src: false) ⇒ Object



166
167
168
169
170
171
172
# File 'app/services/inline_uploads.rb', line 166

def self.match_bbcode_img(markdown, external_src: false)
  markdown.scan(%r{(\[img\]\s*([^\[\]\s]+)\s*\[/img\])}i) do |match|
    if (external_src || (matched_uploads(match[1]).present?)) && block_given?
      yield(match[0], match[1], +"![](#{PLACEHOLDER})", $~.offset(0)[0])
    end
  end
end

.match_img(markdown, external_src: false, uploads: nil) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'app/services/inline_uploads.rb', line 203

def self.match_img(markdown, external_src: false, uploads: nil)
  markdown.scan(%r{(<(?!img)[^<>]+/?>)?(\s*)(<img [^>\n]+>)}i) do |match|
    node = Nokogiri::HTML5.fragment(match[2].strip).children[0]
    src = node&.attributes&.[]("src")&.value

    if src && (external_src || matched_uploads(src).present?)
      upload = uploads&.[](src)
      node["src"] = upload&.short_url || PLACEHOLDER

      spaces_before = match[1].present? ? match[1][/ +$/].size : 0
      replacement = +"#{" " * spaces_before}#{node.to_s}"

      yield(match[2], src, replacement, $~.offset(0)[0]) if block_given?
    end
  end
end

.match_md_inline_img(markdown, external_src: false) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
# File 'app/services/inline_uploads.rb', line 153

def self.match_md_inline_img(markdown, external_src: false)
  markdown.scan(/(!?\[([^\[\]]*)\]\(([^\s\)]+)([ ]*['"]{1}[^\)]*['"]{1}[ ]*)?\))/) do |match|
    if (external_src || matched_uploads(match[2]).present?) && block_given?
      yield(
        match[0],
        match[2],
        +"#{match[0].start_with?("!") ? "!" : ""}[#{match[1]}](#{PLACEHOLDER}#{match[3]})",
        $~.offset(0)[0]
      )
    end
  end
end

.match_md_reference(markdown) ⇒ Object



174
175
176
177
178
179
180
181
182
183
184
185
# File 'app/services/inline_uploads.rb', line 174

def self.match_md_reference(markdown)
  markdown.scan(/(\[([^\]]+)\]:([ ]+)(\S+))/) do |match|
    if match[3] && matched_uploads(match[3]).present? && block_given?
      yield(
        match[0],
        match[3],
        +"[#{match[1]}]:#{match[2]}#{Discourse.base_url}#{PATH_PLACEHOLDER}",
        $~.offset(0)[0]
      )
    end
  end
end

.process(markdown, on_missing: nil) ⇒ Object



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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'app/services/inline_uploads.rb', line 10

def self.process(markdown, on_missing: nil)
  markdown = markdown.dup

  match_md_reference(markdown) do |match, src, replacement, index|
    if upload = Upload.get_from_url(src)
      markdown = markdown.sub(match, replacement.sub!(PATH_PLACEHOLDER, "__#{upload.sha1}__"))
    end
  end

  cooked_fragment = Nokogiri::HTML5.fragment(PrettyText.cook(markdown, disable_emojis: true))
  link_occurrences = []

  cooked_fragment.traverse do |node|
    if node.name == "img"
      # Do nothing
    elsif !(
          node.children.count == 1 &&
            (node.children[0].name != "img" && node.children[0].children.blank?)
        ) &&
          !(
            node.name == "a" && node.children.count > 1 &&
              !node_children_names(node).include?("img")
          )
      next
    end

    if seen_link = matched_uploads(node).first
      if (actual_link = (node.attributes["href"]&.value || node.attributes["src"]&.value))
        link_occurrences << { link: actual_link, is_valid: true }
      elsif node.name != "p"
        link_occurrences << { link: seen_link, is_valid: false }
      end
    end
  end

  raw_matches = []

  match_bbcode_img(markdown) do |match, src, replacement, index|
    raw_matches << [match, src, replacement, index]
  end

  match_md_inline_img(markdown) do |match, src, replacement, index|
    raw_matches << [match, src, replacement, index]
  end

  match_img(markdown) do |match, src, replacement, index|
    raw_matches << [match, src, replacement, index]
  end

  match_anchor(markdown) do |match, href, replacement, index|
    raw_matches << [match, href, replacement, index]
  end

  regexps = [
    %r{(https?://[a-zA-Z0-9\./-]+/#{Discourse.store.upload_path}#{UPLOAD_REGEXP_PATTERN})},
  ]

  if Discourse.store.external?
    regexps << /((?:https?:)?#{SiteSetting.Upload.s3_base_url}#{UPLOAD_REGEXP_PATTERN})/
    regexps << /(#{SiteSetting.Upload.s3_cdn_url}#{UPLOAD_REGEXP_PATTERN})/
  end

  regexps.each do |regexp|
    indexes = Set.new

    markdown.scan(/(\n{2,}|\A)#{regexp}$/) do |match|
      if match[1].present? && match[2].present?
        extension = match[2].split(".")[-1].downcase
        index = $~.offset(2)[0]
        indexes << index
        if FileHelper.supported_images.include?(extension)
          raw_matches << [match[1], match[1], +"![](#{PLACEHOLDER})", index]
        else
          raw_matches << [match[1], match[1], +"#{Discourse.base_url}#{PATH_PLACEHOLDER}", index]
        end
      end
    end

    markdown.scan(/^#{regexp}(\s)/) do |match|
      if match[0].present?
        index = $~.offset(0)[0]
        next if !indexes.add?(index)
        raw_matches << [match[0], match[0], +"#{Discourse.base_url}#{PATH_PLACEHOLDER}", index]
      end
    end

    markdown.scan(/\[[^\[\]]*\]: #{regexp}/) do |match|
      indexes.add($~.offset(1)[0]) if match[0].present?
    end

    markdown.scan(/(([\n\s\)\]\<])+)#{regexp}/) do |match|
      if matched_uploads(match[2]).present?
        next if !indexes.add?($~.offset(3)[0])
        index = $~.offset(0)[0]
        raw_matches << [match[2], match[2], +"#{Discourse.base_url}#{PATH_PLACEHOLDER}", index]
      end
    end
  end

  raw_matches
    .sort { |a, b| a[3] <=> b[3] }
    .each do |match, link, replace_with, _index|
      node_info = link_occurrences.shift
      next unless node_info&.dig(:is_valid)

      if link.include?(node_info[:link])
        begin
          uri = URI(link)
        rescue URI::Error
        end

        if !Discourse.store.external?
          host = uri&.host

          hosts = [Discourse.current_hostname]

          if cdn_url = GlobalSetting.cdn_url
            hosts << URI(GlobalSetting.cdn_url).hostname
          end

          next if host && !hosts.include?(host)
        end

        upload = Upload.get_from_url(link)

        if upload
          replace_with.sub!(PLACEHOLDER, upload.short_url)
          replace_with.sub!(PATH_PLACEHOLDER, upload.short_path)
          markdown.sub!(match, replace_with)
        else
          on_missing.call(link) if on_missing
        end
      end
    end

  markdown.scan(/(__(\h{40})__)/) do |match|
    upload = Upload.find_by(sha1: match[1])
    markdown = markdown.sub(match[0], upload.short_path)
  end

  markdown
end

.replace_hotlinked_image_urls(raw:, &blk) ⇒ Object



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'app/services/inline_uploads.rb', line 220

def self.replace_hotlinked_image_urls(raw:, &blk)
  replace =
    Proc.new do |match, match_src, replacement, _index|
      upload = blk.call(match_src)
      next if !upload

      replacement =
        if replacement.include?(InlineUploads::PLACEHOLDER)
          replacement.sub(InlineUploads::PLACEHOLDER, upload.short_url)
        elsif replacement.include?(InlineUploads::PATH_PLACEHOLDER)
          replacement.sub(InlineUploads::PATH_PLACEHOLDER, upload.short_path)
        end

      raw = raw.gsub(match, replacement)
    end

  # there are 6 ways to insert an image in a post
  # HTML tag - <img src="http://...">
  InlineUploads.match_img(raw, external_src: true, &replace)

  # BBCode tag - [img]http://...[/img]
  InlineUploads.match_bbcode_img(raw, external_src: true, &replace)

  # Markdown linked image - [![alt](http://...)](http://...)
  # Markdown inline - ![alt](http://...)
  # Markdown inline - ![](http://... "image title")
  # Markdown inline - ![alt](http://... "image title")
  InlineUploads.match_md_inline_img(raw, external_src: true, &replace)

  raw =
    raw.gsub(%r{^(https?://\S+)(\s?)$}) do |match|
      if upload = blk.call(match)
        "![](#{upload.short_url})"
      else
        match
      end
    end

  raw
end