From c03649355a1a344dfb31b814699778ac26fd514d Mon Sep 17 00:00:00 2001 From: Anton Khorev Date: Sat, 15 Jun 2024 15:03:22 +0300 Subject: [PATCH] Join and normalize og:image url using Addressable Avoids failing on urls that are not strictly rfc2396 URIs. --- Gemfile | 1 + Gemfile.lock | 1 + app/helpers/open_graph_helper.rb | 4 +++- .../diary_entries_controller_test.rb | 22 +++++++++++++++++++ 4 files changed, 27 insertions(+), 1 deletion(-) diff --git a/Gemfile b/Gemfile index 77a9f1c97..5a21c7f7a 100644 --- a/Gemfile +++ b/Gemfile @@ -72,6 +72,7 @@ gem "validates_email_format_of", ">= 1.5.1" gem "quad_tile", "~> 1.0.1" # Sanitise URIs +gem "addressable", "~> 2.8" gem "rack-uri_sanitizer" # Omniauth for authentication diff --git a/Gemfile.lock b/Gemfile.lock index 246a37407..a8cc3a94f 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -602,6 +602,7 @@ DEPENDENCIES actionpack-page_caching (>= 1.2.0) active_record_union activerecord-import + addressable (~> 2.8) annotate argon2 autoprefixer-rails diff --git a/app/helpers/open_graph_helper.rb b/app/helpers/open_graph_helper.rb index aebb5d856..b7654ee89 100644 --- a/app/helpers/open_graph_helper.rb +++ b/app/helpers/open_graph_helper.rb @@ -1,10 +1,12 @@ module OpenGraphHelper + require "addressable/uri" + def opengraph_tags(title = nil, og_image = nil) tags = { "og:site_name" => t("layouts.project_name.title"), "og:title" => title || t("layouts.project_name.title"), "og:type" => "website", - "og:image" => og_image ? URI.join(root_url, og_image) : image_url("osm_logo_256.png"), + "og:image" => og_image ? Addressable::URI.join(root_url, og_image).normalize : image_url("osm_logo_256.png"), "og:url" => url_for(:only_path => false), "og:description" => t("layouts.intro_text") } diff --git a/test/controllers/diary_entries_controller_test.rb b/test/controllers/diary_entries_controller_test.rb index 1dfd5ec1a..f3ca40f41 100644 --- a/test/controllers/diary_entries_controller_test.rb +++ b/test/controllers/diary_entries_controller_test.rb @@ -766,6 +766,28 @@ class DiaryEntriesControllerTest < ActionDispatch::IntegrationTest end end + def test_show_og_image_with_spaces + user = create(:user) + diary_entry = create(:diary_entry, :user => user, :body => "![some picture](https://example.com/the picture.jpg)") + + get diary_entry_path(user, diary_entry) + assert_response :success + assert_dom "head meta[property='og:image']" do + assert_dom "> @content", "https://example.com/the%20picture.jpg" + end + end + + def test_show_og_image_with_relative_uri_and_spaces + user = create(:user) + diary_entry = create(:diary_entry, :user => user, :body => "![some local picture](/the picture.jpg)") + + get diary_entry_path(user, diary_entry) + assert_response :success + assert_dom "head meta[property='og:image']" do + assert_dom "> @content", "#{root_url}the%20picture.jpg" + end + end + def test_hide user = create(:user) diary_entry = create(:diary_entry, :user => user) -- 2.39.5