A platform for community discussion. Free, open, simple.
FEATURE: Native Reddit embeds for oneboxes (#39162)
Rafael dos Santos Silva6096c3551b8c
diff --git a/app/assets/stylesheets/common/base/onebox.scss b/app/assets/stylesheets/common/base/onebox.scssindex d8c7b0ec073..f8ca444163b 100644--- a/app/assets/stylesheets/common/base/onebox.scss+++ b/app/assets/stylesheets/common/base/onebox.scss@@ -950,49 +950,14 @@ aside.onebox.xkcd .onebox-body img {}}-.onebox.reddit {- div.description {- color: var(--primary-med-or-secondary-med);- }-- .onebox-body.reddit-preview-onebox {- display: flex;- gap: 0.75em;-- .reddit-preview-thumbnail {- flex-shrink: 0;- max-width: 150px;-- // neutralize the legacy float/absolute-position system- .aspect-image {- position: relative;- width: auto;- height: auto;- max-width: 100%;- max-height: none;- float: none;- margin: 0;- }-- .aspect-image img,- > img {- position: static;- width: auto;- height: auto;- max-width: 100%;- max-height: 170px;- float: none;- }- }-- .reddit-preview-details {- flex: 1;- min-width: 0;- display: flex;- flex-direction: column;- justify-content: space-between;- }- }+iframe.reddit-onebox {+ width: 100%;+ max-width: 640px;+ display: block;+ margin: 0 auto;+ overflow: hidden;+ border: 0;+ border-radius: var(--d-border-radius);}.onebox.githubfolder {diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 0a4b55e85f5..7eba7ed0b8c 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -1841,9 +1841,6 @@ en:max_oneboxes_per_post: "Set the maximum number of oneboxes that can be included in a single post. Oneboxes provide a preview of linked content within the post."facebook_app_access_token: "A token generated from your Facebook app ID and secret. Used to generate Instagram oneboxes."github_onebox_access_tokens: "A mapping of a GitHub organisation or user to a GitHub access token which is used to generate GitHub oneboxes for private repos, commits, pull requests, issues, and file contents. Without this, only public GitHub URLs will be oneboxed."- reddit_onebox_client_id: "Reddit API OAuth client ID used for authenticated Reddit oneboxes. Create a 'script' type app at reddit.com/prefs/apps to obtain credentials."- reddit_onebox_client_secret: "Reddit API OAuth client secret used for authenticated Reddit oneboxes. Found under the 'script' type app created at reddit.com/prefs/apps."-logo: "The logo image at the top left of your site. Use a wide rectangular image with a height of 120 and an aspect ratio greater than 3:1. If left blank, the site title text will be shown."logo_small: "The small logo image at the top left of your site, seen when scrolling down. Use a square 120 × 120 image. If left blank, a home glyph will be shown."digest_logo: "The alternate logo image used at the top of your site's email summary. Use a wide rectangle image. Don't use an SVG image. If left blank, the image from the `logo` setting will be used."diff --git a/config/site_settings.yml b/config/site_settings.ymlindex 776c0d83110..a3323506fb0 100644--- a/config/site_settings.yml+++ b/config/site_settings.yml@@ -2866,12 +2866,6 @@ onebox:type: listsecret: truelist_type: secret- reddit_onebox_client_id:- default: ""- secret: true- reddit_onebox_client_secret:- default: ""- secret: truespam:add_rel_nofollow_to_user_content: truehide_post_sensitivity:diff --git a/frontend/discourse/app/instance-initializers/onebox-decorators.js b/frontend/discourse/app/instance-initializers/onebox-decorators.jsindex 36317a37c6f..b67edd349da 100644--- a/frontend/discourse/app/instance-initializers/onebox-decorators.js+++ b/frontend/discourse/app/instance-initializers/onebox-decorators.js@@ -1,5 +1,13 @@import { withPluginApi } from "discourse/lib/plugin-api";+const REDDIT_EMBED_ORIGINS = [+ "https://embed.reddit.com",+ "https://sh.reddit.com",+];+const REDDIT_ONEBOX_RESIZE_LISTENER_STATE = Symbol(+ "reddit-onebox-resize-listener-state"+);+export function decorateGithubOneboxBody(element) {const containers = element.querySelectorAll(".onebox.githubcommit .show-more-container, .onebox.githubpullrequest .show-more-container, .onebox.githubissue .show-more-container"@@ -13,6 +21,82 @@ export function decorateGithubOneboxBody(element) {}}+export function handleRedditOneboxResizeMessage(event, root = document) {+ if (!REDDIT_EMBED_ORIGINS.includes(event.origin) || !event.source) {+ return;+ }++ let messageData = event.data;++ if (typeof messageData === "string") {+ try {+ messageData = JSON.parse(messageData);+ } catch {+ return;+ }+ }++ if (messageData?.type !== "resize.embed") {+ return;+ }++ const height = parseInt(messageData.data, 10);++ if (!height) {+ return;+ }++ root.querySelectorAll("iframe.reddit-onebox").forEach((iframe) => {+ if (iframe.contentWindow === event.source) {+ iframe.setAttribute("height", `${height}`);+ }+ });+}++function redditOneboxResizeListenerState(eventTarget) {+ eventTarget[REDDIT_ONEBOX_RESIZE_LISTENER_STATE] ||= {+ activeDecorations: 0,+ listenerAdded: false,+ };++ return eventTarget[REDDIT_ONEBOX_RESIZE_LISTENER_STATE];+}++function addRedditOneboxResizeListener(eventTarget) {+ const state = redditOneboxResizeListenerState(eventTarget);+ state.activeDecorations += 1;++ if (!state.listenerAdded) {+ eventTarget.addEventListener("message", handleRedditOneboxResizeMessage);+ state.listenerAdded = true;+ }++ return () => {+ if (state.activeDecorations > 0) {+ state.activeDecorations -= 1;+ }++ if (state.activeDecorations === 0 && state.listenerAdded) {+ eventTarget.removeEventListener(+ "message",+ handleRedditOneboxResizeMessage+ );+ state.listenerAdded = false;+ }+ };+}++export function decorateRedditOneboxes(+ element,+ eventTarget = typeof window === "undefined" ? null : window+) {+ if (!eventTarget || !element.querySelector("iframe.reddit-onebox")) {+ return;+ }++ return addRedditOneboxResizeListener(eventTarget);+}+function _handleClick(event) {if (!event.target.classList.contains("show-more")) {return;@@ -33,6 +117,7 @@ export default {initialize() {withPluginApi((api) => {api.decorateCookedElement(decorateGithubOneboxBody);+ api.decorateCookedElement((element) => decorateRedditOneboxes(element));});},};diff --git a/frontend/discourse/tests/unit/instance-initializers/onebox-decorators-test.js b/frontend/discourse/tests/unit/instance-initializers/onebox-decorators-test.jsnew file mode 100644index 00000000000..e766119672b--- /dev/null+++ b/frontend/discourse/tests/unit/instance-initializers/onebox-decorators-test.js@@ -0,0 +1,103 @@+import { module, test } from "qunit";+import {+ decorateRedditOneboxes,+ handleRedditOneboxResizeMessage,+} from "discourse/instance-initializers/onebox-decorators";++module("Unit | Instance Initializer | onebox-decorators", function () {+ test("handleRedditOneboxResizeMessage resizes the matching reddit iframe", function (assert) {+ const root = document.createElement("div");+ const iframe = document.createElement("iframe");+ const source = {};++ iframe.className = "reddit-onebox";+ iframe.setAttribute("height", "500");+ Object.defineProperty(iframe, "contentWindow", {+ configurable: true,+ value: source,+ });+ root.appendChild(iframe);++ handleRedditOneboxResizeMessage(+ {+ origin: "https://embed.reddit.com",+ source,+ data: JSON.stringify({ type: "resize.embed", data: 321 }),+ },+ root+ );++ assert.strictEqual(iframe.getAttribute("height"), "321");+ });++ test("handleRedditOneboxResizeMessage ignores unrelated messages", function (assert) {+ const root = document.createElement("div");+ const iframe = document.createElement("iframe");+ const source = {};++ iframe.className = "reddit-onebox";+ iframe.setAttribute("height", "500");+ Object.defineProperty(iframe, "contentWindow", {+ configurable: true,+ value: source,+ });+ root.appendChild(iframe);++ handleRedditOneboxResizeMessage(+ {+ origin: "https://example.com",+ source,+ data: JSON.stringify({ type: "resize.embed", data: 321 }),+ },+ root+ );++ assert.strictEqual(iframe.getAttribute("height"), "500");+ });++ test("decorateRedditOneboxes adds a single global listener and cleans it up", function (assert) {+ const makeRoot = () => {+ const root = document.createElement("div");+ const iframe = document.createElement("iframe");+ iframe.className = "reddit-onebox";+ root.appendChild(iframe);+ return root;+ };++ const eventTarget = {+ addCalls: 0,+ removeCalls: 0,+ addEventListener() {+ this.addCalls += 1;+ },+ removeEventListener() {+ this.removeCalls += 1;+ },+ };++ const cleanupOne = decorateRedditOneboxes(makeRoot(), eventTarget);+ const cleanupTwo = decorateRedditOneboxes(makeRoot(), eventTarget);++ assert.strictEqual(eventTarget.addCalls, 1);++ cleanupOne();+ assert.strictEqual(eventTarget.removeCalls, 0);++ cleanupTwo();+ assert.strictEqual(eventTarget.removeCalls, 1);+ });++ test("decorateRedditOneboxes does nothing without a reddit iframe", function (assert) {+ const root = document.createElement("div");+ const eventTarget = {+ addEventListener() {+ assert.step("addEventListener");+ },+ };++ const cleanup = decorateRedditOneboxes(root, eventTarget);++ assert.strictEqual(cleanup, undefined);+ assert.verifySteps([]);+ });+});diff --git a/lib/onebox/engine/reddit_media_onebox.rb b/lib/onebox/engine/reddit_media_onebox.rbindex 7f46858d0dd..b509fd9b412 100644--- a/lib/onebox/engine/reddit_media_onebox.rb+++ b/lib/onebox/engine/reddit_media_onebox.rb@@ -1,14 +1,12 @@# frozen_string_literal: true-require_relative "../mixins/reddit_auth_header"-module Oneboxmodule Engineclass RedditMediaOneboxinclude Engine- include Onebox::Mixins::RedditAuthHeaderalways_https+ requires_iframe_origins "https://embed.reddit.com", "https://sh.reddit.com"matches_domain("reddit.com","www.reddit.com",@@ -18,130 +16,62 @@ module Onebox)def self.matches_path(path)- path.match?(%r{^/r/[^/]+/comments/[^/]+})+ path.match?(%r{^/(?:r|user)/[^/]+/comments/[^/]+})enddef to_html- post = reddit_post- return nil unless post-- url = Onebox::Helpers.normalize_url_for_output("https://www.reddit.com#{post["permalink"]}")- subreddit_url =- Onebox::Helpers.normalize_url_for_output(- "https://www.reddit.com/#{post["subreddit_name_prefixed"]}",- )- title = CGI.escapeHTML(Onebox::Helpers.truncate(post["title"].to_s, 80))- subreddit = CGI.escapeHTML(post["subreddit_name_prefixed"].to_s)- author = CGI.escapeHTML(post["author"].to_s)- score = post["score"].to_i- num_comments = post["num_comments"].to_i- nsfw_label = post["over_18"] ? " <span class='nsfw'>NSFW</span>" : ""- meta = "#{score} points | #{num_comments} comments — u/#{author}"-- if image_post?(post)- image_url = extract_image_url(post)- return nil unless image_url-- image_url = Onebox::Helpers.normalize_url_for_output(image_url)+ <<~HTML+ <iframe+ class="reddit-onebox"+ src="#{embed_url}"+ width="640"+ height="#{default_height}"+ allowfullscreen+ ></iframe>+ HTML+ end- <<~HTML- <aside class="onebox reddit">- <header class="source">- <img src="https://www.reddit.com/favicon.ico" class="site-icon" width="16" height="16">- <a href="#{subreddit_url}" target="_blank" rel="nofollow ugc noopener">#{subreddit}</a>- </header>- <article class="onebox-body">- <h3><a href="#{url}" target="_blank" rel="nofollow ugc noopener">#{title}#{nsfw_label}</a></h3>- <div class="scale-images">- <img src="#{image_url}" class="scale-image"/>- </div>- <div class="description"><p>#{meta}</p></div>- </article>- </aside>- HTML- elsif video_post?(post)- preview_url = extract_image_url(post)- preview_html =- if preview_url- preview_url = Onebox::Helpers.normalize_url_for_output(preview_url)- "<div class=\"reddit-preview-thumbnail\"><img src=\"#{preview_url}\" class=\"thumbnail\"/></div>"- else- ""- end+ def placeholder_html+ Onebox::Helpers.generic_placeholder_html+ end- <<~HTML- <aside class="onebox reddit">- <header class="source">- <img src="https://www.reddit.com/favicon.ico" class="site-icon" width="16" height="16">- <a href="#{subreddit_url}" target="_blank" rel="nofollow ugc noopener">#{subreddit}</a>- </header>- <article class="onebox-body reddit-preview-onebox">- #{preview_html}- <div class="reddit-preview-details">- <h3><a href="#{url}" target="_blank" rel="nofollow ugc noopener">#{title}#{nsfw_label}</a></h3>- <div class="description"><p>#{meta}</p></div>- </div>- </article>- </aside>- HTML- else- description_html =- if post["is_self"] && post["selftext"].present?- desc = CGI.escapeHTML(Onebox::Helpers.truncate(post["selftext"], 250))- "<div class=\"description\"><p>#{desc}</p></div>"- else- ""- end+ private- <<~HTML- <aside class="onebox reddit">- <header class="source">- <img src="https://www.reddit.com/favicon.ico" class="site-icon" width="16" height="16">- <a href="#{subreddit_url}" target="_blank" rel="nofollow ugc noopener">#{subreddit}</a>- </header>- <article class="onebox-body">- <h3><a href="#{url}" target="_blank" rel="nofollow ugc noopener">#{title}#{nsfw_label}</a></h3>- #{description_html}- <div class="description"><p>#{meta}</p></div>- </article>- </aside>- HTML- end+ def embed_url+ @embed_url ||=+ Onebox::Helpers.normalize_url_for_output(+ URI::HTTPS.build(+ host: "embed.reddit.com",+ path: normalized_path,+ query: URI.encode_www_form(embed_params),+ ).to_s,+ )end- private+ def normalized_path+ return "#{uri.path}/" unless uri.path.end_with?("/")+ uri.path+ end- def reddit_post- return @reddit_post if defined?(@reddit_post)+ def embed_params+ params = { embed: true, ref_source: "embed", ref: "share" }- json_url = @url.sub(%r{/?(\?.*)?$}, ".json")- headers = reddit_auth_header- if headers.any?- json_url = json_url.sub(%r{://(www|old|np|new)\.reddit\.com}, "://oauth.reddit.com")+ if comment_path?+ params[:showmedia] = false+ params[:showmore] = false+ params[:depth] = 1+ params[:context] = 1end- response = Onebox::Helpers.fetch_response(json_url, headers:)- parsed = ::MultiJson.load(response)- @reddit_post = parsed[0]["data"]["children"][0]["data"]- rescue StandardError- @reddit_post = nil- end- def image_post?(post)- post["post_hint"] == "image" ||- post["url"].to_s.match?(/\.(jpg|jpeg|png|gif|webp)(\?.*)?$/i)+ paramsend- def video_post?(post)- post["is_video"] || post["post_hint"].to_s.include?("video")+ def comment_path?+ uri.path.match?(%r{^/(?:r|user)/[^/]+/comments/[^/]+/[^/]*/[^/]+/?$})end- def extract_image_url(post)- if post["url"].to_s.match?(/\.(jpg|jpeg|png|gif|webp)(\?.*)?$/i)- return CGI.unescapeHTML(post["url"])- end-- preview_url = post.dig("preview", "images", 0, "source", "url")- CGI.unescapeHTML(preview_url) if preview_url+ def default_height+ comment_path? ? 300 : 500endendenddiff --git a/lib/onebox/mixins/reddit_auth_header.rb b/lib/onebox/mixins/reddit_auth_header.rbdeleted file mode 100644index 0814f178620..00000000000--- a/lib/onebox/mixins/reddit_auth_header.rb+++ /dev/null@@ -1,49 +0,0 @@-# frozen_string_literal: true--module Onebox- module Mixins- module RedditAuthHeader- def reddit_auth_header- if SiteSetting.reddit_onebox_client_id.blank? ||- SiteSetting.reddit_onebox_client_secret.blank?- return {}- end-- token = fetch_reddit_access_token- return {} if token.blank?-- { "Authorization" => "Bearer #{token}" }- end-- def reddit_authenticated?- SiteSetting.reddit_onebox_client_id.present? &&- SiteSetting.reddit_onebox_client_secret.present?- end-- private-- def fetch_reddit_access_token- Discourse- .cache- .fetch("reddit_onebox_access_token", expires_in: 50.minutes) do- user = SiteSetting.reddit_onebox_client_id- password = SiteSetting.reddit_onebox_client_secret-- response =- Excon.post(- "https://www.reddit.com/api/v1/access_token",- body: URI.encode_www_form(grant_type: "client_credentials"),- headers: {- "Content-Type" => "application/x-www-form-urlencoded",- "User-Agent" => Onebox::Helpers.user_agent,- },- user:,- password:,- )-- ::MultiJson.load(response.body)["access_token"] if response.status == 200- end- end- end- end-enddiff --git a/spec/lib/onebox/engine/reddit_media_onebox_spec.rb b/spec/lib/onebox/engine/reddit_media_onebox_spec.rbindex dbecef7d566..72cba12f718 100644--- a/spec/lib/onebox/engine/reddit_media_onebox_spec.rb+++ b/spec/lib/onebox/engine/reddit_media_onebox_spec.rb@@ -1,151 +1,66 @@# frozen_string_literal: trueRSpec.describe Onebox::Engine::RedditMediaOnebox do- let(:image_link) do+ let(:post_link) do"https://www.reddit.com/r/colors/comments/b4d5xm/literally_nothing_black_edition"end- let(:self_post_link) do- "https://www.reddit.com/r/LocalLLaMA/comments/xyz789/what_are_some_underrated_local_llms"+ let(:comment_link) do+ "https://www.reddit.com/r/cats/comments/abc123/my_cat_doing_a_backflip/def456"end- let(:video_link) { "https://www.reddit.com/r/cats/comments/abc123/my_cat_doing_a_backflip" }- describe "image post" do- let(:html) { described_class.new(image_link).to_html }-- before do- stub_request(:get, "#{image_link}.json").to_return(- status: 200,- body: onebox_response("reddit_image"),- )- end-- it "includes image" do- expect(html).to include("https://i.redd.it/vsg59iw0srn21.jpg")- end-- it "includes title" do- expect(html).to include("Literally nothing black edition")- end-- it "includes subreddit" do- expect(html).to include("r/colors")- end-- it "includes score and comments" do- expect(html).to include("4 points")- expect(html).to include("1 comments")+ describe "#placeholder_html" do+ it "returns a generic placeholder" do+ expect(described_class.new(post_link).placeholder_html).to include("placeholder-icon generic")endend- describe "self/text post" do- let(:html) { described_class.new(self_post_link).to_html }+ describe "#to_html" do+ it "renders a native Reddit embed iframe" do+ html = described_class.new(post_link).to_html- before do- stub_request(:get, "#{self_post_link}.json").to_return(- status: 200,- body: onebox_response("reddit_self_post"),+ expect(html).to include("<iframe")+ expect(html).to include('class="reddit-onebox"')+ expect(html).to include(+ "https://embed.reddit.com/r/colors/comments/b4d5xm/literally_nothing_black_edition/",)+ expect(html).to include("embed=true")+ expect(html).to include('height="500"')+ expect(html).not_to include("scrolling=")+ expect(html).not_to include("frameborder=")end- it "includes title" do- expect(html).to include("What are some underrated local LLMs?")- end-- it "includes selftext" do- expect(html).to include("experimenting with various local models")- end-- it "includes author" do- expect(html).to include("u/llm_enthusiast")- end+ it "does not fetch Reddit content server-side" do+ described_class.new(post_link).to_html- it "does not include image markup" do- expect(html).not_to include("scale-image")+ expect(WebMock).not_to have_requested(:any, %r{reddit\.com/.*(?:\.json|access_token)})endend- describe "video post" do- let(:html) { described_class.new(video_link).to_html }+ describe "comment permalinks" do+ it "adds the native comment embed params" do+ html = described_class.new(comment_link).to_html- before do- stub_request(:get, "#{video_link}.json").to_return(- status: 200,- body: onebox_response("reddit_video"),+ expect(html).to include(+ "https://embed.reddit.com/r/cats/comments/abc123/my_cat_doing_a_backflip/def456/",)- end-- it "includes title" do- expect(html).to include("My cat doing a backflip")- end-- it "includes preview thumbnail" do- expect(html).to include("thumbnail")- end-- it "includes preview image" do- expect(html).to include("https://preview.redd.it/abc123def456.png")+ expect(html).to include("showmedia=false")+ expect(html).to include("showmore=false")+ expect(html).to include("depth=1")+ expect(html).to include("context=1")+ expect(html).to include('height="300"')endend- describe "authenticated requests" do- let(:image_link) do- "https://www.reddit.com/r/colors/comments/b4d5xm/literally_nothing_black_edition"- end- let(:oauth_json_url) do- "https://oauth.reddit.com/r/colors/comments/b4d5xm/literally_nothing_black_edition.json"- end- let(:token_url) { "https://www.reddit.com/api/v1/access_token" }-- context "when Reddit OAuth credentials are configured" do- before do- SiteSetting.reddit_onebox_client_id = "test_client_id"- SiteSetting.reddit_onebox_client_secret = "test_client_secret"-- stub_request(:post, token_url).to_return(- status: 200,- body: { access_token: "test_token", token_type: "bearer", expires_in: 3600 }.to_json,- )-- stub_request(:get, oauth_json_url).with(- headers: {- "Authorization" => "Bearer test_token",- },- ).to_return(status: 200, body: onebox_response("reddit_image"))- end-- it "uses oauth.reddit.com with auth header" do- described_class.new(image_link).to_html- expect(WebMock).to have_requested(:get, oauth_json_url).with(- headers: {- "Authorization" => "Bearer test_token",- },- )- end- end-- context "when Reddit OAuth credentials are blank" do- before do- SiteSetting.reddit_onebox_client_id = ""- SiteSetting.reddit_onebox_client_secret = ""-- stub_request(:get, "#{image_link}.json").to_return(- status: 200,- body: onebox_response("reddit_image"),- )- end-- it "uses www.reddit.com without auth header" do- described_class.new(image_link).to_html- expect(WebMock).to have_requested(:get, "#{image_link}.json").with { |req|- req.headers.exclude?("Authorization")- }- end+ describe ".===" do+ it "allows both Reddit embed iframe origins" do+ expect(described_class.iframe_origins).to contain_exactly(+ "https://embed.reddit.com",+ "https://sh.reddit.com",+ )end- end- describe ".===" doit "matches valid Reddit URL" do- valid_url = URI(image_link)+ valid_url = URI(post_link)expect(described_class === valid_url).to eq(true)end@@ -167,6 +82,12 @@ RSpec.describe Onebox::Engine::RedditMediaOnebox do)end+ it "matches Reddit user comment URLs" do+ expect(+ described_class === URI("https://www.reddit.com/user/spez/comments/abc123/post/def456/"),+ ).to eq(true)+ end+it "does not match invalid Reddit URL" doinvalid_url = URI("https://www.reddit.com.somedomain.com/r/colors/comments/b4d5xm/")expect(described_class === invalid_url).to eq(false)