A platform for community discussion. Free, open, simple.
FEATURE: Add oneboxes and lightboxes to localized posts (#34900)
Rafael dos Santos Silvad4e939d053c3
diff --git a/db/migrate/20251008050307_delete_post_localizations_with_links.rb b/db/migrate/20251008050307_delete_post_localizations_with_links.rbnew file mode 100644index 00000000000..9fce3037db0--- /dev/null+++ b/db/migrate/20251008050307_delete_post_localizations_with_links.rb@@ -0,0 +1,14 @@+# frozen_string_literal: true+class DeletePostLocalizationsWithLinks < ActiveRecord::Migration[8.0]+ def up+ execute <<~SQL+ DELETE FROM post_localizations+ WHERE raw ~ 'https?://'+ OR cooked ~ 'https?://'+ SQL+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/lib/cooked_post_processor.rb b/lib/cooked_post_processor.rbindex a0f357933ef..b36b9904214 100644--- a/lib/cooked_post_processor.rb+++ b/lib/cooked_post_processor.rb@@ -6,11 +6,6 @@class CookedPostProcessorinclude CookedProcessorMixin- LIGHTBOX_WRAPPER_CSS_CLASS = "lightbox-wrapper"- GIF_SOURCES_REGEXP = %r{(giphy|tenor)\.com/}- MIN_LIGHTBOX_WIDTH = 100- MIN_LIGHTBOX_HEIGHT = 100-attr_reader :cooking_options, :docdef initialize(post, opts = {})@@ -130,15 +125,6 @@ class CookedPostProcessor)end- def extract_images- # all images with a src attribute- @doc.css("img[src], img[#{PrettyText::BLOCKED_HOTLINKED_SRC_ATTR}]") -- # minus data images- @doc.css("img[src^='data']") -- # minus emojis- @doc.css("img.emoji")- end-def extract_images_for_post# all images with a src attribute@doc.css("img[src]") -@@ -154,161 +140,6 @@ class CookedPostProcessor@doc.css(".onebox.githubfolder img")end- def convert_to_link!(img)- w, h = img["width"].to_i, img["height"].to_i- user_width, user_height =- (w > 0 && h > 0 && [w, h]) || get_size_from_attributes(img) ||- get_size_from_image_sizes(img["src"], @opts[:image_sizes])-- limit_size!(img)-- src = img["src"]- return if src.blank? || is_a_hyperlink?(img) || is_svg?(img)-- upload = Upload.get_from_url(src)-- original_width, original_height = nil-- if (upload.present?)- original_width = upload.width || 0- original_height = upload.height || 0- else- original_width, original_height = (get_size(src) || [0, 0]).map(&:to_i)- if original_width == 0 || original_height == 0- Rails.logger.info "Can't reach '#{src}' to get its dimension."- return- end- end-- if (upload.present? && upload.animated?) || src.match?(GIF_SOURCES_REGEXP)- img.add_class("animated")- end-- generate_thumbnail =- original_width > SiteSetting.max_image_width || original_height > SiteSetting.max_image_height-- user_width, user_height = [original_width, original_height] if user_width.to_i <= 0 &&- user_height.to_i <= 0- width, height = user_width, user_height-- crop =- SiteSetting.min_ratio_to_crop > 0 && width.to_f / height.to_f < SiteSetting.min_ratio_to_crop-- if crop- width, height = ImageSizer.crop(width, height)- img["width"], img["height"] = width, height- else- width, height = ImageSizer.resize(width, height)- end-- if upload.present?- if generate_thumbnail- upload.create_thumbnail!(width, height, crop: crop)-- each_responsive_ratio do |ratio|- resized_w = (width * ratio).to_i- resized_h = (height * ratio).to_i-- if upload.width && resized_w <= upload.width- upload.create_thumbnail!(resized_w, resized_h, crop: crop)- end- end- end-- return if upload.animated?-- if img.ancestors(".onebox, .onebox-body").blank? && !img.classes.include?("onebox")- add_lightbox!(img, original_width, original_height, upload)- end-- optimize_image!(img, upload, cropped: crop) if generate_thumbnail- end- end-- def optimize_image!(img, upload, cropped: false)- w, h = img["width"].to_i, img["height"].to_i- onebox = img.ancestors(".onebox, .onebox-body").first-- # note: optimize_urls cooks the src further after this- thumbnail = upload.thumbnail(w, h)- if thumbnail && thumbnail.filesize.to_i < upload.filesize- img["src"] = thumbnail.url-- srcset = +""-- # Skip srcset for onebox images. Because onebox thumbnails by default- # are fairly small the width/height of the smallest thumbnail is likely larger- # than what the onebox thumbnail size will be displayed at, so we shouldn't- # need to upscale for retina devices- if !onebox- each_responsive_ratio do |ratio|- resized_w = (w * ratio).to_i- resized_h = (h * ratio).to_i-- if !cropped && upload.width && resized_w > upload.width- cooked_url = UrlHelper.cook_url(upload.url, secure: @should_secure_uploads)- srcset << ", #{cooked_url} #{ratio.to_s.sub(/\.0\z/, "")}x"- elsif t = upload.thumbnail(resized_w, resized_h)- cooked_url = UrlHelper.cook_url(t.url, secure: @should_secure_uploads)- srcset << ", #{cooked_url} #{ratio.to_s.sub(/\.0\z/, "")}x"- end-- img[- "srcset"- ] = "#{UrlHelper.cook_url(img["src"], secure: @should_secure_uploads)}#{srcset}" if srcset.present?- end- end- else- img["src"] = upload.url- end-- if !@disable_dominant_color &&- (color = upload.dominant_color(calculate_if_missing: true).presence)- img["data-dominant-color"] = color- end- end-- def add_lightbox!(img, original_width, original_height, upload)- return if original_width < MIN_LIGHTBOX_WIDTH || original_height < MIN_LIGHTBOX_HEIGHT-- # first, create a div to hold our lightbox- lightbox = create_node("div", LIGHTBOX_WRAPPER_CSS_CLASS)- img.add_next_sibling(lightbox)- lightbox.add_child(img)-- # then, the link to our larger image- src_url = Upload.secure_uploads_url?(img["src"]) ? upload&.url || img["src"] : img["src"]- src = UrlHelper.cook_url(src_url, secure: @should_secure_uploads)-- a = create_link_node("lightbox", src)- img.add_next_sibling(a)-- a["data-download-href"] = Discourse.store.download_url(upload) if upload-- a.add_child(img)-- # then, some overlay informations- meta = create_node("div", "meta")- img.add_next_sibling(meta)-- filename = get_filename(upload, img["src"])- informations = +"#{original_width}×#{original_height}"- informations << " #{upload.human_filesize}" if upload-- a["title"] = img["title"] || img["alt"] || filename-- meta.add_child create_icon_node("far-image")- meta.add_child create_span_node("filename", a["title"])- meta.add_child create_span_node("informations", informations)- meta.add_child create_icon_node("discourse-expand")- end-- def get_filename(upload, src)- return File.basename(src) unless upload- return upload.original_filename unless upload.original_filename =~ /\Ablob(\.png)?\z/i- I18n.t("upload.pasted_image_filename")- end-def update_post_imageupload = nilimages = extract_images_for_post@@ -387,13 +218,6 @@ class CookedPostProcessorprivate- def post_process_images- extract_images.each do |img|- still_an_image = process_hotlinked_image(img)- convert_to_link!(img) if still_an_image- end- end-def post_process_videoschanges_made = false@@ -436,41 +260,6 @@ class CookedPostProcessorendend- def process_hotlinked_image(img)- onebox = img.ancestors(".onebox, .onebox-body").first-- @hotlinked_map ||= @post.post_hotlinked_media.preload(:upload).index_by(&:url)- normalized_src =- PostHotlinkedMedia.normalize_src(img["src"] || img[PrettyText::BLOCKED_HOTLINKED_SRC_ATTR])- info = @hotlinked_map[normalized_src]-- still_an_image = true-- if info&.too_large?- if !onebox || onebox.element_children.size == 1- add_large_image_placeholder!(img)- else- img.remove- end-- still_an_image = false- elsif info&.download_failed?- if !onebox || onebox.element_children.size == 1- add_broken_image_placeholder!(img)- else- img.remove- end-- still_an_image = false- elsif info&.downloaded? && upload = info&.upload- img["src"] = UrlHelper.cook_url(upload.url, secure: @should_secure_uploads)- img["data-dominant-color"] = upload.dominant_color(calculate_if_missing: true).presence- img.delete(PrettyText::BLOCKED_HOTLINKED_SRC_ATTR)- end-- still_an_image- end-def add_blocked_hotlinked_media_placeholders@doc.css(@@ -496,15 +285,4 @@ class CookedPostProcessoradd_blocked_hotlinked_media_placeholder!(el, src)endend-- def is_svg?(img)- path =- begin- URI(img["src"]).path- rescue URI::Error- nil- end-- File.extname(path) == ".svg" if path- endenddiff --git a/lib/cooked_processor_mixin.rb b/lib/cooked_processor_mixin.rbindex acde19cec14..11913870b25 100644--- a/lib/cooked_processor_mixin.rb+++ b/lib/cooked_processor_mixin.rb@@ -1,6 +1,11 @@# frozen_string_literal: truemodule CookedProcessorMixin+ GIF_SOURCES_REGEXP = %r{(giphy|tenor)\.com/}+ LIGHTBOX_WRAPPER_CSS_CLASS = "lightbox-wrapper"+ MIN_LIGHTBOX_WIDTH = 100+ MIN_LIGHTBOX_HEIGHT = 100+def post_process_oneboxeslimit = SiteSetting.max_oneboxes_per_post - @doc.css("aside.onebox, a.inline-onebox").sizeoneboxes = {}@@ -120,6 +125,22 @@ module CookedProcessorMixinendend+ def post_process_images+ extract_images.each do |img|+ still_an_image = process_hotlinked_image(img)+ convert_to_link!(img) if still_an_image+ end+ end++ def extract_images+ # all images with a src attribute+ @doc.css("img[src], img[#{PrettyText::BLOCKED_HOTLINKED_SRC_ATTR}]") -+ # minus data images+ @doc.css("img[src^='data']") -+ # minus emojis+ @doc.css("img.emoji")+ end+def limit_size!(img)# retrieve the size from# 1) the width/height attributes@@ -199,6 +220,12 @@ module CookedProcessorMixin# FastImage.size raises BufError for some gifs, leave it.end+ def get_filename(upload, src)+ return File.basename(src) unless upload+ return upload.original_filename unless upload.original_filename =~ /\Ablob(\.png)?\z/i+ I18n.t("upload.pasted_image_filename")+ end+def is_valid_image_url?(url)uri = URI.parse(url)%w[http https].include? uri.scheme@@ -371,4 +398,199 @@ module CookedProcessorMixin.sort.each { |r| yield r if r > 1 }end++ def is_svg?(img)+ path =+ begin+ URI(img["src"]).path+ rescue URI::Error+ nil+ end++ File.extname(path) == ".svg" if path+ end++ def convert_to_link!(img)+ w, h = img["width"].to_i, img["height"].to_i+ user_width, user_height =+ (w > 0 && h > 0 && [w, h]) || get_size_from_attributes(img) ||+ get_size_from_image_sizes(img["src"], @opts[:image_sizes])++ limit_size!(img)++ src = img["src"]+ return if src.blank? || is_a_hyperlink?(img) || is_svg?(img)++ upload = Upload.get_from_url(src)++ original_width, original_height = nil++ if (upload.present?)+ original_width = upload.width || 0+ original_height = upload.height || 0+ else+ original_width, original_height = (get_size(src) || [0, 0]).map(&:to_i)+ if original_width == 0 || original_height == 0+ Rails.logger.info "Can't reach '#{src}' to get its dimension."+ return+ end+ end++ if (upload.present? && upload.animated?) || src.match?(GIF_SOURCES_REGEXP)+ img.add_class("animated")+ end++ generate_thumbnail =+ original_width > SiteSetting.max_image_width || original_height > SiteSetting.max_image_height++ user_width, user_height = [original_width, original_height] if user_width.to_i <= 0 &&+ user_height.to_i <= 0+ width, height = user_width, user_height++ crop =+ SiteSetting.min_ratio_to_crop > 0 && width.to_f / height.to_f < SiteSetting.min_ratio_to_crop++ if crop+ width, height = ImageSizer.crop(width, height)+ img["width"], img["height"] = width, height+ else+ width, height = ImageSizer.resize(width, height)+ end++ if upload.present?+ if generate_thumbnail+ upload.create_thumbnail!(width, height, crop: crop)++ each_responsive_ratio do |ratio|+ resized_w = (width * ratio).to_i+ resized_h = (height * ratio).to_i++ if upload.width && resized_w <= upload.width+ upload.create_thumbnail!(resized_w, resized_h, crop: crop)+ end+ end+ end++ return if upload.animated?++ if img.ancestors(".onebox, .onebox-body").blank? && !img.classes.include?("onebox")+ add_lightbox!(img, original_width, original_height, upload)+ end++ optimize_image!(img, upload, cropped: crop) if generate_thumbnail+ end+ end++ def process_hotlinked_image(img)+ onebox = img.ancestors(".onebox, .onebox-body").first++ @hotlinked_map ||= @post.post_hotlinked_media.preload(:upload).index_by(&:url)+ normalized_src =+ PostHotlinkedMedia.normalize_src(img["src"] || img[PrettyText::BLOCKED_HOTLINKED_SRC_ATTR])+ info = @hotlinked_map[normalized_src]++ still_an_image = true++ if info&.too_large?+ if !onebox || onebox.element_children.size == 1+ add_large_image_placeholder!(img)+ else+ img.remove+ end++ still_an_image = false+ elsif info&.download_failed?+ if !onebox || onebox.element_children.size == 1+ add_broken_image_placeholder!(img)+ else+ img.remove+ end++ still_an_image = false+ elsif info&.downloaded? && upload = info&.upload+ img["src"] = UrlHelper.cook_url(upload.url, secure: @should_secure_uploads)+ img["data-dominant-color"] = upload.dominant_color(calculate_if_missing: true).presence+ img.delete(PrettyText::BLOCKED_HOTLINKED_SRC_ATTR)+ end++ still_an_image+ end++ def optimize_image!(img, upload, cropped: false)+ w, h = img["width"].to_i, img["height"].to_i+ onebox = img.ancestors(".onebox, .onebox-body").first++ # note: optimize_urls cooks the src further after this+ thumbnail = upload.thumbnail(w, h)+ if thumbnail && thumbnail.filesize.to_i < upload.filesize+ img["src"] = thumbnail.url++ srcset = +""++ # Skip srcset for onebox images. Because onebox thumbnails by default+ # are fairly small the width/height of the smallest thumbnail is likely larger+ # than what the onebox thumbnail size will be displayed at, so we shouldn't+ # need to upscale for retina devices+ if !onebox+ each_responsive_ratio do |ratio|+ resized_w = (w * ratio).to_i+ resized_h = (h * ratio).to_i++ if !cropped && upload.width && resized_w > upload.width+ cooked_url = UrlHelper.cook_url(upload.url, secure: @should_secure_uploads)+ srcset << ", #{cooked_url} #{ratio.to_s.sub(/\.0\z/, "")}x"+ elsif t = upload.thumbnail(resized_w, resized_h)+ cooked_url = UrlHelper.cook_url(t.url, secure: @should_secure_uploads)+ srcset << ", #{cooked_url} #{ratio.to_s.sub(/\.0\z/, "")}x"+ end++ img[+ "srcset"+ ] = "#{UrlHelper.cook_url(img["src"], secure: @should_secure_uploads)}#{srcset}" if srcset.present?+ end+ end+ else+ img["src"] = upload.url+ end++ if !@disable_dominant_color &&+ (color = upload.dominant_color(calculate_if_missing: true).presence)+ img["data-dominant-color"] = color+ end+ end++ def add_lightbox!(img, original_width, original_height, upload)+ return if original_width < MIN_LIGHTBOX_WIDTH || original_height < MIN_LIGHTBOX_HEIGHT++ # first, create a div to hold our lightbox+ lightbox = create_node("div", LIGHTBOX_WRAPPER_CSS_CLASS)+ img.add_next_sibling(lightbox)+ lightbox.add_child(img)++ # then, the link to our larger image+ src_url = Upload.secure_uploads_url?(img["src"]) ? upload&.url || img["src"] : img["src"]+ src = UrlHelper.cook_url(src_url, secure: @should_secure_uploads)++ a = create_link_node("lightbox", src)+ img.add_next_sibling(a)++ a["data-download-href"] = Discourse.store.download_url(upload) if upload++ a.add_child(img)++ # then, some overlay informations+ meta = create_node("div", "meta")+ img.add_next_sibling(meta)++ filename = get_filename(upload, img["src"])+ informations = +"#{original_width}×#{original_height}"+ informations << " #{upload.human_filesize}" if upload++ a["title"] = img["title"] || img["alt"] || filename++ meta.add_child create_icon_node("far-image")+ meta.add_child create_span_node("filename", a["title"])+ meta.add_child create_span_node("informations", informations)+ meta.add_child create_icon_node("discourse-expand")+ endenddiff --git a/plugins/discourse-ai/lib/translation/localized_cooked_post_processor.rb b/plugins/discourse-ai/lib/translation/localized_cooked_post_processor.rbnew file mode 100644index 00000000000..ae2c07d986b--- /dev/null+++ b/plugins/discourse-ai/lib/translation/localized_cooked_post_processor.rb@@ -0,0 +1,32 @@+# frozen_string_literal: true++module DiscourseAi+ module Translation+ class LocalizedCookedPostProcessor+ include CookedProcessorMixin++ def initialize(post_localization, post, opts = {})+ @post_localization = post_localization+ @post = post+ @opts = opts+ @doc = Loofah.html5_fragment(@post_localization.cooked)+ @cooking_options = @post.cooking_options || {}+ @cooking_options[:topic_id] = @post.topic_id+ @cooking_options = @cooking_options.symbolize_keys+ @model = @post+ @category_id = @post&.topic&.category_id+ @omit_nofollow = @post.omit_nofollow?+ @size_cache = {}+ end++ def post_process+ post_process_oneboxes+ post_process_images+ end++ def html+ @doc.try(:to_html)+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/translation/post_localizer.rb b/plugins/discourse-ai/lib/translation/post_localizer.rbindex e3582396c78..544fb8c7492 100644--- a/plugins/discourse-ai/lib/translation/post_localizer.rb+++ b/plugins/discourse-ai/lib/translation/post_localizer.rb@@ -1,5 +1,7 @@# frozen_string_literal: true+require_relative "localized_cooked_post_processor"+module DiscourseAimodule Translationclass PostLocalizer@@ -17,7 +19,12 @@ module DiscourseAiPostLocalization.find_or_initialize_by(post_id: post.id, locale: target_locale)localization.raw = translated_raw- localization.cooked = PrettyText.cook(translated_raw)+ localization.cooked = post.post_analyzer.cook(translated_raw, post.cooking_options || {})++ cooked_processor = LocalizedCookedPostProcessor.new(localization, post, {})+ cooked_processor.post_process+ localization.cooked = cooked_processor.html+localization.post_version = post.versionlocalization.localizer_user_id = Discourse.system_user.idlocalization.save!diff --git a/plugins/discourse-ai/spec/jobs/regular/detect_translate_post_spec.rb b/plugins/discourse-ai/spec/jobs/regular/detect_translate_post_spec.rbindex db6cbf54568..a3258b0b52a 100644--- a/plugins/discourse-ai/spec/jobs/regular/detect_translate_post_spec.rb+++ b/plugins/discourse-ai/spec/jobs/regular/detect_translate_post_spec.rb@@ -9,6 +9,12 @@ describe Jobs::DetectTranslatePost dobefore doassign_fake_provider_to(:ai_default_llm_model)+ # fake provider (Completions::Endpoints::Fake) returns translated text that includes this svg+ stub_request(:get, "https://meta.discourse.org/images/discourse-logo.svg").to_return(+ status: 200,+ body: "",+ )+enable_current_pluginSiteSetting.ai_translation_enabled = trueSiteSetting.content_localization_supported_locales = locales.join("|")diff --git a/plugins/discourse-ai/spec/lib/translation/post_localizer_spec.rb b/plugins/discourse-ai/spec/lib/translation/post_localizer_spec.rbindex e34496a5686..0d243589f65 100644--- a/plugins/discourse-ai/spec/lib/translation/post_localizer_spec.rb+++ b/plugins/discourse-ai/spec/lib/translation/post_localizer_spec.rb@@ -87,6 +87,63 @@ describe DiscourseAi::Translation::PostLocalizer doexpect(out.cooked).to eq(cooked)}.to_not change { PostLocalization.count }end++ context "with cooked post processing" do+ describe "oneboxing" do+ fab!(:topic_to_onebox, :topic)++ let(:onebox_url) { topic_to_onebox.url }+ let(:post) { Fabricate(:post, raw: onebox_url) }+ let(:translated_raw) { onebox_url }+ let(:onebox_html) do+ "<aside class=\"onebox\"><a href=\"#{onebox_url}\">#{topic_to_onebox.title}</a></aside>"+ end++ before { Oneboxer.stubs(:onebox).with(onebox_url, anything).returns(onebox_html) }++ it "creates oneboxes in the cooked HTML" do+ post_raw_translator_stub(+ { text: post.raw, target_locale: "ja", translated: translated_raw },+ )+ localization = described_class.localize(post, "ja")+ expect(localization.cooked).to include(onebox_html)+ end+ end++ describe "image lightbox" do+ fab!(:image_url) { "https://cat.com/image.png" }+ fab!(:uploaded_image_url) { "https://cat.com/uploaded.png" }+ fab!(:upload) do+ Fabricate(+ :upload,+ url: uploaded_image_url,+ width: 2000,+ height: 1500,+ original_filename: "test_image.png",+ )+ end+ fab!(:post) { Fabricate(:post, raw: "") }+ fab!(:translated_raw) { "" }++ before do+ SiteSetting.max_image_width = 500+ SiteSetting.max_image_height = 500+ Upload.stubs(:get_from_url).with(image_url).returns(upload)+ upload.stubs(:create_thumbnail!)+ upload.stubs(:thumbnail).returns(nil)+ upload.stubs(:dominant_color).returns(nil)+ end++ it "processes images including optimize_image! in the cooked HTML" do+ post_raw_translator_stub(+ { text: post.raw, target_locale: "ja", translated: translated_raw },+ )+ localization = described_class.localize(post, "ja")+ expect(localization.cooked).to include("lightbox-wrapper")+ expect(localization.cooked).to include(uploaded_image_url)+ end+ end+ endenddescribe ".has_relocalize_quota?" do