Skip to content

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

FEATURE: generated OpenGraph images for topics (#39194)

Penar Musaraj2d895de2977e
diff --git a/app/assets/stylesheets/admin/admin_config_area.scss b/app/assets/stylesheets/admin/admin_config_area.scss
index 16d4923508e..adbade0d195 100644
--- a/app/assets/stylesheets/admin/admin_config_area.scss
+++ b/app/assets/stylesheets/admin/admin_config_area.scss
@@ -187,6 +187,64 @@
}
}
+.og-image-preview {
+ margin-top: var(--space-4);
+
+ &__header {
+ margin-bottom: var(--space-1);
+ }
+
+ &__title {
+ font-weight: bold;
+ font-size: var(--font-0-rem);
+ }
+
+ &__description {
+ color: var(--primary-medium);
+ font-size: var(--font-down-1-rem);
+ margin-bottom: var(--space-3);
+ }
+
+ &__form {
+ margin-bottom: var(--space-3);
+ }
+
+ &__controls {
+ display: flex;
+ align-items: flex-end;
+ gap: var(--space-2);
+
+ .form-kit__field {
+ margin-bottom: 0;
+ }
+ }
+
+ &__frame {
+ border: 1px solid var(--primary-low);
+ border-radius: var(--d-border-radius-large);
+ overflow: hidden;
+ max-width: 600px;
+ background: var(--secondary);
+ }
+
+ &__image {
+ display: block;
+ width: 100%;
+ height: auto;
+ }
+
+ &__loading,
+ &__error,
+ &__placeholder {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ aspect-ratio: 1200 / 630;
+ color: var(--primary-medium);
+ font-size: var(--font-down-1-rem);
+ }
+}
+
.admin-fonts-form {
&__more {
font-size: var(--font-down-1-rem);
diff --git a/app/controllers/admin/config/logo_controller.rb b/app/controllers/admin/config/logo_controller.rb
index 37088a0b467..fb1a7c98249 100644
--- a/app/controllers/admin/config/logo_controller.rb
+++ b/app/controllers/admin/config/logo_controller.rb
@@ -3,6 +3,34 @@ class Admin::Config::LogoController < Admin::AdminController
def index
end
+ def og_image_preview
+ raise Discourse::InvalidParameters.new(:topic_id) if params[:topic_id].blank?
+
+ topic = Topic.find_by(id: params[:topic_id])
+ raise Discourse::NotFound if topic.nil?
+
+ if !TopicOgImageGenerator.eligible?(topic)
+ render json: {
+ error: I18n.t("topic_og_image.preview_not_eligible"),
+ },
+ status: :unprocessable_entity
+ return
+ end
+
+ png_bytes = TopicOgImageGenerator.new(topic).generate_bytes
+
+ if png_bytes.blank?
+ render json: {
+ error: I18n.t("topic_og_image.preview_generation_failed"),
+ },
+ status: :unprocessable_entity
+ return
+ end
+
+ data_uri = "data:image/png;base64,#{Base64.strict_encode64(png_bytes)}"
+ render json: { url: data_uri, topic_id: topic.id, topic_title: topic.title }
+ end
+
def update
settings =
%i[
@@ -18,6 +46,7 @@ class Admin::Config::LogoController < Admin::AdminController
manifest_screenshots
apple_touch_icon
digest_logo
+ generate_topic_og_image
opengraph_image
x_summary_large_image
].filter_map do |setting|
diff --git a/app/jobs/regular/generate_topic_og_image.rb b/app/jobs/regular/generate_topic_og_image.rb
new file mode 100644
index 00000000000..f9c1ee67997
--- /dev/null
+++ b/app/jobs/regular/generate_topic_og_image.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+module Jobs
+ class GenerateTopicOgImage < ::Jobs::Base
+ sidekiq_options queue: "ultra_low"
+
+ def execute(args)
+ return if !SiteSetting.generate_topic_og_image
+
+ topic_id = args[:topic_id]
+ raise Discourse::InvalidParameters.new(:topic_id) if topic_id.blank?
+
+ topic = Topic.find_by(id: topic_id)
+ return if topic.nil?
+ if topic.image_upload_id.present?
+ topic.clear_generated_og_image!
+ return
+ end
+ return if !TopicOgImageGenerator.eligible?(topic)
+
+ generator = TopicOgImageGenerator.new(topic)
+ upload = generator.generate
+ return if upload.nil? || upload.errors.any?
+
+ old_upload_id = topic.og_image_upload_id
+ topic.update_column(:og_image_upload_id, upload.id)
+ UploadReference.ensure_exist!(upload_ids: [upload.id], target: topic)
+ UploadReference.where(target: topic, upload_id: old_upload_id).delete_all if old_upload_id
+ end
+ end
+end
diff --git a/app/models/topic.rb b/app/models/topic.rb
index 89f1b5f1f7c..16b81c36ca0 100644
--- a/app/models/topic.rb
+++ b/app/models/topic.rb
@@ -310,8 +310,11 @@ class Topic < ActiveRecord::Base
has_one :nested_topic, dependent: :destroy
belongs_to :image_upload, class_name: "Upload"
+ belongs_to :og_image_upload, class_name: "Upload"
has_many :topic_thumbnails, through: :image_upload
+ after_save :regenerate_og_image
+
# When we want to temporarily attach some data to a forum topic (usually before serialization)
attr_accessor :user_data
attr_accessor :category_user_data
@@ -394,6 +397,8 @@ class Topic < ActiveRecord::Base
attr_accessor :skip_callbacks
attr_accessor :advance_draft
+ OG_IMAGE_REGENERATION_COUNTER_STEP = 10
+
before_create { initialize_default_values }
after_create do
@@ -445,6 +450,52 @@ class Topic < ActiveRecord::Base
end
end
+ def regenerate_og_image
+ return if !(saved_changes[:title] || saved_changes[:category_id])
+ return if og_image_upload_id.blank?
+
+ if SiteSetting.generate_topic_og_image && TopicOgImageGenerator.eligible?(self)
+ Jobs.enqueue(:generate_topic_og_image, topic_id: id)
+ else
+ clear_generated_og_image!
+ end
+ end
+
+ def self.regenerate_og_image_after_replies_change(topic_id, replies_count)
+ return if !og_image_counter_regeneration_needed?(replies_count - 1, replies_count)
+
+ Topic.find_by(id: topic_id)&.enqueue_og_image_regeneration_after_counter_change(
+ previous_count: replies_count - 1,
+ current_count: replies_count,
+ )
+ end
+
+ def self.og_image_counter_regeneration_needed?(previous_count, current_count)
+ previous_count = previous_count.to_i
+ current_count = current_count.to_i
+
+ current_count >= OG_IMAGE_REGENERATION_COUNTER_STEP &&
+ previous_count / OG_IMAGE_REGENERATION_COUNTER_STEP <
+ current_count / OG_IMAGE_REGENERATION_COUNTER_STEP
+ end
+
+ def enqueue_og_image_regeneration_after_counter_change(previous_count:, current_count:)
+ return if !SiteSetting.generate_topic_og_image
+ return if og_image_upload_id.blank?
+ return if !TopicOgImageGenerator.eligible?(self)
+ return if !self.class.og_image_counter_regeneration_needed?(previous_count, current_count)
+
+ Jobs.enqueue(:generate_topic_og_image, topic_id: id)
+ end
+
+ def clear_generated_og_image!
+ old_upload_id = og_image_upload_id
+ return if old_upload_id.blank?
+
+ update_column(:og_image_upload_id, nil)
+ UploadReference.where(target: self, upload_id: old_upload_id).delete_all
+ end
+
def initialize_default_values
self.bumped_at ||= Time.now
self.last_post_user_id ||= user_id
@@ -912,6 +963,7 @@ class Topic < ActiveRecord::Base
WHERE id = ?
RETURNING highest_staff_post_number
SQL
+ return result.first.to_i
else
reply_sql = opts[:reply] ? ", reply_count = reply_count + 1" : ""
posts_sql = opts[:post] ? ", posts_count = posts_count + 1" : ""
@@ -923,11 +975,17 @@ class Topic < ActiveRecord::Base
#{reply_sql}
#{posts_sql}
WHERE id = :topic_id
- RETURNING highest_post_number
+ RETURNING highest_post_number, posts_count
SQL
end
- result.first.to_i
+ if opts[:post]
+ highest_post_number, posts_count = result
+ regenerate_og_image_after_replies_change(topic_id, posts_count.to_i - 1)
+ highest_post_number.to_i
+ else
+ result.first.to_i
+ end
end
def self.reset_all_highest!
@@ -1361,9 +1419,14 @@ class Topic < ActiveRecord::Base
end
def update_action_counts
- update_column(
- :like_count,
- Post.where.not(post_type: Post.types[:whisper]).where(topic_id: id).sum(:like_count),
+ old_like_count = like_count
+ new_like_count =
+ Post.where.not(post_type: Post.types[:whisper]).where(topic_id: id).sum(:like_count)
+
+ update_column(:like_count, new_like_count)
+ enqueue_og_image_regeneration_after_counter_change(
+ previous_count: old_like_count,
+ current_count: new_like_count,
)
end
@@ -2276,6 +2339,7 @@ end
# featured_user4_id :integer
# image_upload_id :bigint
# last_post_user_id :integer not null
+# og_image_upload_id :bigint
# user_id :integer
# visibility_reason_id :integer
#
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index a317cec5dba..daaef90f5be 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -6689,9 +6689,25 @@ en:
title: "Digest logo"
description: "The alternate logo image used at the top of your site's email summary. If left blank, the image from the `logo` setting will be used."
help_text: "Use a wide rectangle image. Don't use an SVG image."
+ og_image_source:
+ title: "OpenGraph image source"
+ description: "Choose how OpenGraph preview images are provided for topics that don't have their own image."
+ uploaded: "Use an uploaded image"
+ generated: "Generate an image per topic"
opengraph_image:
title: "OpenGraph image"
description: "Default opengraph image, used when the page has no other suitable image. If left blank, large_icon will be used."
+ generate_topic_og_image:
+ title: "Generate topic OG images"
+ description: "Automatically generate OpenGraph preview images for topics that don't have an image. Uses topic title, category, and site colors."
+ og_image_preview:
+ title: "Generated OG image preview"
+ description: "Preview of automatically generated OpenGraph images for topics without images. Enter a topic ID to test."
+ generate: "Generate"
+ topic_id_label: "Topic ID"
+ topic_id_placeholder: "e.g. 123"
+ placeholder: "Enter a topic ID and click Generate to preview."
+ error: "Could not generate preview. Check the topic ID and try again."
x_summary_large_image:
title: "X summary large image"
description: "X card 'summary large image'. If left blank, regular card metadata is generated using the OpenGraph_image, as long as that is not also a .svg."
diff --git a/config/locales/server.en.yml b/config/locales/server.en.yml
index f6c9754931c..df49fada86f 100644
--- a/config/locales/server.en.yml
+++ b/config/locales/server.en.yml
@@ -465,6 +465,9 @@ en:
invalid_access: "You are not permitted to view the requested resource."
topic_converter:
too_many_recipients: "Cannot convert: this topic has more participants than the max allowed (%{max})."
+ topic_og_image:
+ preview_not_eligible: "Cannot generate an OG image for personal messages or topics in private categories."
+ preview_generation_failed: "Failed to generate preview image."
authenticator_not_found: "Authentication method does not exist, or has been disabled."
authenticator_no_connect: "This authentication provider does not allow connection to an existing forum account."
invalid_api_credentials: "You are not permitted to view the requested resource. The API username or key is invalid."
@@ -1947,6 +1950,7 @@ en:
manifest_icon: "Image used as logo/splash image on Android. Will be automatically resized to 512 × 512. If left blank, {{setting:large_icon}} will be used."
manifest_screenshots: "Screenshots that showcase your instance features and functionality on its install prompt page. All images should be local uploads and of the same dimensions."
favicon: "A favicon for your site, see <a href='https://en.wikipedia.org/wiki/Favicon' target='_blank'>https://en.wikipedia.org/wiki/Favicon</a>. To work correctly over a CDN it must be a png. Will be resized to 32x32. If left blank, {{setting:large_icon}} will be used."
+ generate_topic_og_image: "Automatically generate OpenGraph preview images for topics that don't have an image. Uses topic title, category, and site colors."
apple_touch_icon: "Icon used for Apple touch devices. A transparent background is not recommended. Will be automatically resized to 180x180. If left blank, {{setting:large_icon}} will be used."
opengraph_image: "Default opengraph image, used when the page has no other suitable image. If left blank, {{setting:large_icon}} will be used"
x_summary_large_image: "Twitter card 'summary large image' (should be at least 280 in width, and at least 150 in height, cannot be .svg). If left blank, regular card metadata is generated using the {{setting:opengraph_image}}, as long as that is not also a .svg"
diff --git a/config/routes.rb b/config/routes.rb
index 6abde1aab7d..26f1b5abf1a 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -450,6 +450,7 @@ Discourse::Application.routes.draw do
get "trust-levels" => "site_settings#index"
get "group-permissions" => "site_settings#index"
get "/logo" => "logo#index"
+ get "/logo/og-image-preview" => "logo#og_image_preview"
get "/fonts" => "fonts#index"
get "/welcome-banner/themes-with-setting" => "welcome_banner#themes_with_setting"
get "/welcome-banner" => "welcome_banner#index"
diff --git a/config/site_settings.yml b/config/site_settings.yml
index e62620f4f8c..4bf84bfd300 100644
--- a/config/site_settings.yml
+++ b/config/site_settings.yml
@@ -192,6 +192,9 @@ branding:
default: ""
client: true
type: upload
+ generate_topic_og_image:
+ default: false
+ client: true
opengraph_image:
default: ""
client: true
diff --git a/db/migrate/20260409225129_add_og_image_upload_id_to_topics.rb b/db/migrate/20260409225129_add_og_image_upload_id_to_topics.rb
new file mode 100644
index 00000000000..4fd5efe11d8
--- /dev/null
+++ b/db/migrate/20260409225129_add_og_image_upload_id_to_topics.rb
@@ -0,0 +1,6 @@
+# frozen_string_literal: true
+class AddOgImageUploadIdToTopics < ActiveRecord::Migration[8.0]
+ def change
+ add_column :topics, :og_image_upload_id, :bigint, null: true
+ end
+end
diff --git a/db/structure.sql b/db/structure.sql
index 6394935facd..bb7612cd72b 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -1673,6 +1673,7 @@ CREATE TABLE public.topics (
external_id character varying,
visibility_reason_id integer,
locale character varying(20),
+ og_image_upload_id bigint,
CONSTRAINT has_category_id CHECK (((category_id IS NOT NULL) OR ((archetype)::text <> 'regular'::text))),
CONSTRAINT pm_has_no_category CHECK (((category_id IS NULL) OR ((archetype)::text <> 'private_message'::text)))
);
@@ -22257,6 +22258,7 @@ INSERT INTO "schema_migrations" (version) VALUES
('20260421061908'),
('20260420014648'),
('20260415082426'),
+('20260409225129'),
('20260408214007'),
('20260408165014'),
('20260407093145'),
diff --git a/frontend/discourse/admin/components/admin-logo-form.gjs b/frontend/discourse/admin/components/admin-logo-form.gjs
index bfcb3e41b49..4025af71afe 100644
--- a/frontend/discourse/admin/components/admin-logo-form.gjs
+++ b/frontend/discourse/admin/components/admin-logo-form.gjs
@@ -5,11 +5,13 @@ import { action } from "@ember/object";
import { trackedObject } from "@ember/reactive/collections";
import { service } from "@ember/service";
import AdminConfigAreaCardSection from "discourse/admin/components/admin-config-area-card-section";
+import OgImagePreview from "discourse/admin/components/og-image-preview";
import SimpleList from "discourse/admin/components/simple-list";
import Form from "discourse/components/form";
import { ajax } from "discourse/lib/ajax";
import { bind } from "discourse/lib/decorators";
import getURL from "discourse/lib/get-url";
+import { eq } from "discourse/truth-helpers";
import DConditionalLoadingSpinner from "discourse/ui-kit/d-conditional-loading-spinner";
import { i18n } from "discourse-i18n";
@@ -73,6 +75,7 @@ export default class AdminLogoForm extends Component {
manifest_screenshots: data.manifest_screenshots,
apple_touch_icon: data.apple_touch_icon,
digest_logo: data.digest_logo,
+ generate_topic_og_image: data.og_image_source === "generated",
opengraph_image: data.opengraph_image,
x_summary_large_image: data.x_summary_large_image,
},
@@ -117,6 +120,9 @@ export default class AdminLogoForm extends Component {
manifest_screenshots: this.siteSettings.manifest_screenshots,
apple_touch_icon: this.siteSettings.apple_touch_icon,
digest_logo: this.siteSettings.digest_logo,
+ og_image_source: this.siteSettings.generate_topic_og_image
+ ? "generated"
+ : "uploaded",
opengraph_image: this.siteSettings.opengraph_image,
x_summary_large_image: this.siteSettings.x_summary_large_image,
};
@@ -369,20 +375,43 @@ export default class AdminLogoForm extends Component {
>
<:content>
<form.Field
- @name="opengraph_image"
- @title={{i18n "admin.config.logo.form.opengraph_image.title"}}
+ @name="og_image_source"
+ @title={{i18n "admin.config.logo.form.og_image_source.title"}}
@description={{i18n
- "admin.config.logo.form.opengraph_image.description"
+ "admin.config.logo.form.og_image_source.description"
}}
- @onSet={{fn this.handleUpload "opengraph_image"}}
- @type="image"
+ @format="full"
+ @type="radio-group"
as |field|
>
- <field.Control
- @type="branding"
- @placeholderUrl={{this.placeholders.opengraph_image}}
- />
+ <field.Control as |radioGroup|>
+ <radioGroup.Radio @value="uploaded">
+ {{i18n "admin.config.logo.form.og_image_source.uploaded"}}
+ </radioGroup.Radio>
+ <radioGroup.Radio @value="generated">
+ {{i18n "admin.config.logo.form.og_image_source.generated"}}
+ </radioGroup.Radio>
+ </field.Control>
</form.Field>
+ {{#if (eq transientData.og_image_source "uploaded")}}
+ <form.Field
+ @name="opengraph_image"
+ @title={{i18n "admin.config.logo.form.opengraph_image.title"}}
+ @description={{i18n
+ "admin.config.logo.form.opengraph_image.description"
+ }}
+ @onSet={{fn this.handleUpload "opengraph_image"}}
+ @type="image"
+ as |field|
+ >
+ <field.Control
+ @type="branding"
+ @placeholderUrl={{this.placeholders.opengraph_image}}
+ />
+ </form.Field>
+ {{else if (eq transientData.og_image_source "generated")}}
+ <OgImagePreview />
+ {{/if}}
</:content>
</AdminConfigAreaCardSection>
<form.Submit />
diff --git a/frontend/discourse/admin/components/og-image-preview.gjs b/frontend/discourse/admin/components/og-image-preview.gjs
new file mode 100644
index 00000000000..0fe14ff04a7
--- /dev/null
+++ b/frontend/discourse/admin/components/og-image-preview.gjs
@@ -0,0 +1,98 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { action } from "@ember/object";
+import Form from "discourse/components/form";
+import { ajax } from "discourse/lib/ajax";
+import { extractError } from "discourse/lib/ajax-error";
+import { i18n } from "discourse-i18n";
+
+export default class OgImagePreview extends Component {
+ @tracked imageUrl = null;
+ @tracked loading = false;
+ @tracked errorMessage = null;
+
+ formData = { topic_id: "" };
+
+ @action
+ async generate(data) {
+ if (!data.topic_id) {
+ return;
+ }
+ this.loading = true;
+ this.errorMessage = null;
+ this.imageUrl = null;
+ try {
+ const response = await ajax("/admin/config/logo/og-image-preview", {
+ type: "GET",
+ data: { topic_id: data.topic_id },
+ });
+ this.imageUrl = response.url;
+ } catch (error) {
+ this.errorMessage =
+ extractError(error) ||
+ i18n("admin.config.logo.form.og_image_preview.error");
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ <template>
+ <div class="og-image-preview">
+ <div class="og-image-preview__header">
+ <span class="og-image-preview__title">{{i18n
+ "admin.config.logo.form.og_image_preview.title"
+ }}</span>
+ </div>
+ <p class="og-image-preview__description">{{i18n
+ "admin.config.logo.form.og_image_preview.description"
+ }}</p>
+ <Form
+ @onSubmit={{this.generate}}
+ @data={{this.formData}}
+ class="og-image-preview__form"
+ as |form|
+ >
+ <div class="og-image-preview__controls">
+ <form.Field
+ @name="topic_id"
+ @title={{i18n
+ "admin.config.logo.form.og_image_preview.topic_id_label"
+ }}
+ @format="small"
+ @type="input"
+ as |field|
+ >
+ <field.Control
+ placeholder={{i18n
+ "admin.config.logo.form.og_image_preview.topic_id_placeholder"
+ }}
+ />
+ </form.Field>
+ <form.Submit
+ @icon="arrows-rotate"
+ @label="admin.config.logo.form.og_image_preview.generate"
+ @disabled={{this.loading}}
+ class="btn-small og-image-preview__generate"
+ />
+ </div>
+ </Form>
+ <div class="og-image-preview__frame">
+ {{#if this.loading}}
+ <div class="og-image-preview__loading">{{i18n "loading"}}</div>
+ {{else if this.errorMessage}}
+ <div class="og-image-preview__error">{{this.errorMessage}}</div>
+ {{else if this.imageUrl}}
+ <img
+ src={{this.imageUrl}}
+ class="og-image-preview__image"
+ alt={{i18n "admin.config.logo.form.og_image_preview.title"}}
+ />
+ {{else}}
+ <div class="og-image-preview__placeholder">{{i18n
+ "admin.config.logo.form.og_image_preview.placeholder"
+ }}</div>
+ {{/if}}
+ </div>
+ </div>
+ </template>
+}
diff --git a/lib/cooked_post_processor.rb b/lib/cooked_post_processor.rb
index 6f778ba6b60..e85c3439016 100644
--- a/lib/cooked_post_processor.rb
+++ b/lib/cooked_post_processor.rb
@@ -160,14 +160,20 @@ class CookedPostProcessor
@post.update_column(:image_upload_id, upload.id) # post
if @post.is_first_post? # topic
@post.topic.update_column(:image_upload_id, upload.id)
+ @post.topic.clear_generated_og_image!
extra_sizes =
ThemeModifierHelper.new(theme_ids: Theme.user_selectable.pluck(:id)).topic_thumbnail_sizes
@post.topic.generate_thumbnails!(extra_sizes: extra_sizes)
end
else
@post.update_column(:image_upload_id, nil) if @post.image_upload_id
- if @post.topic.image_upload_id && @post.is_first_post?
- @post.topic.update_column(:image_upload_id, nil)
+ if @post.is_first_post?
+ topic = @post.topic
+ topic.update_column(:image_upload_id, nil) if topic.image_upload_id
+ if SiteSetting.generate_topic_og_image && topic.og_image_upload_id.nil? &&
+ TopicOgImageGenerator.eligible?(topic)
+ Jobs.enqueue(:generate_topic_og_image, topic_id: topic.id)
+ end
end
nil
end
diff --git a/lib/topic_og_image_generator.rb b/lib/topic_og_image_generator.rb
new file mode 100644
index 00000000000..0cc59c2ad29
--- /dev/null
+++ b/lib/topic_og_image_generator.rb
@@ -0,0 +1,372 @@
+# frozen_string_literal: true
+
+class TopicOgImageGenerator
+ OG_WIDTH = 1200
+ OG_HEIGHT = 630
+ MAX_TITLE_LENGTH = 100
+ MAX_TITLE_LINES = 2
+ TITLE_LINE_CHARS = 34
+ LOGO_HEIGHT = 100
+ LOGO_WIDTH = 300
+ AVATAR_SIZE = 72
+ SIDE_MARGIN = 80
+ FONT_FAMILY = "sans-serif"
+
+ # OG images are embedded in public topic pages for external crawlers and
+ # link previewers, so we must not generate them for content that is not
+ # publicly visible (PMs or topics in read-restricted categories).
+ def self.eligible?(topic)
+ return false if topic.nil?
+ return false if SiteSetting.login_required
+ return false if topic.private_message?
+ return false if topic.category&.read_restricted?
+ true
+ end
+
+ def initialize(topic)
+ @topic = topic
+ end
+
+ # Generates the OG image, persists as an Upload, and returns it (or nil on failure).
+ def generate
+ svg = build_svg
+ png = render_png(svg)
+ return nil if png.nil?
+ create_upload(png)
+ end
+
+ # Renders the OG image to PNG bytes without persisting an Upload. Used by the
+ # admin preview endpoint to avoid producing orphaned uploads on every click.
+ def generate_bytes
+ svg = build_svg
+ render_png(svg)
+ end
+
+ private
+
+ def build_svg
+ title = truncated_title
+ category_name = @topic.category&.name || ""
+ category_color = @topic.category&.color || "888888"
+ like_count = @topic.like_count || 0
+ posts_count = [@topic.posts_count - 1, 0].max
+ read_time = calculate_read_time
+ colors = fetch_colors
+ logo_upload = SiteSetting.logo.presence || SiteSetting.logo_small
+ logo_data_uri = fetch_as_data_uri(logo_upload&.url)
+
+ title_lines = word_wrap(title, TITLE_LINE_CHARS)
+ truncated = title_lines.length > MAX_TITLE_LINES
+ display_lines = title_lines.take(MAX_TITLE_LINES)
+ if truncated
+ last = display_lines.last
+ display_lines[-1] = (
+ if last.length > TITLE_LINE_CHARS - 1
+ "#{last[0...TITLE_LINE_CHARS - 1]}…"
+ else
+ "#{last}…"
+ end
+ )
+ end
+
+ title_start_y = 190
+ title_end_y = title_start_y + ((display_lines.length - 1) * 58)
+ author_y = title_end_y + 55
+
+ author = @topic.user
+ avatar_data_uri =
+ author ? fetch_as_data_uri(author.avatar_template_url.gsub("{size}", "120")) : nil
+ username = author&.username
+ created_at = @topic.created_at&.strftime("%b %-d, %Y")
+
+ logo_y = OG_HEIGHT - 60 - LOGO_HEIGHT
+ stats_y = OG_HEIGHT - 60 - (LOGO_HEIGHT / 2) + 15
+
+ <<~SVG
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="#{OG_WIDTH}" height="#{OG_HEIGHT}" viewBox="0 0 #{OG_WIDTH} #{OG_HEIGHT}">
+ <defs>
+ <clipPath id="avatar-clip">
+ <rect x="#{SIDE_MARGIN}" y="#{author_y}" width="#{AVATAR_SIZE}" height="#{AVATAR_SIZE}" rx="20"/>
+ </clipPath>
+ </defs>
+
+ <!-- Background -->
+ <rect width="#{OG_WIDTH}" height="#{OG_HEIGHT}" fill="##{colors[:secondary]}"/>
+
+ <!-- Top accent bar -->
+ <rect width="#{OG_WIDTH}" height="18" fill="##{colors[:tertiary]}"/>
+
+ <!-- Category pill -->
+ #{category_pill_svg(category_name, category_color, SIDE_MARGIN, 60)}
+
+ <!-- Title -->
+ #{title_svg(display_lines, colors[:primary], SIDE_MARGIN, title_start_y)}
+
+ <!-- Author -->
+ #{author_svg(avatar_data_uri, username, created_at, colors, SIDE_MARGIN, author_y)}
+
+ <!-- Site logo -->
+ #{logo_svg(logo_data_uri, logo_upload, SIDE_MARGIN, logo_y)}
+
+ <!-- Stats -->
+ #{stats_svg(like_count, posts_count, read_time, colors, OG_WIDTH - SIDE_MARGIN, stats_y)}
+
+ <!-- Site domain -->
+ #{domain_svg(colors, OG_WIDTH - SIDE_MARGIN, 88)}
+ </svg>
+ SVG
+ end
+
+ # Category pill size. Character-width heuristic is approximate and tuned for a
+ # generic sans-serif at font-size 24; long / non-Latin names are truncated
+ # here and the rect is capped to the canvas width so we never render past the
+ # right edge. Non-Latin glyphs may not fill the pill perfectly but will stay
+ # visually contained.
+ def category_pill_svg(name, color, x, y)
+ return "" if name.blank?
+
+ pill_padding = 16
+ max_pill_width = OG_WIDTH - (2 * SIDE_MARGIN)
+ pill_width = [name.length * 14.5 + (pill_padding * 2), max_pill_width].min
+ max_name_chars = [((pill_width - (pill_padding * 2)) / 14.5).floor, 1].max
+ display_name = name.length > max_name_chars ? "#{name[0...[max_name_chars - 1, 1].max]}…" : name
+
+ <<~SVG
+ <rect x="#{x}" y="#{y}" width="#{pill_width}" height="40" rx="6" fill="##{color}" fill-opacity="0.15"/>
+ <text x="#{x + pill_padding}" y="#{y + 30}" font-family="#{FONT_FAMILY}" font-size="24" font-weight="600" fill="##{color}">#{escape_xml(display_name)}</text>
+ SVG
+ end
+
+ def title_svg(lines, primary_color, x, start_y)
+ lines
+ .each_with_index
+ .map do |line, i|
+ y = start_y + (i * 68)
+ %(<text x="#{x}" y="#{y}" font-family="#{FONT_FAMILY}" font-size="62" font-weight="700" fill="##{primary_color}">#{escape_xml(line)}</text>)
+ end
+ .join("\n ")
+ end
+
+ def author_svg(avatar_data_uri, username, created_at, colors, x, y)
+ return "" if username.blank?
+
+ parts = []
+
+ parts << <<~SVG.strip if avatar_data_uri.present?
+ <image x="#{x}" y="#{y}" width="#{AVATAR_SIZE}" height="#{AVATAR_SIZE}" href="#{avatar_data_uri}" clip-path="url(#avatar-clip)"/>
+ <rect x="#{x}" y="#{y}" width="#{AVATAR_SIZE}" height="#{AVATAR_SIZE}" rx="20" fill="none" stroke="##{colors[:secondary]}" stroke-opacity="0.1" stroke-width="1"/>
+ SVG
+
+ text_x = avatar_data_uri.present? ? x + AVATAR_SIZE + 32 : x
+ text_y = y + (AVATAR_SIZE / 2) + 8
+
+ author_text = username
+ author_text = "#{author_text} · #{created_at}" if created_at.present?
+
+ parts << %(<text x="#{text_x}" y="#{text_y}" font-family="#{FONT_FAMILY}" font-size="34" font-weight="400" fill="##{colors[:primary]}" opacity="0.6">#{escape_xml(author_text)}</text>)
+
+ parts.join("\n ")
+ end
+
+ def logo_svg(logo_data_uri, upload, x, y)
+ return "" if logo_data_uri.blank?
+
+ orig_w = upload&.width.to_f
+ orig_h = upload&.height.to_f
+
+ if orig_w > 0 && orig_h > 0
+ scale = [LOGO_WIDTH.to_f / orig_w, LOGO_HEIGHT.to_f / orig_h].min
+ w = (orig_w * scale).round
+ h = (orig_h * scale).round
+ else
+ w = LOGO_WIDTH
+ h = LOGO_HEIGHT
+ end
+
+ offset_y = y + ((LOGO_HEIGHT - h) / 2)
+
+ <<~SVG
+ <image x="#{x}" y="#{offset_y}" width="#{w}" height="#{h}" href="#{logo_data_uri}"/>
+ SVG
+ end
+
+ def stats_svg(likes, replies, read_time, colors, right_x, y)
+ items = []
+ items << "#{read_time}m read" if read_time && read_time >= 1
+ items << "#{replies} #{replies == 1 ? "reply" : "replies"}" if replies > 0
+ items << "#{likes} #{likes == 1 ? "like" : "likes"}" if likes > 0
+ return "" if items.empty?
+
+ text = items.join(" · ")
+ %(<text x="#{right_x}" y="#{y}" font-family="#{FONT_FAMILY}" font-size="30" font-weight="400" fill="##{colors[:primary]}" opacity="0.5" text-anchor="end">#{escape_xml(text)}</text>)
+ end
+
+ def domain_svg(colors, right_x, y)
+ domain = Discourse.current_hostname
+ return "" if domain.blank?
+
+ %(<text x="#{right_x}" y="#{y}" font-family="#{FONT_FAMILY}" font-size="30" font-weight="400" fill="##{colors[:primary]}" opacity="0.5" text-anchor="end">#{escape_xml(domain)}</text>)
+ end
+
+ def calculate_read_time
+ return nil if @topic.word_count.to_i <= 0 || SiteSetting.read_time_word_count.to_i <= 0
+
+ min_post_read_time = 4.0
+ [
+ @topic.word_count / SiteSetting.read_time_word_count,
+ @topic.posts_count * min_post_read_time / 60,
+ ].max.ceil
+ end
+
+ def truncated_title
+ title = @topic.title || ""
+ title.length > MAX_TITLE_LENGTH ? "#{title[0...MAX_TITLE_LENGTH - 1]}…" : title
+ end
+
+ # Wraps by whitespace when possible; falls back to grapheme-boundary splits
+ # for runs longer than max_chars (e.g. CJK titles with no spaces, long URLs)
+ # so the title doesn't overflow the canvas.
+ def word_wrap(text, max_chars)
+ lines = []
+ current_line = +""
+
+ text.split.each do |word|
+ chunks = word.length > max_chars ? split_chunks(word, max_chars) : [word]
+
+ chunks.each do |chunk|
+ if current_line.empty?
+ current_line = chunk.dup
+ elsif (current_line.length + 1 + chunk.length) <= max_chars
+ current_line << " " << chunk
+ else
+ lines << current_line
+ current_line = chunk.dup
+ end
+ end
+ end
+
+ lines << current_line if current_line.present?
+ lines
+ end
+
+ def split_chunks(word, max_chars)
+ word.grapheme_clusters.each_slice(max_chars).map(&:join)
+ end
+
+ def fetch_colors
+ scheme = Theme.find_by(id: SiteSetting.default_theme_id)&.color_scheme
+ if scheme
+ resolved = scheme.resolved_colors
+ {
+ primary: resolved["primary"] || "000000",
+ secondary: resolved["secondary"] || "ffffff",
+ tertiary: resolved["tertiary"] || "0088cc",
+ }
+ else
+ base = ColorScheme.base_colors
+ {
+ primary: base["primary"] || "000000",
+ secondary: base["secondary"] || "ffffff",
+ tertiary: base["tertiary"] || "0088cc",
+ }
+ end
+ end
+
+ def fetch_as_data_uri(url)
+ return nil if url.blank?
+
+ absolute_url = get_absolute_url(url)
+ tmp =
+ FileHelper.download(
+ absolute_url,
+ max_file_size: 1.megabyte,
+ tmp_file_name: "og_image_asset",
+ follow_redirect: true,
+ read_timeout: 10,
+ )
+ return nil if tmp.nil?
+
+ path =
+ (
+ begin
+ URI.parse(absolute_url).path
+ rescue StandardError
+ absolute_url
+ end
+ )
+ content_type = MiniMime.lookup_by_filename(path)&.content_type || "image/png"
+ encoded = Base64.strict_encode64(tmp.read)
+ "data:#{content_type};base64,#{encoded}"
+ rescue => e
+ Discourse.warn("Failed to fetch image for OG generation", url: url, error: e.message)
+ nil
+ ensure
+ tmp&.close
+ tmp&.unlink if tmp.respond_to?(:unlink)
+ end
+
+ def get_absolute_url(url)
+ return url if url.start_with?("http")
+ return "https:#{url}" if url.start_with?("//")
+ "#{Discourse.base_url_no_prefix}#{url}"
+ end
+
+ def escape_xml(text)
+ text
+ .to_s
+ .gsub("&", "&amp;")
+ .gsub("<", "&lt;")
+ .gsub(">", "&gt;")
+ .gsub("'", "&apos;")
+ .gsub('"', "&quot;")
+ end
+
+ def render_png(svg)
+ Dir.mktmpdir("topic_og") do |dir|
+ svg_path = File.join(dir, "og.svg")
+ png_path = File.join(dir, "og.png")
+
+ File.write(svg_path, svg)
+
+ Discourse::Utils.execute_command(
+ "nice",
+ "-n",
+ "10",
+ "convert",
+ "-background",
+ "none",
+ "-size",
+ "#{OG_WIDTH}x#{OG_HEIGHT}",
+ svg_path,
+ "-depth",
+ "8",
+ "-define",
+ "png:compression-level=9",
+ png_path,
+ timeout: 20_000,
+ )
+
+ return nil unless File.exist?(png_path)
+ FileHelper.optimize_image!(png_path)
+ File.binread(png_path)
+ end
+ rescue Discourse::Utils::CommandError => e
+ Discourse.warn("Failed to render topic OG image", topic_id: @topic.id, error: e.message)
+ nil
+ end
+
+ def create_upload(png_bytes)
+ Tempfile.create(["topic-og-#{@topic.id}", ".png"], binmode: true) do |tmp|
+ tmp.write(png_bytes)
+ tmp.rewind
+ return(
+ UploadCreator.new(
+ tmp,
+ "topic-og-#{@topic.id}.png",
+ type: "topic_og_image",
+ skip_validations: true,
+ ).create_for(Discourse.system_user.id)
+ )
+ end
+ end
+end
diff --git a/lib/topic_view.rb b/lib/topic_view.rb
index 25aba9cc037..ca7f04691d3 100644
--- a/lib/topic_view.rb
+++ b/lib/topic_view.rb
@@ -421,12 +421,20 @@ class TopicView
end
def image_url
- return @topic.image_url if @post_number == 1
- desired_post&.image_url
+ if @post_number == 1
+ @topic.image_url || og_image_url
+ else
+ desired_post&.image_url
+ end
end
def image_upload
- @image_upload ||= @post_number == 1 ? @topic.image_upload : desired_post&.image_upload
+ @image_upload ||=
+ if @post_number == 1
+ @topic.image_upload || og_image_upload
+ else
+ desired_post&.image_upload
+ end
end
def image_width
@@ -442,6 +450,18 @@ class TopicView
MiniMime.lookup_by_extension(ext)&.content_type if ext.present?
end
+ def og_image_upload
+ return unless SiteSetting.generate_topic_og_image
+ return if !TopicOgImageGenerator.eligible?(@topic)
+ @topic.og_image_upload
+ end
+
+ def og_image_url
+ upload = og_image_upload
+ return unless upload
+ UrlHelper.cook_url(upload.url, secure: upload.secure?)
+ end
+
def filter_posts(opts = {})
if opts[:post_number].present?
filter_posts_near(opts[:post_number].to_i)
diff --git a/lib/upload_creator.rb b/lib/upload_creator.rb
index eac3ab09bfd..c698d349915 100644
--- a/lib/upload_creator.rb
+++ b/lib/upload_creator.rb
@@ -368,6 +368,7 @@ class UploadCreator
end
def convert_to_jpeg!
+ return if @opts[:type] == "topic_og_image"
return if @opts[:for_site_setting] || ADMIN_ASSET_TYPES.include?(@opts[:type])
return if filesize < MIN_CONVERT_TO_JPEG_BYTES_SAVED
diff --git a/spec/jobs/regular/generate_topic_og_image_spec.rb b/spec/jobs/regular/generate_topic_og_image_spec.rb
new file mode 100644
index 00000000000..81bdb76e2c3
--- /dev/null
+++ b/spec/jobs/regular/generate_topic_og_image_spec.rb
@@ -0,0 +1,72 @@
+# frozen_string_literal: true
+
+RSpec.describe Jobs::GenerateTopicOgImage do
+ fab!(:topic)
+
+ before { SiteSetting.generate_topic_og_image = true }
+
+ it "does nothing when the setting is disabled" do
+ SiteSetting.generate_topic_og_image = false
+ TopicOgImageGenerator.any_instance.expects(:generate).never
+ described_class.new.execute(topic_id: topic.id)
+ end
+
+ it "does nothing when login_required is enabled" do
+ SiteSetting.login_required = true
+ TopicOgImageGenerator.any_instance.expects(:generate).never
+ described_class.new.execute(topic_id: topic.id)
+ expect(topic.reload.og_image_upload_id).to be_nil
+ end
+
+ it "clears stale generated OG images when topic has a user-uploaded image" do
+ old_upload = Fabricate(:upload)
+ topic.update_column(:image_upload_id, Fabricate(:upload).id)
+ topic.update_column(:og_image_upload_id, old_upload.id)
+ UploadReference.ensure_exist!(upload_ids: [old_upload.id], target: topic)
+
+ TopicOgImageGenerator.any_instance.expects(:generate).never
+ described_class.new.execute(topic_id: topic.id)
+
+ expect(topic.reload.og_image_upload_id).to be_nil
+ expect(UploadReference.exists?(upload_id: old_upload.id, target: topic)).to eq(false)
+ end
+
+ it "replaces an existing generated OG image and cleans up the old reference" do
+ old_upload = Fabricate(:upload)
+ topic.update_column(:og_image_upload_id, old_upload.id)
+ UploadReference.ensure_exist!(upload_ids: [old_upload.id], target: topic)
+
+ new_upload = Fabricate(:upload)
+ TopicOgImageGenerator.any_instance.expects(:generate).returns(new_upload)
+
+ described_class.new.execute(topic_id: topic.id)
+
+ expect(topic.reload.og_image_upload_id).to eq(new_upload.id)
+ expect(UploadReference.exists?(upload_id: new_upload.id, target: topic)).to eq(true)
+ expect(UploadReference.exists?(upload_id: old_upload.id, target: topic)).to eq(false)
+ end
+
+ it "does nothing for personal messages" do
+ pm = Fabricate(:private_message_topic)
+ TopicOgImageGenerator.any_instance.expects(:generate).never
+ described_class.new.execute(topic_id: pm.id)
+ expect(pm.reload.og_image_upload_id).to be_nil
+ end
+
+ it "does nothing for topics in a read-restricted category" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ topic.update!(category: private_category)
+ TopicOgImageGenerator.any_instance.expects(:generate).never
+ described_class.new.execute(topic_id: topic.id)
+ expect(topic.reload.og_image_upload_id).to be_nil
+ end
+
+ it "generates an OG image for a topic without an image" do
+ upload = Fabricate(:upload)
+ TopicOgImageGenerator.any_instance.expects(:generate).returns(upload)
+ described_class.new.execute(topic_id: topic.id)
+ topic.reload
+ expect(topic.og_image_upload_id).to eq(upload.id)
+ expect(UploadReference.exists?(upload_id: upload.id, target: topic)).to eq(true)
+ end
+end
diff --git a/spec/lib/cooked_post_processor_spec.rb b/spec/lib/cooked_post_processor_spec.rb
index f5d8c2948ac..dd82f468d7a 100644
--- a/spec/lib/cooked_post_processor_spec.rb
+++ b/spec/lib/cooked_post_processor_spec.rb
@@ -900,6 +900,74 @@ RSpec.describe CookedPostProcessor do
end
end
+ context "with topic og image generation" do
+ fab!(:post) { Fabricate(:post, user: user_with_auto_groups, raw: "no image in this post") }
+
+ it "enqueues the generator job when the first post has no image and setting is on" do
+ SiteSetting.generate_topic_og_image = true
+ expect { CookedPostProcessor.new(post).post_process }.to change {
+ Jobs::GenerateTopicOgImage.jobs.size
+ }.by(1)
+ end
+
+ it "does not enqueue when the setting is off" do
+ SiteSetting.generate_topic_og_image = false
+ expect { CookedPostProcessor.new(post).post_process }.not_to change {
+ Jobs::GenerateTopicOgImage.jobs.size
+ }
+ end
+
+ it "does not enqueue when the topic already has a generated OG image" do
+ SiteSetting.generate_topic_og_image = true
+ post.topic.update_column(:og_image_upload_id, Fabricate(:upload).id)
+ expect { CookedPostProcessor.new(post).post_process }.not_to change {
+ Jobs::GenerateTopicOgImage.jobs.size
+ }
+ end
+
+ it "does not enqueue for non-first posts" do
+ SiteSetting.generate_topic_og_image = true
+ reply =
+ Fabricate(:post, user: user_with_auto_groups, topic: post.topic, raw: "no image reply")
+ expect { CookedPostProcessor.new(reply).post_process }.not_to change {
+ Jobs::GenerateTopicOgImage.jobs.size
+ }
+ end
+
+ it "does not enqueue for personal messages" do
+ SiteSetting.generate_topic_og_image = true
+ pm_post = Fabricate(:private_message_post, user: user_with_auto_groups)
+ expect { CookedPostProcessor.new(pm_post).post_process }.not_to change {
+ Jobs::GenerateTopicOgImage.jobs.size
+ }
+ end
+
+ it "does not enqueue for topics in a read-restricted category" do
+ SiteSetting.generate_topic_og_image = true
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ post.topic.update!(category: private_category)
+ expect { CookedPostProcessor.new(post).post_process }.not_to change {
+ Jobs::GenerateTopicOgImage.jobs.size
+ }
+ end
+
+ it "clears the generated OG image when the first post has an image" do
+ SiteSetting.generate_topic_og_image = true
+ FastImage.stubs(:size)
+ old_upload = Fabricate(:upload)
+ image_post = Fabricate(:post_with_uploaded_image, user: user_with_auto_groups)
+ image_post.topic.update_column(:og_image_upload_id, old_upload.id)
+ UploadReference.ensure_exist!(upload_ids: [old_upload.id], target: image_post.topic)
+
+ CookedPostProcessor.new(image_post).post_process
+
+ expect(image_post.topic.reload.og_image_upload_id).to be_nil
+ expect(UploadReference.exists?(upload_id: old_upload.id, target: image_post.topic)).to eq(
+ false,
+ )
+ end
+ end
+
it "prioritizes data-thumbnail images" do
upload1 = Fabricate(:image_upload, width: 1750, height: 2000)
upload2 = Fabricate(:image_upload, width: 1750, height: 2000)
diff --git a/spec/lib/topic_og_image_generator_spec.rb b/spec/lib/topic_og_image_generator_spec.rb
new file mode 100644
index 00000000000..9bd49d48258
--- /dev/null
+++ b/spec/lib/topic_og_image_generator_spec.rb
@@ -0,0 +1,138 @@
+# frozen_string_literal: true
+
+RSpec.describe TopicOgImageGenerator do
+ fab!(:category) { Fabricate(:category, name: "Feature", color: "0088cc") }
+ fab!(:topic) do
+ Fabricate(
+ :topic,
+ title: "How to configure your Discourse site for best results",
+ category: category,
+ )
+ end
+
+ # 1x1 transparent PNG as a test fixture for data URI embedding
+ TINY_PNG_DATA_URI =
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg=="
+
+ before do
+ topic.update_columns(like_count: 42, posts_count: 13)
+ TopicOgImageGenerator.any_instance.stubs(:fetch_as_data_uri).returns(TINY_PNG_DATA_URI)
+ end
+
+ describe "#generate" do
+ it "generates a PNG upload for a topic" do
+ generator = described_class.new(topic)
+ # Stub the ImageMagick rasterization: rendering an SVG to PNG depends on the
+ # ImageMagick/font setup of the host, which isn't reliable across CI and dev
+ # environments. Here we assert that #generate turns rendered bytes into a
+ # proper PNG Upload.
+ generator.stubs(:render_png).returns(File.binread(file_from_fixtures("logo.png").path))
+ upload = generator.generate
+
+ expect(upload).to be_a(Upload)
+ expect(upload.errors).to be_empty
+ expect(upload.extension).to eq("png")
+ expect(upload.original_filename).to eq("topic-og-#{topic.id}.png")
+ end
+ end
+
+ describe ".eligible?" do
+ it "returns true for a public topic in a public category" do
+ expect(described_class.eligible?(topic)).to eq(true)
+ end
+
+ it "returns false when topic is nil" do
+ expect(described_class.eligible?(nil)).to eq(false)
+ end
+
+ it "returns false when login_required is enabled" do
+ SiteSetting.login_required = true
+ expect(described_class.eligible?(topic)).to eq(false)
+ end
+
+ it "returns false for a personal message" do
+ pm = Fabricate(:private_message_topic)
+ expect(described_class.eligible?(pm)).to eq(false)
+ end
+
+ it "returns false for a topic in a read-restricted category" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ topic.update!(category: private_category)
+ expect(described_class.eligible?(topic)).to eq(false)
+ end
+ end
+
+ describe "#build_svg (via send)" do
+ it "includes the topic title limited to two lines" do
+ generator = described_class.new(topic)
+ svg = generator.send(:build_svg)
+
+ expect(svg).to include("How to configure your")
+ title_line_count = svg.scan(/font-size="62"/).length
+ expect(title_line_count).to eq(2)
+ end
+
+ it "adds ellipsis when title exceeds two lines" do
+ long_title =
+ "This is a very long topic title that will definitely wrap onto more than two lines and require truncation with an ellipsis at the end"
+ topic.update!(title: long_title)
+
+ generator = described_class.new(topic)
+ svg = generator.send(:build_svg)
+
+ title_line_count = svg.scan(/font-size="62"/).length
+ expect(title_line_count).to eq(TopicOgImageGenerator::MAX_TITLE_LINES)
+ expect(svg).to include("…")
+ end
+
+ it "includes category name" do
+ generator = described_class.new(topic)
+ svg = generator.send(:build_svg)
+
+ expect(svg).to include("Feature")
+ expect(svg).to include("0088cc")
+ end
+
+ it "includes stats separated by middle dots" do
+ generator = described_class.new(topic)
+ svg = generator.send(:build_svg)
+
+ expect(svg).to include("12 replies · 42 likes")
+ end
+
+ it "includes author avatar and username" do
+ generator = described_class.new(topic)
+ svg = generator.send(:build_svg)
+
+ expect(svg).to include(topic.user.username)
+ expect(svg).to include("avatar-clip")
+ expect(svg).to include(topic.created_at.strftime("%b %-d, %Y"))
+ end
+
+ it "embeds images as data URIs" do
+ generator = described_class.new(topic)
+ svg = generator.send(:build_svg)
+
+ expect(svg).to include("data:image/png;base64,")
+ expect(svg).not_to match(%r{href="https?://})
+ end
+
+ it "escapes XML entities in title" do
+ topic.update!(title: "Using <script> tags & other HTML elements safely")
+ generator = described_class.new(topic)
+ svg = generator.send(:build_svg)
+
+ expect(svg).not_to include("<script>")
+ expect(svg).to include("&lt;script&gt;")
+ expect(svg).to include("&amp;")
+ end
+
+ it "does not include site name text" do
+ SiteSetting.title = "My Test Forum"
+ generator = described_class.new(topic)
+ svg = generator.send(:build_svg)
+
+ expect(svg).not_to include("My Test Forum")
+ end
+ end
+end
diff --git a/spec/lib/topic_view_spec.rb b/spec/lib/topic_view_spec.rb
index 8820ee8a484..88099f4cae6 100644
--- a/spec/lib/topic_view_spec.rb
+++ b/spec/lib/topic_view_spec.rb
@@ -1108,6 +1108,19 @@ RSpec.describe TopicView do
expect(topic_view_for_post(2).image_url).to eq(nil)
expect(topic_view_for_post(3).image_url).to end_with(post3_upload.url)
end
+
+ it "uses the generated OG image only for eligible topics" do
+ SiteSetting.generate_topic_og_image = true
+ og_upload = Fabricate(:image_upload)
+ topic.update_column(:og_image_upload_id, og_upload.id)
+
+ expect(topic_view_for_post(1).image_url).to end_with(og_upload.url)
+
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ topic.update_column(:category_id, private_category.id)
+
+ expect(TopicView.new(topic.id, admin, post_number: 1).image_url).to eq(nil)
+ end
end
end
diff --git a/spec/models/topic_spec.rb b/spec/models/topic_spec.rb
index a41dc3fb233..b7163e26594 100644
--- a/spec/models/topic_spec.rb
+++ b/spec/models/topic_spec.rb
@@ -2814,6 +2814,63 @@ RSpec.describe Topic do
end
end
+ describe "#regenerate_og_image" do
+ fab!(:topic)
+
+ before { SiteSetting.generate_topic_og_image = true }
+
+ it "clears generated OG images when the topic becomes ineligible" do
+ old_upload = Fabricate(:upload)
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ topic.update_column(:og_image_upload_id, old_upload.id)
+ UploadReference.ensure_exist!(upload_ids: [old_upload.id], target: topic)
+
+ topic.update!(category: private_category)
+
+ expect(topic.reload.og_image_upload_id).to be_nil
+ expect(UploadReference.exists?(upload_id: old_upload.id, target: topic)).to eq(false)
+ end
+
+ it "enqueues regeneration after each ten replies" do
+ topic.update_columns(og_image_upload_id: Fabricate(:upload).id, posts_count: 10)
+
+ expect { Topic.next_post_number(topic.id, post: true, reply: true) }.to change {
+ Jobs::GenerateTopicOgImage.jobs.size
+ }.by(1)
+
+ expect { Topic.next_post_number(topic.id, post: true, reply: true) }.not_to change {
+ Jobs::GenerateTopicOgImage.jobs.size
+ }
+
+ topic.update_column(:posts_count, 20)
+
+ expect { Topic.next_post_number(topic.id, post: true, reply: true) }.to change {
+ Jobs::GenerateTopicOgImage.jobs.size
+ }.by(1)
+ end
+
+ it "enqueues regeneration after each ten likes" do
+ post = Fabricate(:post, topic: topic)
+ topic.update_columns(og_image_upload_id: Fabricate(:upload).id, like_count: 9)
+
+ post.update_column(:like_count, 10)
+
+ expect { topic.update_action_counts }.to change { Jobs::GenerateTopicOgImage.jobs.size }.by(1)
+
+ post.update_column(:like_count, 11)
+
+ expect { topic.reload.update_action_counts }.not_to change {
+ Jobs::GenerateTopicOgImage.jobs.size
+ }
+
+ post.update_column(:like_count, 20)
+
+ expect { topic.reload.update_action_counts }.to change {
+ Jobs::GenerateTopicOgImage.jobs.size
+ }.by(1)
+ end
+ end
+
describe "trash!" do
fab!(:topic)
diff --git a/spec/requests/admin/config/logo_controller_spec.rb b/spec/requests/admin/config/logo_controller_spec.rb
new file mode 100644
index 00000000000..f82b71c421c
--- /dev/null
+++ b/spec/requests/admin/config/logo_controller_spec.rb
@@ -0,0 +1,96 @@
+# frozen_string_literal: true
+
+RSpec.describe Admin::Config::LogoController do
+ fab!(:admin)
+ fab!(:moderator)
+ fab!(:user)
+ fab!(:topic)
+
+ describe "#og_image_preview" do
+ before do
+ TopicOgImageGenerator.any_instance.stubs(:generate_bytes).returns("\x89PNG\r\n\x1A\n".b)
+ end
+
+ context "when logged in as an admin" do
+ before { sign_in(admin) }
+
+ it "returns a base64 data URI for the given topic" do
+ get "/admin/config/logo/og-image-preview.json", params: { topic_id: topic.id }
+ expect(response.status).to eq(200)
+ json = response.parsed_body
+ expect(json["url"]).to start_with("data:image/png;base64,")
+ expect(json["topic_id"]).to eq(topic.id)
+ expect(json["topic_title"]).to eq(topic.title)
+ end
+
+ it "returns 400 when topic_id is missing" do
+ get "/admin/config/logo/og-image-preview.json"
+ expect(response.status).to eq(400)
+ end
+
+ it "returns 404 for a non-existent topic" do
+ get "/admin/config/logo/og-image-preview.json", params: { topic_id: 0 }
+ expect(response.status).to eq(404)
+ end
+
+ it "returns 422 when generation fails" do
+ TopicOgImageGenerator.any_instance.stubs(:generate_bytes).returns(nil)
+ get "/admin/config/logo/og-image-preview.json", params: { topic_id: topic.id }
+ expect(response.status).to eq(422)
+ end
+
+ it "returns 422 when login_required is enabled" do
+ SiteSetting.login_required = true
+ TopicOgImageGenerator.any_instance.expects(:generate_bytes).never
+ get "/admin/config/logo/og-image-preview.json", params: { topic_id: topic.id }
+ expect(response.status).to eq(422)
+ end
+
+ it "returns 422 for personal messages without attempting to generate" do
+ pm = Fabricate(:private_message_topic)
+ TopicOgImageGenerator.any_instance.expects(:generate_bytes).never
+ get "/admin/config/logo/og-image-preview.json", params: { topic_id: pm.id }
+ expect(response.status).to eq(422)
+ end
+
+ it "returns 422 for topics in a read-restricted category" do
+ private_category = Fabricate(:private_category, group: Fabricate(:group))
+ topic.update!(category: private_category)
+ TopicOgImageGenerator.any_instance.expects(:generate_bytes).never
+ get "/admin/config/logo/og-image-preview.json", params: { topic_id: topic.id }
+ expect(response.status).to eq(422)
+ end
+
+ it "does not persist an Upload" do
+ expect {
+ get "/admin/config/logo/og-image-preview.json", params: { topic_id: topic.id }
+ }.not_to change { Upload.count }
+ end
+ end
+
+ context "when logged in as a moderator" do
+ before { sign_in(moderator) }
+
+ it "denies access" do
+ get "/admin/config/logo/og-image-preview.json", params: { topic_id: topic.id }
+ expect(response.status).to eq(403)
+ end
+ end
+
+ context "when logged in as a regular user" do
+ before { sign_in(user) }
+
+ it "denies access" do
+ get "/admin/config/logo/og-image-preview.json", params: { topic_id: topic.id }
+ expect(response.status).to eq(404)
+ end
+ end
+
+ context "when not logged in" do
+ it "denies access" do
+ get "/admin/config/logo/og-image-preview.json", params: { topic_id: topic.id }
+ expect(response.status).to eq(404)
+ end
+ end
+ end
+end