Skip to content

A platform for community discussion. Free, open, simple.

FIX: Embed not loading when canonical URL points to different host due to discourseEmbedUrl not being used (#39647)

Juan David Martínez Cubillos57c48030cca0
diff --git a/app/models/topic_embed.rb b/app/models/topic_embed.rb
index 1270133ab31..663bc3f02a7 100644
--- a/app/models/topic_embed.rb
+++ b/app/models/topic_embed.rb
@@ -271,9 +271,16 @@ class TopicEmbed < ActiveRecord::Base
response.title = opts[:title] if opts[:title].present?
import_user = opts[:user] if opts[:user].present?
import_user = response.author if response.author.present?
- url = normalize_url(response.url) if response.url.present?
- TopicEmbed.import(import_user, url, response.title, response.body)
+ embed_url = url
+
+ if response.url.present?
+ original_uri = URI.parse(UrlHelper.normalized_encode(url))
+ canonical_uri = URI.parse(UrlHelper.normalized_encode(response.url))
+ embed_url = response.url if original_uri.host == canonical_uri.host
+ end
+
+ TopicEmbed.import(import_user, embed_url, response.title, response.body)
end
# Convert any relative URLs to absolute. RSS is annoying for this.
diff --git a/spec/models/topic_embed_spec.rb b/spec/models/topic_embed_spec.rb
index ed194f5903c..7a8c64ad275 100644
--- a/spec/models/topic_embed_spec.rb
+++ b/spec/models/topic_embed_spec.rb
@@ -747,6 +747,36 @@ RSpec.describe TopicEmbed do
}
end
end
+
+ context "when canonical URL points to a different domain" do
+ fab!(:user)
+ let(:title) { "Some article title" }
+ let(:original_url) { "http://staging.example.com/article/123" }
+ let(:canonical_url) { "http://production.example.com/article/123" }
+ let(:original_content) do
+ "<head><link rel=\"canonical\" href=\"#{canonical_url}\"></head><body>Article content</body>"
+ end
+ let(:canonical_content) do
+ "<title>#{title}</title><body>Article content from canonical</body>"
+ end
+
+ before do
+ stub_request(:get, original_url).to_return(status: 200, body: original_content)
+ stub_request(:head, canonical_url)
+ stub_request(:get, canonical_url).to_return(status: 200, body: canonical_content)
+ end
+
+ it "stores the original URL as embed_url so embeds can be found" do
+ Jobs.run_immediately!
+ post = TopicEmbed.import_remote(original_url, { title: title, user: user })
+
+ topic_embed = TopicEmbed.find_by(topic_id: post.topic_id)
+ expect(topic_embed.embed_url).to include("staging.example.com")
+
+ found_topic_id = TopicEmbed.topic_id_for_embed(original_url)
+ expect(found_topic_id).to eq(post.topic_id)
+ end
+ end
end
describe ".absolutize_urls" do