From: Anton Khorev Date: Sat, 15 Jun 2024 12:57:10 +0000 (+0300) Subject: Use default og:image if Addressable::URI fails X-Git-Tag: live~471^2 X-Git-Url: https://git.openstreetmap.org./rails.git/commitdiff_plain/b97834f1fd8f5ee299e83b38147da439165dc859 Use default og:image if Addressable::URI fails --- diff --git a/app/helpers/open_graph_helper.rb b/app/helpers/open_graph_helper.rb index b7654ee89..a41831ca6 100644 --- a/app/helpers/open_graph_helper.rb +++ b/app/helpers/open_graph_helper.rb @@ -6,7 +6,7 @@ module OpenGraphHelper "og:site_name" => t("layouts.project_name.title"), "og:title" => title || t("layouts.project_name.title"), "og:type" => "website", - "og:image" => og_image ? Addressable::URI.join(root_url, og_image).normalize : image_url("osm_logo_256.png"), + "og:image" => og_image_url(og_image), "og:url" => url_for(:only_path => false), "og:description" => t("layouts.intro_text") } @@ -15,4 +15,15 @@ module OpenGraphHelper tag.meta(:property => property, :content => content) end, "\n") end + + private + + def og_image_url(og_image) + begin + return Addressable::URI.join(root_url, og_image).normalize if og_image + rescue Addressable::URI::InvalidURIError + # return default image + end + image_url("osm_logo_256.png") + end end diff --git a/test/controllers/diary_entries_controller_test.rb b/test/controllers/diary_entries_controller_test.rb index f3ca40f41..c8548d67b 100644 --- a/test/controllers/diary_entries_controller_test.rb +++ b/test/controllers/diary_entries_controller_test.rb @@ -744,6 +744,17 @@ class DiaryEntriesControllerTest < ActionDispatch::IntegrationTest end end + def test_show_og_image_with_no_image + user = create(:user) + diary_entry = create(:diary_entry, :user => user, :body => "nothing") + + get diary_entry_path(user, diary_entry) + assert_response :success + assert_dom "head meta[property='og:image']" do + assert_dom "> @content", ActionController::Base.helpers.image_url("osm_logo_256.png", :host => root_url) + end + end + def test_show_og_image user = create(:user) diary_entry = create(:diary_entry, :user => user, :body => "![some picture](https://example.com/picture.jpg)") @@ -788,6 +799,17 @@ class DiaryEntriesControllerTest < ActionDispatch::IntegrationTest end end + def test_show_og_image_with_invalid_uri + user = create(:user) + diary_entry = create(:diary_entry, :user => user, :body => "![](:)") + + get diary_entry_path(user, diary_entry) + assert_response :success + assert_dom "head meta[property='og:image']" do + assert_dom "> @content", ActionController::Base.helpers.image_url("osm_logo_256.png", :host => root_url) + end + end + def test_hide user = create(:user) diary_entry = create(:diary_entry, :user => user)