Skip to content

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

FIX: Publish reaction changes from all entry points (#43021)

Rafael dos Santos Silvab1bcb557b536
diff --git a/plugins/discourse-reactions/app/controllers/discourse_reactions/custom_reactions_controller.rb b/plugins/discourse-reactions/app/controllers/discourse_reactions/custom_reactions_controller.rb
index df79de60539..840549cec37 100644
--- a/plugins/discourse-reactions/app/controllers/discourse_reactions/custom_reactions_controller.rb
+++ b/plugins/discourse-reactions/app/controllers/discourse_reactions/custom_reactions_controller.rb
@@ -9,32 +9,18 @@ class DiscourseReactions::CustomReactionsController < ApplicationController
before_action :ensure_logged_in, except: %i[reactions_users_list post_reactions_users]
def toggle
- post = fetch_post_from_params
- reaction = params[:reaction]
-
- return render_json_error(post) unless DiscourseReactions::Reaction.valid?(reaction)
-
- begin
- manager =
- DiscourseReactions::ReactionManager.new(
- reaction_value: params[:reaction],
- user: current_user,
- post: post,
- )
- manager.toggle!
- rescue ActiveRecord::RecordNotUnique
- # If the user already performed this action, it's probably due to a different browser tab
- # or non-debounced clicking. We can ignore.
+ DiscourseReactions::PostReaction::Toggle.call(
+ service_params.deep_merge(params: { post_id: params[:post_id], reaction: params[:reaction] }),
+ ) do |result|
+ on_success do |post:|
+ render_json_dump(PostSerializer.new(post, scope: guardian, root: false).as_json)
+ end
+ on_model_not_found(:post) { raise Discourse::NotFound }
+ on_failed_policy(:can_see_post) { raise Discourse::InvalidAccess }
+ on_failed_policy(:reaction_is_valid) { |_policy, post:| render_json_error(post) }
+ on_exceptions(Discourse::InvalidAccess) { |exception| raise exception }
+ on_failure { render_json_error(result) }
end
-
- post.publish_change_to_clients!(:acted)
- publish_change_to_clients!(
- post,
- reaction: manager.reaction_value,
- previous_reaction: manager.previous_reaction_value,
- )
-
- render_json_dump(post_serializer(post).as_json)
end
def reactions_given
@@ -362,10 +348,6 @@ class DiscourseReactions::CustomReactionsController < ApplicationController
likes.includes([:user]).limit(MAX_USERS_COUNT + 1).map { |like| format_like_user(like) }
end
- def post_serializer(post)
- PostSerializer.new(post, scope: guardian, root: false)
- end
-
def fetch_post_from_params
post_id = params[:post_id] || params[:id]
post = Post.find(post_id)
@@ -373,18 +355,6 @@ class DiscourseReactions::CustomReactionsController < ApplicationController
post
end
- def publish_change_to_clients!(post, reaction: nil, previous_reaction: nil)
- return unless (topic = post.topic)
-
- message = { post_id: post.id, reactions: [reaction, previous_reaction].compact.uniq }
-
- opts = topic.secure_audience_publish_messages
-
- if opts[:user_ids] != [] && opts[:group_ids] != []
- MessageBus.publish("/topic/#{topic.id}/reactions", message, opts)
- end
- end
-
def secure_reaction_users!(reaction_users)
builder = DB.build("/*where*/")
UserAction.apply_common_filters(builder, current_user.id, guardian)
diff --git a/plugins/discourse-reactions/app/services/discourse_reactions/post_reaction/toggle.rb b/plugins/discourse-reactions/app/services/discourse_reactions/post_reaction/toggle.rb
new file mode 100644
index 00000000000..eeaea3242df
--- /dev/null
+++ b/plugins/discourse-reactions/app/services/discourse_reactions/post_reaction/toggle.rb
@@ -0,0 +1,81 @@
+# frozen_string_literal: true
+
+module DiscourseReactions
+ module PostReaction
+ class Toggle
+ include Service::Base
+
+ params do
+ attribute :post_id, :integer
+ attribute :reaction, :string
+
+ validates :post_id, presence: true
+ validates :reaction, presence: true
+ end
+
+ model :post
+ policy :can_see_post
+ policy :reaction_is_valid
+ model :reaction_manager, :build_reaction_manager
+
+ try(Discourse::InvalidAccess) { step :toggle_reaction }
+
+ step :publish_post_acted
+
+ only_if(:topic_has_audience) { step :publish_reaction_change }
+
+ private
+
+ def fetch_post(params:)
+ Post.find_by(id: params.post_id)
+ end
+
+ def can_see_post(guardian:, post:)
+ guardian.can_see?(post)
+ end
+
+ def reaction_is_valid(params:)
+ DiscourseReactions::Reaction.valid?(params.reaction)
+ end
+
+ def build_reaction_manager(params:, guardian:, post:)
+ DiscourseReactions::ReactionManager.new(
+ reaction_value: params.reaction,
+ user: guardian.user,
+ post: post,
+ )
+ end
+
+ def toggle_reaction(reaction_manager:)
+ reaction_manager.toggle!
+ rescue ActiveRecord::RecordNotUnique
+ # Concurrent toggles are idempotent from the caller's perspective.
+ end
+
+ def publish_post_acted(post:)
+ post.publish_change_to_clients!(:acted)
+ end
+
+ def topic_has_audience(post:)
+ return if post.topic.blank?
+
+ audience = post.topic.secure_audience_publish_messages
+ audience[:user_ids] != [] && audience[:group_ids] != []
+ end
+
+ def publish_reaction_change(post:, reaction_manager:)
+ MessageBus.publish(
+ "/topic/#{post.topic_id}/reactions",
+ {
+ post_id: post.id,
+ reactions: [
+ reaction_manager.reaction_value,
+ reaction_manager.previous_reaction_value,
+ ].compact.uniq,
+ },
+ post.topic.secure_audience_publish_messages,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-reactions/plugin.rb b/plugins/discourse-reactions/plugin.rb
index 004407c7835..59f78ddc884 100644
--- a/plugins/discourse-reactions/plugin.rb
+++ b/plugins/discourse-reactions/plugin.rb
@@ -37,6 +37,7 @@ after_initialize do
app/services/discourse_reactions/reaction_manager.rb
app/services/discourse_reactions/reaction_notification.rb
app/services/discourse_reactions/reaction_like_synchronizer.rb
+ app/services/discourse_reactions/post_reaction/toggle.rb
lib/discourse_reactions/guardian_extension.rb
lib/discourse_reactions/notification_extension.rb
lib/discourse_reactions/post_alerter_extension.rb
@@ -63,11 +64,13 @@ after_initialize do
end
register_anonymous_action("react_to_post") do |user, params|
- post = Post.find_by(id: params["post_id"])
- next if !post || !user.guardian.can_see?(post)
- reaction_value = params["reaction"].to_s
- next if !DiscourseReactions::Reaction.valid?(reaction_value)
- DiscourseReactions::ReactionManager.new(reaction_value:, user:, post:).toggle!
+ DiscourseReactions::PostReaction::Toggle.call(
+ params: {
+ post_id: params["post_id"],
+ reaction: params["reaction"],
+ },
+ guardian: user.guardian,
+ )
end
Discourse::Application.routes.append { mount DiscourseReactions::Engine, at: "/" }
diff --git a/plugins/discourse-reactions/spec/requests/custom_reactions_controller_spec.rb b/plugins/discourse-reactions/spec/requests/custom_reactions_controller_spec.rb
index 140a19d154c..2808f9b288d 100644
--- a/plugins/discourse-reactions/spec/requests/custom_reactions_controller_spec.rb
+++ b/plugins/discourse-reactions/spec/requests/custom_reactions_controller_spec.rb
@@ -172,13 +172,6 @@ describe DiscourseReactions::CustomReactionsController do
expect(messages).to be_empty
end
- it "does not publish MessageBus messages when the post topic is unavailable" do
- post_1.stubs(:topic).returns(nil)
- MessageBus.expects(:publish).never
-
- described_class.new.send(:publish_change_to_clients!, post_1, reaction: "cry")
- end
-
it "errors when reaction is invalid" do
sign_in(user_1)
expect do
diff --git a/plugins/discourse-reactions/spec/services/post_reaction/toggle_spec.rb b/plugins/discourse-reactions/spec/services/post_reaction/toggle_spec.rb
new file mode 100644
index 00000000000..3b1aaa1d3f8
--- /dev/null
+++ b/plugins/discourse-reactions/spec/services/post_reaction/toggle_spec.rb
@@ -0,0 +1,117 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseReactions::PostReaction::Toggle do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:post_id) }
+ it { is_expected.to validate_presence_of(:reaction) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:acting_user, :user)
+ fab!(:topic, :topic_with_op)
+ let(:post) { topic.first_post }
+ let(:params) { { post_id:, reaction: } }
+ let(:dependencies) { { guardian: } }
+ let(:guardian) { acting_user.guardian }
+ let(:post_id) { post.id }
+ let(:reaction) { "laughing" }
+ let(:channel) { "/topic/#{post.topic_id}/reactions" }
+ let(:messages) { MessageBus.track_publish(channel) { result } }
+
+ before do
+ SiteSetting.discourse_reactions_enabled = true
+ SiteSetting.discourse_reactions_enabled_reactions = "laughing|hugs"
+ end
+
+ context "when the contract is invalid" do
+ let(:reaction) { nil }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when the post does not exist" do
+ let(:post_id) { 0 }
+
+ it { is_expected.to fail_to_find_a_model(:post) }
+ end
+
+ context "when the user cannot see the post" do
+ fab!(:private_topic, :private_message_topic)
+ let(:post) { Fabricate(:post, topic: private_topic) }
+
+ it { is_expected.to fail_a_policy(:can_see_post) }
+ end
+
+ context "when the reaction is invalid" do
+ let(:reaction) { "invalid-reaction" }
+
+ it { is_expected.to fail_a_policy(:reaction_is_valid) }
+ end
+
+ context "when the reaction cannot be toggled" do
+ before { acting_user.update!(silenced_till: 1.day.from_now) }
+
+ it { is_expected.to fail_with_exception(Discourse::InvalidAccess) }
+ end
+
+ context "when the topic is unavailable" do
+ before do
+ Post.stubs(:find_by).with(id: post.id).returns(post)
+ guardian.stubs(:can_see?).with(post).returns(true)
+ guardian.stubs(:can_use_reactions?).with(post).returns(true)
+ acting_user.stubs(:guardian).returns(guardian)
+ post.stubs(:topic).returns(nil)
+ end
+
+ it "toggles the reaction without publishing a reaction change" do
+ expect(messages).to be_empty
+ expect(result).to run_successfully
+ expect(DiscourseReactions::ReactionUser.exists?(user: acting_user, post:)).to eq(true)
+ end
+ end
+
+ context "when the secure audience is empty" do
+ fab!(:restricted_category) { Fabricate(:category, read_restricted: true) }
+ fab!(:restricted_topic) { Fabricate(:topic, category: restricted_category) }
+ fab!(:acting_user, :admin)
+ let(:post) { Fabricate(:post, topic: restricted_topic) }
+
+ it "toggles the reaction without publishing a reaction change" do
+ expect(messages).to be_empty
+ expect(result).to run_successfully
+ expect(DiscourseReactions::ReactionUser.exists?(user: acting_user, post:)).to eq(true)
+ end
+ end
+
+ context "when the topic has a secure audience" do
+ fab!(:recipient, :user)
+ fab!(:acting_user, :admin)
+ fab!(:private_topic) do
+ Fabricate(:private_message_topic, user: recipient, recipient: acting_user)
+ end
+ let(:post) { Fabricate(:post, topic: private_topic) }
+
+ it "publishes the reaction change only to the private-message participants" do
+ expect(messages.size).to eq(1)
+ expect(messages.first.user_ids).to contain_exactly(recipient.id, acting_user.id)
+ expect(messages.first.group_ids).to be_nil
+ end
+ end
+
+ context "when the reaction can be toggled" do
+ it { is_expected.to run_successfully }
+
+ it "creates the reaction" do
+ expect { result }.to change { DiscourseReactions::ReactionUser.count }.by(1)
+ expect(DiscourseReactions::ReactionUser.exists?(user: acting_user, post:)).to eq(true)
+ end
+
+ it "publishes the changed reaction" do
+ expect(messages.size).to eq(1)
+ expect(messages.first.data).to include(post_id: post.id, reactions: [reaction])
+ end
+ end
+ end
+end