FIX: include 'short_url' as src if upload url not exist

FIX: include ‘short_url’ as src if upload url not exist

The URL ‘/images/transparent.png’ will be used in the cooked content if upload record not found. In that case we have to use ‘short_url’ as image src in ‘post.each_upload_url’ method.

diff --git a/app/models/post.rb b/app/models/post.rb
index 3cbe11e..56d96b0 100644
--- a/app/models/post.rb
+++ b/app/models/post.rb
@@ -895,10 +895,27 @@ class Post < ActiveRecord::Base
     ]
 
     fragments ||= Nokogiri::HTML::fragment(self.cooked)
-    links = fragments.css("a/@href", "img/@src").map { |media| media.value }.uniq
+    links = fragments.css("a/@href", "img/@src").map do |media|
+      src = media.value
+      next if src.blank?
+
+      if src.end_with?("/images/transparent.png") && (parent = media.parent)["data-orig-src"].present?
+        parent["data-orig-src"]
+      else
+        src
+      end
+    end.compact.uniq
 
     links.each do |src|
-      next if src.blank? || upload_patterns.none? { |pattern| src.split("?")[0] =~ pattern }
+      src = src.split("?")[0]
+
+      if src.start_with?("upload://")
+        sha1 = Upload.sha1_from_short_url(src)
+        yield(src, nil, sha1)
+        next
+      end
+
+      next if upload_patterns.none? { |pattern| src =~ pattern }
       next if Rails.configuration.multisite && src.exclude?(current_db) && src.exclude?("short-url")
 
       src = "#{SiteSetting.force_https ? "https" : "http"}:#{src}" if src.start_with?("//")
diff --git a/spec/models/post_spec.rb b/spec/models/post_spec.rb
index 111f90e..de591e2 100644
--- a/spec/models/post_spec.rb
+++ b/spec/models/post_spec.rb
@@ -1399,6 +1399,29 @@ describe Post do
       )
     end
 
+    it "correctly identifies missing uploads with short url" do
+      upload = Fabricate(:upload)
+      url = upload.short_url
+      sha1 = upload.sha1
+      upload.destroy!
+
+      post = Fabricate(:post, raw: "![upload](#{url})")
+
+      urls = []
+      paths = []
+      sha1s = []
+
+      post.each_upload_url do |src, path, sha1|
+        urls << src
+        paths << path
+        sha1s << sha1
+      end
+
+      expect(urls).to contain_exactly(url)
+      expect(paths).to contain_exactly(nil)
+      expect(sha1s).to contain_exactly(sha1)
+    end
+
     it "should skip external urls with upload url in query string" do
       SiteSetting.enable_s3_uploads = true
       SiteSetting.s3_upload_bucket = "s3-upload-bucket"

GitHub sha: aa012d12

fix the build