FIX: Edge cases with markdown references for `InlineUploads`.

FIX: Edge cases with markdown references for InlineUploads.

diff --git a/app/services/inline_uploads.rb b/app/services/inline_uploads.rb
index 95cabeb..c0a202e 100644
--- a/app/services/inline_uploads.rb
+++ b/app/services/inline_uploads.rb
@@ -11,6 +11,13 @@ class InlineUploads
 
   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::HTML::fragment(PrettyText.cook(markdown, disable_emojis: true))
     link_occurences = []
 
@@ -40,10 +47,6 @@ class InlineUploads
       raw_matches << [match, src, replacement, index]
     end
 
-    match_md_reference(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
@@ -140,6 +143,11 @@ class InlineUploads
       end
     end
 
+    markdown.scan(/(__([a-f0-9]{40})__)/) do |match|
+      upload = Upload.find_by(sha1: match[1])
+      markdown = markdown.sub(match[0], upload.short_path)
+    end
+
     markdown
   end
 
diff --git a/spec/services/inline_uploads_spec.rb b/spec/services/inline_uploads_spec.rb
index 2924293..a1fdcc0 100644
--- a/spec/services/inline_uploads_spec.rb
+++ b/spec/services/inline_uploads_spec.rb
@@ -177,19 +177,29 @@ RSpec.describe InlineUploads do
 
       it "should correct markdown references" do
         md = <<~MD
-        This is a [some reference] something
+        [link3][3]
 
-        [some reference]: #{Discourse.base_url}#{upload.url}
+        [3]: #{Discourse.base_url}#{upload2.url}
+
+        This is a [link1][1] test [link2][2] something
 
         <img src="#{upload.url}">
+
+        [1]: #{Discourse.base_url}#{upload.url}
+        [2]: #{Discourse.base_url}#{upload2.url}
         MD
 
         expect(InlineUploads.process(md)).to eq(<<~MD)
-        This is a [some reference] something
+        [link3][3]
 
-        [some reference]: #{Discourse.base_url}#{upload.short_path}
+        [3]: #{Discourse.base_url}#{upload2.short_path}
+
+        This is a [link1][1] test [link2][2] something
 
         ![](#{upload.short_url})
+
+        [1]: #{Discourse.base_url}#{upload.short_path}
+        [2]: #{Discourse.base_url}#{upload2.short_path}
         MD
       end

GitHub sha: 782e5838

1 Like

FYI, you can do that in Ruby

markdown.scan(/(__(\h{40})__)/) do |match|