A platform for community discussion. Free, open, simple.
FEATURE: Add support for uploads on translated posts (#35871)
Keegan George8b789c930610
diff --git a/app/models/concerns/has_post_upload_references.rb b/app/models/concerns/has_post_upload_references.rbnew file mode 100644index 00000000000..86fa4d93aaa--- /dev/null+++ b/app/models/concerns/has_post_upload_references.rb@@ -0,0 +1,150 @@+# frozen_string_literal: true++module HasPostUploadReferences+ extend ActiveSupport::Concern++ def link_post_uploads(fragments: nil)+ upload_ids = []++ each_upload_url(fragments: fragments) do |src, _, sha1|+ upload = nil+ upload = Upload.find_by(sha1: sha1) if sha1.present?+ upload ||= Upload.get_from_url(src)++ # Link any video thumbnails+ if SiteSetting.video_thumbnails_enabled && upload.present? &&+ FileHelper.supported_video.include?(upload.extension&.downcase)+ # Video thumbnails have the filename of the video file sha1 with a .png or .jpg extension.+ # This is because at time of upload in the composer we don't know the topic/post id yet+ # and there is no thumbnail info added to the markdown to tie the thumbnail to the topic/post after+ # creation.+ thumbnail =+ Upload+ .where("original_filename like ?", "#{upload.sha1}.%")+ .order(id: :desc)+ .first if upload.sha1.present?+ if thumbnail.present?+ upload_ids << thumbnail.id+ handle_video_thumbnail(thumbnail) if respond_to?(:handle_video_thumbnail, true)+ end+ end+ upload_ids << upload.id if upload.present?+ end++ upload_references =+ upload_ids.map do |upload_id|+ {+ target_id: self.id,+ target_type: self.class.name,+ upload_id: upload_id,+ created_at: Time.zone.now,+ updated_at: Time.zone.now,+ }+ end++ UploadReference.transaction do+ UploadReference.where(target: self).delete_all+ UploadReference.insert_all(upload_references) if upload_references.size > 0++ if SiteSetting.secure_uploads?+ Upload+ .where(id: upload_ids, access_control_post_id: nil)+ .where("id NOT IN (SELECT upload_id FROM custom_emojis)")+ .update_all(access_control_post_id: access_control_post_id_for_upload)+ end+ end+ end++ def each_upload_url(fragments: nil, include_local_upload: true)+ current_db = RailsMultisite::ConnectionManagement.current_db++ upload_patterns = [+ %r{/uploads/#{current_db}/},+ %r{/original/},+ %r{/optimized/},+ %r{/uploads/short-url/[a-zA-Z0-9]+(\.[a-z0-9]+)?},+ ]++ fragments ||= Nokogiri::HTML5.fragment(self.cooked)++ selectors =+ fragments.css(+ "a/@href",+ "img/@src",+ "source/@src",+ "track/@src",+ "video/@poster",+ "div/@data-video-src",+ "div/@data-original-video-src",+ )++ links =+ selectors+ .map do |media|+ src = media.value+ next if src.blank?++ if src.end_with?("/images/transparent.png") &&+ (parent = media.parent)["data-orig-src"].present?+ parent["data-orig-src"]+ else+ src+ end+ end+ .compact+ .uniq++ links.each do |src|+ src = src.split("?")[0]++ if src.start_with?("upload://")+ sha1 = Upload.sha1_from_short_url(src)+ yield(src, nil, sha1)+ next+ end++ if src.include?("/uploads/short-url/")+ host =+ begin+ URI(src).host+ rescue URI::Error+ end++ next if host.present? && host != Discourse.current_hostname++ sha1 = Upload.sha1_from_short_path(src)+ yield(src, nil, sha1)+ next+ end++ next if upload_patterns.none? { |pattern| src =~ pattern }+ next if Rails.configuration.multisite && src.exclude?(current_db)++ src = "#{SiteSetting.force_https ? "https" : "http"}:#{src}" if src.start_with?("//")++ if !Discourse.store.has_been_uploaded?(src) && !Upload.secure_uploads_url?(src) &&+ !(include_local_upload && src =~ %r{\A/[^/]}i)+ next+ end++ path =+ begin+ URI(+ UrlHelper.unencode(GlobalSetting.cdn_url ? src.sub(GlobalSetting.cdn_url, "") : src),+ )&.path+ rescue URI::Error+ end++ next if path.blank?++ sha1 =+ if path.include? "optimized"+ OptimizedImage.extract_sha1(path)+ else+ Upload.extract_sha1(path) || Upload.sha1_from_short_path(path)+ end++ yield(src, path, sha1)+ end+ end+enddiff --git a/app/models/post.rb b/app/models/post.rbindex 8cbed1e6eec..65561253477 100644--- a/app/models/post.rb+++ b/app/models/post.rb@@ -10,6 +10,7 @@ class Post < ActiveRecord::Baseinclude HasCustomFieldsinclude LimitedEditinclude Localizable+ include HasPostUploadReferencesself.ignored_columns = ["avg_time", # TODO: Remove when 20240212034010_drop_deprecated_columns has been promoted to pre-deploy@@ -1085,164 +1086,12 @@ class Post < ActiveRecord::Baselocked_by_id.present?end- def link_post_uploads(fragments: nil)- upload_ids = []-- each_upload_url(fragments: fragments) do |src, _, sha1|- upload = nil- upload = Upload.find_by(sha1: sha1) if sha1.present?- upload ||= Upload.get_from_url(src)-- # Link any video thumbnails- if SiteSetting.video_thumbnails_enabled && upload.present? &&- FileHelper.supported_video.include?(upload.extension&.downcase)- # Video thumbnails have the filename of the video file sha1 with a .png or .jpg extension.- # This is because at time of upload in the composer we don't know the topic/post id yet- # and there is no thumbnail info added to the markdown to tie the thumbnail to the topic/post after- # creation.- thumbnail =- Upload- .where("original_filename like ?", "#{upload.sha1}.%")- .order(id: :desc)- .first if upload.sha1.present?- if thumbnail.present?- upload_ids << thumbnail.id- if self.is_first_post? && !self.topic.image_upload_id- self.topic.update_column(:image_upload_id, thumbnail.id)- extra_sizes =- ThemeModifierHelper.new(- theme_ids: Theme.user_selectable.pluck(:id),- ).topic_thumbnail_sizes- self.topic.generate_thumbnails!(extra_sizes: extra_sizes)- end- end- end- upload_ids << upload.id if upload.present?- end-- upload_references =- upload_ids.map do |upload_id|- {- target_id: self.id,- target_type: self.class.name,- upload_id: upload_id,- created_at: Time.zone.now,- updated_at: Time.zone.now,- }- end-- UploadReference.transaction do- UploadReference.where(target: self).delete_all- UploadReference.insert_all(upload_references) if upload_references.size > 0-- if SiteSetting.secure_uploads?- Upload- .where(id: upload_ids, access_control_post_id: nil)- .where("id NOT IN (SELECT upload_id FROM custom_emojis)")- .update_all(access_control_post_id: self.id)- end- end- end-def update_uploads_secure_status(source:)if Discourse.store.external?self.uploads.each { |upload| upload.update_secure_status(source: source) }endend- def each_upload_url(fragments: nil, include_local_upload: true)- current_db = RailsMultisite::ConnectionManagement.current_db-- upload_patterns = [- %r{/uploads/#{current_db}/},- %r{/original/},- %r{/optimized/},- %r{/uploads/short-url/[a-zA-Z0-9]+(\.[a-z0-9]+)?},- ]-- fragments ||= Nokogiri::HTML5.fragment(self.cooked)-- selectors =- fragments.css(- "a/@href",- "img/@src",- "source/@src",- "track/@src",- "video/@poster",- "div/@data-video-src",- "div/@data-original-video-src",- )-- links =- selectors- .map do |media|- src = media.value- next if src.blank?-- if src.end_with?("/images/transparent.png") &&- (parent = media.parent)["data-orig-src"].present?- parent["data-orig-src"]- else- src- end- end- .compact- .uniq-- links.each do |src|- src = src.split("?")[0]-- if src.start_with?("upload://")- sha1 = Upload.sha1_from_short_url(src)- yield(src, nil, sha1)- next- end-- if src.include?("/uploads/short-url/")- host =- begin- URI(src).host- rescue URI::Error- end-- next if host.present? && host != Discourse.current_hostname-- sha1 = Upload.sha1_from_short_path(src)- yield(src, nil, sha1)- next- end-- next if upload_patterns.none? { |pattern| src =~ pattern }- next if Rails.configuration.multisite && src.exclude?(current_db)-- src = "#{SiteSetting.force_https ? "https" : "http"}:#{src}" if src.start_with?("//")-- if !Discourse.store.has_been_uploaded?(src) && !Upload.secure_uploads_url?(src) &&- !(include_local_upload && src =~ %r{\A/[^/]}i)- next- end-- path =- begin- URI(- UrlHelper.unencode(GlobalSetting.cdn_url ? src.sub(GlobalSetting.cdn_url, "") : src),- )&.path- rescue URI::Error- end-- next if path.blank?-- sha1 =- if path.include? "optimized"- OptimizedImage.extract_sha1(path)- else- Upload.extract_sha1(path) || Upload.sha1_from_short_path(path)- end-- yield(src, path, sha1)- end- end-def self.find_missing_uploads(include_local_upload: true)missing_uploads = []missing_post_uploads = {}@@ -1340,6 +1189,19 @@ class Post < ActiveRecord::Baseprivate+ def access_control_post_id_for_upload+ self.id+ end++ def handle_video_thumbnail(thumbnail)+ if self.is_first_post? && !self.topic.image_upload_id+ self.topic.update_column(:image_upload_id, thumbnail.id)+ extra_sizes =+ ThemeModifierHelper.new(theme_ids: Theme.user_selectable.pluck(:id)).topic_thumbnail_sizes+ self.topic.generate_thumbnails!(extra_sizes: extra_sizes)+ end+ end+def parse_quote_into_arguments(quote)return {} if quote.blank?args = ActiveSupport::HashWithIndifferentAccess.newdiff --git a/app/models/post_localization.rb b/app/models/post_localization.rbindex 0ec077b7be3..a48c9dab628 100644--- a/app/models/post_localization.rb+++ b/app/models/post_localization.rb@@ -2,8 +2,11 @@class PostLocalization < ActiveRecord::Baseinclude LocaleMatchable+ include HasPostUploadReferencesbelongs_to :post+ has_many :upload_references, as: :target, dependent: :destroy+ has_many :uploads, through: :upload_referencesvalidates :post_version, presence: truevalidates :locale, presence: true, length: { maximum: 20 }@@ -11,6 +14,12 @@ class PostLocalization < ActiveRecord::Basevalidates :cooked, presence: truevalidates :localizer_user_id, presence: truevalidates :locale, uniqueness: { scope: :post_id }++ private++ def access_control_post_id_for_upload+ self.post_id+ endend# == Schema Informationdiff --git a/frontend/discourse/app/components/composer-editor.gjs b/frontend/discourse/app/components/composer-editor.gjsindex ff553a7cdc7..21301d8a1aa 100644--- a/frontend/discourse/app/components/composer-editor.gjs+++ b/frontend/discourse/app/components/composer-editor.gjs@@ -1082,8 +1082,9 @@ export default class ComposerEditor extends Component {{{else if this.showTranslationEditor}}<PostTranslationEditor@setupEditor={{this.setupEditor}}- {{didInsert this._composerEditorInitEditor}}- {{willDestroy this._composerEditorDestroyEditor}}+ @extraButtons={{this.extraButtons}}+ @showLink={{this.showLink}}+ @uppyComposerUpload={{this.uppyComposerUpload}}{{didInsert this._composerEditorInitPreview}}{{willDestroy this._composerEditorDestroyPreview}}/>diff --git a/frontend/discourse/app/components/post-translation-editor.gjs b/frontend/discourse/app/components/post-translation-editor.gjsindex 4e14e77d4e3..2dee7cdde25 100644--- a/frontend/discourse/app/components/post-translation-editor.gjs+++ b/frontend/discourse/app/components/post-translation-editor.gjs@@ -1,6 +1,8 @@import Component from "@glimmer/component";import { hash } from "@ember/helper";import { action } from "@ember/object";+import didInsert from "@ember/render-modifiers/modifiers/did-insert";+import willDestroy from "@ember/render-modifiers/modifiers/will-destroy";import { service } from "@ember/service";import DEditor from "discourse/components/d-editor";import TextField from "discourse/components/text-field";@@ -103,6 +105,22 @@ export default class PostTranslationEditor extends Component {}}+ @action+ setupUploads(element) {+ if (this.args.uppyComposerUpload && this.composer.allowUpload) {+ this.args.uppyComposerUpload.setup(element);+ this._uploadsSetup = true;+ }+ }++ @action+ teardownUploads(element) {+ if (this._uploadsSetup && this.args.uppyComposerUpload) {+ this.args.uppyComposerUpload.teardown(element);+ this._uploadsSetup = false;+ }+ }+<template><div><DropdownSelectBox@@ -144,8 +162,13 @@ export default class PostTranslationEditor extends Component {@value={{readonly this.composer.model.reply}}@change={{this.handleInput}}@placeholder="composer.translations.placeholder"+ @extraButtons={{@extraButtons}}@forcePreview={{true}}@processPreview={{false}}+ @composerEvents={{true}}+ @onPopupMenuAction={{this.composer.onPopupMenuAction}}+ @popupMenuOptions={{this.composer.popupMenuOptions}}+ @showLink={{@showLink}}@loading={{this.composer.loading}}@hijackPreview={{this.composer.hijackPreview}}@disabled={{this.composer.disableTextarea}}@@ -157,6 +180,8 @@ export default class PostTranslationEditor extends Component {composer=this.composer.modeleditorType="composer"}}+ {{didInsert this.setupUploads}}+ {{willDestroy this.teardownUploads}}/></template>}diff --git a/frontend/discourse/app/services/composer.js b/frontend/discourse/app/services/composer.jsindex 933ff1cb543..24de4495652 100644--- a/frontend/discourse/app/services/composer.js+++ b/frontend/discourse/app/services/composer.js@@ -1310,6 +1310,7 @@ export default class ComposerService extends Service {);}+ this.set("model.loading", false);this.close();this.toasts.success({duration: "short",@@ -1320,8 +1321,6 @@ export default class ComposerService extends Service {this.selectedTranslationLocale = null;} catch (e) {popupAjaxError(e);- } finally {- this.set("model.loading", false);}}diff --git a/lib/localized_cooked_post_processor.rb b/lib/localized_cooked_post_processor.rbindex b1ff77d6c49..a478e41756b 100644--- a/lib/localized_cooked_post_processor.rb+++ b/lib/localized_cooked_post_processor.rb@@ -20,6 +20,7 @@ class LocalizedCookedPostProcessordef post_processpost_process_oneboxespost_process_images+ @post_localization.link_post_uploads(fragments: @doc)enddef htmldiff --git a/spec/lib/localized_cooked_post_processor_spec.rb b/spec/lib/localized_cooked_post_processor_spec.rbnew file mode 100644index 00000000000..f5be9e4278b--- /dev/null+++ b/spec/lib/localized_cooked_post_processor_spec.rb@@ -0,0 +1,96 @@+# frozen_string_literal: true++RSpec.describe LocalizedCookedPostProcessor do+ fab!(:post)+ fab!(:upload1, :upload)+ fab!(:upload2, :upload)++ let(:image_url) { upload1.short_url }+ let(:image_url_2) { upload2.short_url }++ let(:raw_with_uploads) { <<~RAW }+ これは翻訳されたコンテンツです。+ + + RAW++ let(:cooked_with_uploads) { PrettyText.cook(raw_with_uploads) }++ let(:localization) do+ Fabricate(:post_localization, post: post, raw: raw_with_uploads, cooked: cooked_with_uploads)+ end++ let(:processor) { LocalizedCookedPostProcessor.new(localization, post) }++ describe "#post_process" do+ it "calls link_post_uploads on the localization" do+ localization.expects(:link_post_uploads).with(+ fragments: processor.instance_variable_get(:@doc),+ )+ processor.post_process+ end++ it "creates upload references for uploads in the localization" do+ processor.post_process++ upload_ids = UploadReference.where(target: localization).pluck(:upload_id)+ expect(upload_ids).to contain_exactly(upload1.id, upload2.id)+ end++ it "uses PostLocalization as the target type for upload references" do+ processor.post_process++ upload_ref = UploadReference.find_by(target: localization, upload_id: upload1.id)+ expect(upload_ref.target_type).to eq("PostLocalization")+ expect(upload_ref.target_id).to eq(localization.id)+ end++ context "when the localization already has upload references" do+ before do+ UploadReference.create!(+ target: localization,+ upload: upload1,+ created_at: Time.zone.now,+ updated_at: Time.zone.now,+ )+ end++ it "replaces the old upload references" do+ old_ref_id = localization.upload_references.first.id++ processor.post_process++ expect(UploadReference.exists?(old_ref_id)).to eq(false)+ expect(localization.reload.upload_references.pluck(:upload_id)).to contain_exactly(+ upload1.id,+ upload2.id,+ )+ end+ end++ context "when secure uploads is enabled" do+ before do+ setup_s3+ SiteSetting.authorized_extensions = "pdf|png|jpg|csv"+ SiteSetting.secure_uploads = true+ end++ it "sets access_control_post_id to the parent post" do+ processor.post_process++ upload1.reload+ expect(upload1.access_control_post_id).to eq(post.id)+ end++ it "does not override existing access_control_post_id" do+ other_post = Fabricate(:post)+ upload1.update!(access_control_post_id: other_post.id)++ processor.post_process++ upload1.reload+ expect(upload1.access_control_post_id).to eq(other_post.id)+ end+ end+ end+enddiff --git a/spec/models/concerns/has_post_upload_references_spec.rb b/spec/models/concerns/has_post_upload_references_spec.rbnew file mode 100644index 00000000000..a749c0f48e6--- /dev/null+++ b/spec/models/concerns/has_post_upload_references_spec.rb@@ -0,0 +1,259 @@+# frozen_string_literal: true++RSpec.describe HasPostUploadReferences do+ fab!(:upload1, :upload)+ fab!(:upload2, :upload)+ fab!(:video_upload) { Fabricate(:upload, extension: "mp4") }++ shared_examples "has upload references" do+ let(:base_url) { "#{Discourse.base_url_no_prefix}#{Discourse.base_path}" }+ let(:image_url) { "#{base_url}#{upload1.url}" }+ let(:image_url_2) { "#{base_url}#{upload2.url}" }+ let(:video_url) { "#{base_url}#{video_upload.url}" }++ let(:raw_with_uploads) { <<~RAW }+ + + <video width="100%" height="100%" controls>+ <source src="#{video_url}">+ <a href="#{video_url}">#{video_url}</a>+ </video>+ RAW++ let(:cooked_with_uploads) { PrettyText.cook(raw_with_uploads) }++ describe "#link_post_uploads" do+ it "finds all the uploads in the content" do+ subject.link_post_uploads++ expect(UploadReference.where(target: subject).pluck(:upload_id)).to contain_exactly(+ upload1.id,+ upload2.id,+ video_upload.id,+ )+ end++ it "uses the correct target_type for upload references" do+ subject.link_post_uploads++ upload_ref = UploadReference.find_by(target: subject, upload_id: upload1.id)+ expect(upload_ref.target_type).to eq(subject.class.name)+ expect(upload_ref.target_id).to eq(subject.id)+ end++ it "cleans up the reverse index for the current target" do+ subject.link_post_uploads+ original_ids = subject.upload_references.pluck(:id)++ subject.link_post_uploads++ expect(subject.reload.upload_references.pluck(:id)).to_not eq(original_ids)+ expect(UploadReference.where(id: original_ids).exists?).to eq(false)+ end++ it "works with fragments" do+ fragments = Nokogiri::HTML5.fragment(cooked_with_uploads)+ subject.link_post_uploads(fragments: fragments)++ expect(UploadReference.where(target: subject).pluck(:upload_id)).to contain_exactly(+ upload1.id,+ upload2.id,+ video_upload.id,+ )+ end++ context "when video thumbnails are enabled" do+ fab!(:thumbnail_upload, :image_upload)++ before do+ SiteSetting.video_thumbnails_enabled = true+ thumbnail_upload.update!(original_filename: "#{video_upload.sha1}.png")+ end++ it "links video thumbnails" do+ subject.link_post_uploads++ expect(UploadReference.where(target: subject).pluck(:upload_id)).to include(+ thumbnail_upload.id,+ )+ end+ end++ context "when secure uploads is enabled" do+ before do+ setup_s3+ SiteSetting.authorized_extensions = "pdf|png|jpg|csv|mp4"+ SiteSetting.secure_uploads = true+ end++ it "sets the access_control_post_id on uploads that don't already have the value set" do+ other_target = create_target_with_different_access_control_id+ upload2.update(access_control_post_id: other_target.id)++ FileStore::S3Store.any_instance.stubs(:has_been_uploaded?).returns(true)++ subject.link_post_uploads++ upload1.reload+ upload2.reload+ expect(upload1.access_control_post_id).to eq(expected_access_control_post_id)+ expect(upload2.access_control_post_id).not_to eq(expected_access_control_post_id)+ expect(upload2.access_control_post_id).to eq(other_target.id)+ end++ context "for custom emoji" do+ before { CustomEmoji.create(name: "meme", upload: upload1) }++ it "never sets an access control post because they should not be secure" do+ subject.link_post_uploads+ expect(upload1.reload.access_control_post_id).to eq(nil)+ end+ end+ end+ end++ describe "#each_upload_url" do+ let(:raw_with_upload) { "" }+ let(:cooked_with_upload) { PrettyText.cook(raw_with_upload) }++ before { subject.update!(raw: raw_with_upload, cooked: cooked_with_upload) }++ it "yields upload URLs from the cooked HTML" do+ urls = []+ subject.each_upload_url { |url, _src, _sha1| urls << url }++ expect(urls.length).to eq(1)+ expect(urls.first).to include(upload1.sha1)+ end++ it "yields the sha1 when available" do+ sha1s = []+ subject.each_upload_url { |_url, _src, sha1| sha1s << sha1 }++ expect(sha1s).to include(upload1.sha1)+ end++ it "works with fragments" do+ fragments = Nokogiri::HTML5.fragment(cooked_with_upload)+ urls = []+ subject.each_upload_url(fragments: fragments) { |url, _src, _sha1| urls << url }++ expect(urls.length).to eq(1)+ expect(urls.first).to include(upload1.sha1)+ end++ it "handles short URLs" do+ short_url_raw = ""+ short_url_cooked = PrettyText.cook(short_url_raw)+ subject.update!(raw: short_url_raw, cooked: short_url_cooked)++ sha1s = []+ subject.each_upload_url { |_url, _src, sha1| sha1s << sha1 }++ expect(sha1s).to include(upload1.sha1)+ end++ it "handles upload:// protocol URLs" do+ upload_protocol_raw = ""+ upload_protocol_cooked = PrettyText.cook(upload_protocol_raw)+ subject.update!(raw: upload_protocol_raw, cooked: upload_protocol_cooked)++ sha1s = []+ subject.each_upload_url { |_url, _src, sha1| sha1s << sha1 }++ expect(sha1s).to include(upload1.sha1)+ end+ end+ end++ context "with Post" do+ fab!(:user, :admin)++ let(:post) do+ Fabricate(+ :post,+ raw: raw_with_uploads,+ cooked: cooked_with_uploads,+ user: user,+ skip_validation: true,+ )+ end+ let(:subject) { post }+ let(:expected_access_control_post_id) { post.id }++ def create_target_with_different_access_control_id+ Fabricate(:post)+ end++ include_examples "has upload references"++ context "when handling video thumbnails" do+ fab!(:thumbnail_upload, :image_upload)++ before do+ SiteSetting.video_thumbnails_enabled = true+ thumbnail_upload.update!(original_filename: "#{video_upload.sha1}.png")+ end++ it "sets topic image_upload_id for first posts" do+ first_post =+ Fabricate(+ :post,+ raw: raw_with_uploads,+ cooked: cooked_with_uploads,+ skip_validation: true,+ )+ first_post.link_post_uploads++ expect(first_post.topic.reload.image_upload_id).to eq(thumbnail_upload.id)+ end++ it "does not set topic image_upload_id for non-first posts" do+ topic = Fabricate(:topic)+ Fabricate(:post, topic: topic, skip_validation: true)+ second_post =+ Fabricate(+ :post,+ topic: topic,+ raw: raw_with_uploads,+ cooked: cooked_with_uploads,+ skip_validation: true,+ )++ second_post.link_post_uploads++ expect(topic.reload.image_upload_id).to be_nil+ end+ end+ end++ context "with PostLocalization" do+ fab!(:post)++ let(:localization) do+ Fabricate(:post_localization, post: post, raw: raw_with_uploads, cooked: cooked_with_uploads)+ end++ let(:subject) { localization }+ let(:expected_access_control_post_id) { post.id }++ def create_target_with_different_access_control_id+ Fabricate(:post)+ end++ include_examples "has upload references"++ it "uses the parent post's ID for access control" do+ setup_s3+ SiteSetting.authorized_extensions = "pdf|png|jpg|csv|mp4"+ SiteSetting.secure_uploads = true++ FileStore::S3Store.any_instance.stubs(:has_been_uploaded?).returns(true)++ localization.link_post_uploads++ upload1.reload+ expect(upload1.access_control_post_id).to eq(post.id)+ end+ end+enddiff --git a/spec/models/post_localization_spec.rb b/spec/models/post_localization_spec.rbnew file mode 100644index 00000000000..3968bd02b69--- /dev/null+++ b/spec/models/post_localization_spec.rb@@ -0,0 +1,161 @@+# frozen_string_literal: true++RSpec.describe PostLocalization do+ fab!(:post)+ fab!(:upload1, :upload)+ fab!(:upload2, :upload)+ fab!(:video_upload) { Fabricate(:upload, extension: "mp4") }++ describe "associations" do+ it { is_expected.to have_many(:upload_references).dependent(:destroy) }+ it { is_expected.to have_many(:uploads).through(:upload_references) }+ it { is_expected.to belong_to(:post) }+ end++ describe "#link_post_uploads" do+ let(:base_url) { "#{Discourse.base_url_no_prefix}#{Discourse.base_path}" }+ let(:image_url) { "#{base_url}#{upload1.url}" }+ let(:image_url_2) { "#{base_url}#{upload2.url}" }+ let(:video_url) { "#{base_url}#{video_upload.url}" }++ let(:raw_with_uploads) { <<~RAW }+ + + <video width="100%" height="100%" controls>+ <source src="#{video_url}">+ <a href="#{video_url}">#{video_url}</a>+ </video>+ RAW++ let(:cooked_with_uploads) { PrettyText.cook(raw_with_uploads) }++ let(:localization) do+ Fabricate(:post_localization, post: post, raw: raw_with_uploads, cooked: cooked_with_uploads)+ end++ it "finds all the uploads in the localization" do+ localization.link_post_uploads++ expect(UploadReference.where(target: localization).pluck(:upload_id)).to contain_exactly(+ upload1.id,+ upload2.id,+ video_upload.id,+ )+ end++ it "uses the correct target_type for upload references" do+ localization.link_post_uploads++ upload_ref = UploadReference.find_by(target: localization, upload_id: upload1.id)+ expect(upload_ref.target_type).to eq("PostLocalization")+ expect(upload_ref.target_id).to eq(localization.id)+ end++ it "cleans the reverse index up for the current localization" do+ localization.link_post_uploads++ localization_uploads_ids = localization.upload_references.pluck(:id)++ localization.link_post_uploads++ expect(localization.reload.upload_references.pluck(:id)).to_not contain_exactly(+ localization_uploads_ids,+ )+ end++ it "works with fragments" do+ fragments = Nokogiri::HTML5.fragment(cooked_with_uploads)+ localization.link_post_uploads(fragments: fragments)++ expect(UploadReference.where(target: localization).pluck(:upload_id)).to contain_exactly(+ upload1.id,+ upload2.id,+ video_upload.id,+ )+ end++ context "when video thumbnails are enabled" do+ fab!(:thumbnail_upload, :image_upload)++ before do+ SiteSetting.video_thumbnails_enabled = true+ thumbnail_upload.update!(original_filename: "#{video_upload.sha1}.png")+ end++ it "links video thumbnails" do+ localization.link_post_uploads++ expect(UploadReference.where(target: localization).pluck(:upload_id)).to include(+ thumbnail_upload.id,+ )+ end+ end++ context "when secure uploads is enabled" do+ before do+ setup_s3+ SiteSetting.authorized_extensions = "pdf|png|jpg|csv|mp4"+ SiteSetting.secure_uploads = true+ end++ it "sets the access_control_post_id to the parent post on uploads that don't already have the value set" do+ other_post = Fabricate(:post)+ upload2.update(access_control_post_id: other_post.id)++ FileStore::S3Store.any_instance.stubs(:has_been_uploaded?).returns(true)++ localization.link_post_uploads++ upload1.reload+ upload2.reload+ expect(upload1.access_control_post_id).to eq(post.id)+ expect(upload2.access_control_post_id).not_to eq(post.id)+ expect(upload2.access_control_post_id).to eq(other_post.id)+ end++ context "for custom emoji" do+ before { CustomEmoji.create(name: "meme", upload: upload1) }++ it "never sets an access control post because they should not be secure" do+ localization.link_post_uploads+ expect(upload1.reload.access_control_post_id).to eq(nil)+ end+ end+ end+ end++ describe "#each_upload_url" do+ let(:base_url) { "#{Discourse.base_url_no_prefix}#{Discourse.base_path}" }+ let(:image_url) { "#{base_url}#{upload1.url}" }+ let(:raw_with_upload) { "" }+ let(:cooked_with_upload) { PrettyText.cook(raw_with_upload) }++ let(:localization) do+ Fabricate(:post_localization, post: post, raw: raw_with_upload, cooked: cooked_with_upload)+ end++ it "yields upload URLs from the cooked HTML" do+ urls = []+ localization.each_upload_url { |url, _src, _sha1| urls << url }++ expect(urls.length).to eq(1)+ expect(urls.first).to include(upload1.sha1)+ end++ it "yields the sha1 when available" do+ sha1s = []+ localization.each_upload_url { |_url, _src, sha1| sha1s << sha1 }++ expect(sha1s).to include(upload1.sha1)+ end++ it "works with fragments" do+ fragments = Nokogiri::HTML5.fragment(cooked_with_upload)+ urls = []+ localization.each_upload_url(fragments: fragments) { |url, _src, _sha1| urls << url }++ expect(urls.length).to eq(1)+ expect(urls.first).to include(upload1.sha1)+ end+ end+end