Skip to content

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

FEATURE: Pin chat messages (#37985)

Joffrey JAFFEUXaf5329588e9c
diff --git a/plugins/chat/app/controllers/chat/api/channel_pins_controller.rb b/plugins/chat/app/controllers/chat/api/channel_pins_controller.rb
new file mode 100644
index 00000000000..5a5d5c6191e
--- /dev/null
+++ b/plugins/chat/app/controllers/chat/api/channel_pins_controller.rb
@@ -0,0 +1,90 @@
+# frozen_string_literal: true
+
+class Chat::Api::ChannelPinsController < Chat::ApiController
+ def index
+ raise Discourse::NotFound unless SiteSetting.chat_pinned_messages
+
+ Chat::ListChannelPins.call(service_params) do
+ on_success do |pins:, membership:|
+ render_serialized({ pins:, membership: }, Chat::ChannelPinsSerializer, root: false)
+ end
+ on_model_not_found(:channel) { raise Discourse::NotFound }
+ on_model_not_found(:membership) do |pins:|
+ render_serialized({ pins:, membership: nil }, Chat::ChannelPinsSerializer, root: false)
+ end
+ on_failed_policy(:can_view_channel) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render(json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request)
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ end
+ end
+
+ def mark_read
+ raise Discourse::NotFound unless SiteSetting.chat_pinned_messages
+
+ Chat::MarkPinsAsRead.call(params: { channel_id: params[:channel_id] }, guardian: guardian) do
+ on_success { render json: success_json }
+ on_model_not_found(:channel) { raise Discourse::NotFound }
+ on_model_not_found(:membership) { raise Discourse::NotFound }
+ on_failed_policy(:can_access_channel) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render(json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request)
+ end
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ end
+ end
+
+ def create
+ raise Discourse::NotFound unless SiteSetting.chat_pinned_messages
+
+ Chat::PinMessage.call(service_params) do
+ on_success { render(json: success_json) }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_model_not_found(:message) { raise Discourse::NotFound }
+ on_failed_policy(:can_pin) { raise Discourse::InvalidAccess }
+ on_failed_policy(:within_pin_limit) do
+ render(
+ json:
+ failed_json.merge(
+ error:
+ I18n.t(
+ "chat.errors.pin_limit_reached",
+ limit: Chat::PinnedMessage::MAX_PINS_PER_CHANNEL,
+ ),
+ ),
+ status: :unprocessable_entity,
+ )
+ end
+ on_failed_policy(:not_already_pinned) do
+ render(
+ json: failed_json.merge(error: I18n.t("chat.errors.message_already_pinned")),
+ status: :unprocessable_entity,
+ )
+ end
+ on_failed_contract do |contract|
+ render(json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request)
+ end
+ end
+ end
+
+ def destroy
+ raise Discourse::NotFound unless SiteSetting.chat_pinned_messages
+
+ Chat::UnpinMessage.call(service_params) do
+ on_success { render(json: success_json) }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
+ on_model_not_found(:message) { raise Discourse::NotFound }
+ on_model_not_found(:pin) do
+ render(
+ json: failed_json.merge(error: I18n.t("chat.errors.message_not_pinned")),
+ status: :unprocessable_entity,
+ )
+ end
+ on_failed_policy(:can_unpin) { raise Discourse::InvalidAccess }
+ on_failed_contract do |contract|
+ render(json: failed_json.merge(errors: contract.errors.full_messages), status: :bad_request)
+ end
+ end
+ end
+end
diff --git a/plugins/chat/app/jobs/scheduled/chat/delete_old_messages.rb b/plugins/chat/app/jobs/scheduled/chat/delete_old_messages.rb
index 0a706b3875b..20498cdb0e0 100644
--- a/plugins/chat/app/jobs/scheduled/chat/delete_old_messages.rb
+++ b/plugins/chat/app/jobs/scheduled/chat/delete_old_messages.rb
@@ -18,9 +18,11 @@ module Jobs
return unless valid_day_value?(:chat_channel_retention_days)
::Chat::MessageDestroyer.new.destroy_in_batches(
- ::Chat::Message.in_public_channel.with_deleted.created_before(
- ::SiteSetting.chat_channel_retention_days.days.ago,
- ),
+ ::Chat::Message
+ .in_public_channel
+ .with_deleted
+ .created_before(::SiteSetting.chat_channel_retention_days.days.ago)
+ .where.not(id: ::Chat::PinnedMessage.select(:chat_message_id)),
)
end
@@ -28,9 +30,11 @@ module Jobs
return unless valid_day_value?(:chat_dm_retention_days)
::Chat::MessageDestroyer.new.destroy_in_batches(
- ::Chat::Message.in_dm_channel.with_deleted.created_before(
- ::SiteSetting.chat_dm_retention_days.days.ago,
- ),
+ ::Chat::Message
+ .in_dm_channel
+ .with_deleted
+ .created_before(::SiteSetting.chat_dm_retention_days.days.ago)
+ .where.not(id: ::Chat::PinnedMessage.select(:chat_message_id)),
)
end
diff --git a/plugins/chat/app/models/chat/channel.rb b/plugins/chat/app/models/chat/channel.rb
index 3472d3ce64b..32c18dc7084 100644
--- a/plugins/chat/app/models/chat/channel.rb
+++ b/plugins/chat/app/models/chat/channel.rb
@@ -25,6 +25,7 @@ module Chat
class_name: "Chat::Message",
foreign_key: :last_message_id,
optional: true
+ has_many :pinned_messages, class_name: "Chat::PinnedMessage", foreign_key: :chat_channel_id
def last_message
super || NullMessage.new
@@ -145,6 +146,10 @@ module Chat
self.remove(user)
end
+ def pinned_messages_count
+ pinned_messages.size
+ end
+
def url
"#{Discourse.base_url}/chat/c/#{self.slug || "-"}/#{self.id}"
end
diff --git a/plugins/chat/app/models/chat/message.rb b/plugins/chat/app/models/chat/message.rb
index 918cae3d2e6..0bb54f7ae9d 100644
--- a/plugins/chat/app/models/chat/message.rb
+++ b/plugins/chat/app/models/chat/message.rb
@@ -57,6 +57,10 @@ module Chat
dependent: :destroy,
class_name: "Chat::Mention",
foreign_key: :chat_message_id
+ has_one :pinned_message,
+ class_name: "Chat::PinnedMessage",
+ foreign_key: :chat_message_id,
+ dependent: :destroy
has_many :user_mentions,
dependent: :destroy,
class_name: "Chat::UserMention",
diff --git a/plugins/chat/app/models/chat/pinned_message.rb b/plugins/chat/app/models/chat/pinned_message.rb
new file mode 100644
index 00000000000..da79edd0b32
--- /dev/null
+++ b/plugins/chat/app/models/chat/pinned_message.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+module Chat
+ class PinnedMessage < ActiveRecord::Base
+ self.table_name = "chat_pinned_messages"
+
+ MAX_PINS_PER_CHANNEL = 20
+
+ belongs_to :chat_message, class_name: "Chat::Message"
+ belongs_to :chat_channel, class_name: "Chat::Channel"
+ belongs_to :user, foreign_key: :pinned_by_id
+
+ validates :chat_message_id, uniqueness: true
+
+ scope :for_channel, ->(channel) { where(chat_channel: channel).order(created_at: :desc) }
+ end
+end
+
+# == Schema Information
+#
+# Table name: chat_pinned_messages
+#
+# id :bigint not null, primary key
+# created_at :datetime not null
+# updated_at :datetime not null
+# chat_channel_id :bigint not null
+# chat_message_id :bigint not null
+# pinned_by_id :bigint not null
+#
+# Indexes
+#
+# idx_chat_pinned_messages_channel_created (chat_channel_id,created_at DESC)
+# index_chat_pinned_messages_on_chat_message_id (chat_message_id) UNIQUE
+#
diff --git a/plugins/chat/app/models/chat/user_chat_channel_membership.rb b/plugins/chat/app/models/chat/user_chat_channel_membership.rb
index 736d4439f73..1b9dd2f0b7a 100644
--- a/plugins/chat/app/models/chat/user_chat_channel_membership.rb
+++ b/plugins/chat/app/models/chat/user_chat_channel_membership.rb
@@ -17,6 +17,24 @@ module Chat
def mark_read!(new_last_read_id = nil)
update!(last_read_message_id: new_last_read_id || chat_channel.last_message_id)
end
+
+ def has_unseen_pins?
+ pins = chat_channel.pinned_messages
+
+ if pins.loaded?
+ others = pins.reject { |pin| pin.pinned_by_id == user_id }
+ return false if others.empty?
+ return true if last_viewed_pins_at.nil?
+ others.any? { |pin| pin.created_at > last_viewed_pins_at }
+ else
+ others = pins.where.not(pinned_by_id: user_id)
+ if last_viewed_pins_at.nil?
+ others.exists?
+ else
+ others.where("created_at > ?", last_viewed_pins_at).exists?
+ end
+ end
+ end
end
end
@@ -28,6 +46,7 @@ end
# following :boolean default(FALSE), not null
# join_mode :integer default("manual"), not null
# last_viewed_at :datetime not null
+# last_viewed_pins_at :datetime
# muted :boolean default(FALSE), not null
# notification_level :integer default("mention"), not null
# starred :boolean default(FALSE), not null
diff --git a/plugins/chat/app/queries/chat/messages_query.rb b/plugins/chat/app/queries/chat/messages_query.rb
index e4a8bf5a347..7dfcea64a6b 100644
--- a/plugins/chat/app/queries/chat/messages_query.rb
+++ b/plugins/chat/app/queries/chat/messages_query.rb
@@ -107,6 +107,7 @@ module Chat
.includes(uploads: { optimized_videos: :optimized_upload })
.includes(chat_channel: :chatable)
.includes(thread: %i[original_message last_message])
+ .includes(:pinned_message)
.where(chat_channel_id: channel.id)
user_includes = SiteSetting.enable_user_status ? %i[user_status user_option] : %i[user_option]
diff --git a/plugins/chat/app/serializers/chat/base_channel_membership_serializer.rb b/plugins/chat/app/serializers/chat/base_channel_membership_serializer.rb
index 9dac232236f..14e77bb0c46 100644
--- a/plugins/chat/app/serializers/chat/base_channel_membership_serializer.rb
+++ b/plugins/chat/app/serializers/chat/base_channel_membership_serializer.rb
@@ -8,7 +8,9 @@ module Chat
:chat_channel_id,
:last_read_message_id,
:last_viewed_at,
- :starred
+ :last_viewed_pins_at,
+ :starred,
+ :has_unseen_pins
def starred
object.starred
@@ -17,5 +19,17 @@ module Chat
def include_starred?
scope&.authenticated?
end
+
+ def has_unseen_pins
+ object.has_unseen_pins?
+ end
+
+ def include_has_unseen_pins?
+ SiteSetting.chat_pinned_messages && scope&.authenticated?
+ end
+
+ def include_last_viewed_pins_at?
+ SiteSetting.chat_pinned_messages && scope&.authenticated?
+ end
end
end
diff --git a/plugins/chat/app/serializers/chat/channel_pins_serializer.rb b/plugins/chat/app/serializers/chat/channel_pins_serializer.rb
new file mode 100644
index 00000000000..893f7cda428
--- /dev/null
+++ b/plugins/chat/app/serializers/chat/channel_pins_serializer.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module Chat
+ class ChannelPinsSerializer < ApplicationSerializer
+ attributes :pinned_messages, :membership
+
+ def pinned_messages
+ ActiveModel::ArraySerializer.new(
+ object[:pins],
+ each_serializer: Chat::PinnedMessageSerializer,
+ scope: scope,
+ )
+ end
+
+ def membership
+ return if !object[:membership]
+
+ Chat::UserChannelMembershipSerializer.new(object[:membership], scope: scope, root: false)
+ end
+ end
+end
diff --git a/plugins/chat/app/serializers/chat/channel_serializer.rb b/plugins/chat/app/serializers/chat/channel_serializer.rb
index 68cdc5f1f5f..088f12828f7 100644
--- a/plugins/chat/app/serializers/chat/channel_serializer.rb
+++ b/plugins/chat/app/serializers/chat/channel_serializer.rb
@@ -23,7 +23,8 @@ module Chat
:memberships_count,
:current_user_membership,
:meta,
- :threading_enabled
+ :threading_enabled,
+ :pinned_messages_count
has_one :last_message, serializer: Chat::LastMessageSerializer, embed: :objects
@@ -46,6 +47,14 @@ module Chat
object.user_count
end
+ def pinned_messages_count
+ object.pinned_messages.size
+ end
+
+ def include_pinned_messages_count?
+ SiteSetting.chat_pinned_messages
+ end
+
def chatable_url
object.chatable_url
end
@@ -140,6 +149,7 @@ module Chat
data[:can_delete_self] = scope.can_delete_own_chats?(object.chatable)
data[:can_delete_others] = scope.can_delete_other_chats?(object.chatable)
data[:can_remove_members] = scope.can_remove_members?(object)
+ data[:can_manage_pins] = scope.can_manage_chat_channel_pins?(object)
data
end
diff --git a/plugins/chat/app/serializers/chat/message_serializer.rb b/plugins/chat/app/serializers/chat/message_serializer.rb
index d8f52e052dd..b821acdfa76 100644
--- a/plugins/chat/app/serializers/chat/message_serializer.rb
+++ b/plugins/chat/app/serializers/chat/message_serializer.rb
@@ -30,6 +30,7 @@ module Chat
blocks
channel
thread_title
+ pinned
]
),
)
@@ -216,6 +217,14 @@ module Chat
object.thread&.title
end
+ def pinned
+ object.pinned_message.present?
+ end
+
+ def include_pinned?
+ SiteSetting.chat_pinned_messages
+ end
+
def thread
Chat::ThreadSerializer.new(
object.thread,
diff --git a/plugins/chat/app/serializers/chat/pinned_message_serializer.rb b/plugins/chat/app/serializers/chat/pinned_message_serializer.rb
new file mode 100644
index 00000000000..a718d9b11af
--- /dev/null
+++ b/plugins/chat/app/serializers/chat/pinned_message_serializer.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+module Chat
+ class PinnedMessageSerializer < ::ApplicationSerializer
+ attributes :id, :chat_message_id, :pinned_at
+
+ has_one :pinned_by, serializer: ::BasicUserSerializer, embed: :objects
+ has_one :message, serializer: Chat::MessageSerializer, embed: :objects
+
+ def pinned_at
+ object.created_at
+ end
+
+ def pinned_by
+ object.user
+ end
+
+ def message
+ object.chat_message
+ end
+ end
+end
diff --git a/plugins/chat/app/services/chat/list_channel_pins.rb b/plugins/chat/app/services/chat/list_channel_pins.rb
new file mode 100644
index 00000000000..a2355e6e83e
--- /dev/null
+++ b/plugins/chat/app/services/chat/list_channel_pins.rb
@@ -0,0 +1,55 @@
+# frozen_string_literal: true
+
+module Chat
+ class ListChannelPins
+ include Service::Base
+
+ params do
+ attribute :channel_id, :integer
+
+ validates :channel_id, presence: true
+ end
+
+ model :channel
+ policy :can_view_channel
+ model :membership, optional: true
+ model :pins
+
+ private
+
+ def fetch_channel(params:)
+ Chat::Channel.find_by(id: params.channel_id)
+ end
+
+ def can_view_channel(guardian:, channel:)
+ guardian.can_preview_chat_channel?(channel)
+ end
+
+ def fetch_membership(channel:, guardian:)
+ channel.membership_for(guardian.user)
+ end
+
+ def fetch_pins(channel:)
+ user_includes =
+ if SiteSetting.enable_user_status
+ %i[user_status user_option primary_group]
+ else
+ %i[user_option primary_group]
+ end
+
+ Chat::PinnedMessage.for_channel(channel).includes(
+ chat_message: [
+ :revisions,
+ :bookmarks,
+ { uploads: { optimized_videos: :optimized_upload } },
+ { chat_channel: :chatable },
+ :thread,
+ { user: user_includes },
+ { user_mentions: { user: user_includes } },
+ { reactions: :user },
+ { in_reply_to: [:user] },
+ ],
+ )
+ end
+ end
+end
diff --git a/plugins/chat/app/services/chat/mark_pins_as_read.rb b/plugins/chat/app/services/chat/mark_pins_as_read.rb
new file mode 100644
index 00000000000..b08115f3f1e
--- /dev/null
+++ b/plugins/chat/app/services/chat/mark_pins_as_read.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+module Chat
+ class MarkPinsAsRead
+ include Service::Base
+
+ params do
+ attribute :channel_id, :integer
+
+ validates :channel_id, presence: true
+ end
+
+ model :channel
+ model :membership
+ policy :can_access_channel
+ step :update_last_viewed_at
+
+ private
+
+ def fetch_channel(params:)
+ Chat::Channel.find_by(id: params.channel_id)
+ end
+
+ def fetch_membership(guardian:, channel:)
+ channel.membership_for(guardian.user)
+ end
+
+ def can_access_channel(guardian:, channel:)
+ guardian.can_preview_chat_channel?(channel)
+ end
+
+ def update_last_viewed_at(membership:)
+ membership.update!(last_viewed_pins_at: Time.zone.now)
+ end
+ end
+end
diff --git a/plugins/chat/app/services/chat/pin_message.rb b/plugins/chat/app/services/chat/pin_message.rb
new file mode 100644
index 00000000000..289eead46fd
--- /dev/null
+++ b/plugins/chat/app/services/chat/pin_message.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+module Chat
+ class PinMessage
+ include Service::Base
+
+ params do
+ attribute :message_id, :integer
+ attribute :channel_id, :integer
+
+ validates :message_id, presence: true
+ validates :channel_id, presence: true
+ end
+
+ model :message
+ policy :can_pin
+ policy :within_pin_limit
+ policy :not_already_pinned
+
+ model :pin, :create_pin
+ step :publish_pin_event
+
+ private
+
+ def fetch_message(params:)
+ Chat::Message.includes(:chat_channel).find_by(
+ id: params.message_id,
+ chat_channel_id: params.channel_id,
+ )
+ end
+
+ def can_pin(guardian:, message:)
+ guardian.can_manage_chat_message_pin?(message)
+ end
+
+ def within_pin_limit(message:)
+ message.chat_channel.pinned_messages.count < Chat::PinnedMessage::MAX_PINS_PER_CHANNEL
+ end
+
+ def not_already_pinned(message:)
+ !message.pinned_message.present?
+ end
+
+ def create_pin(message:, guardian:)
+ Chat::PinnedMessage.create(
+ chat_message: message,
+ chat_channel: message.chat_channel,
+ pinned_by_id: guardian.user.id,
+ )
+ end
+
+ def publish_pin_event(message:, pin:)
+ Chat::Publisher.publish_pin!(message.chat_channel, message, pin)
+ end
+ end
+end
diff --git a/plugins/chat/app/services/chat/publisher.rb b/plugins/chat/app/services/chat/publisher.rb
index 5d368bb86a9..5987ac2fefe 100644
--- a/plugins/chat/app/services/chat/publisher.rb
+++ b/plugins/chat/app/services/chat/publisher.rb
@@ -462,6 +462,25 @@ module Chat
)
end
+ def self.publish_pin!(chat_channel, chat_message, pin)
+ publish_to_channel!(
+ chat_channel,
+ {
+ type: :pin,
+ chat_message_id: chat_message.id,
+ pinned_at: pin.created_at.iso8601(3),
+ pinned_by_id: pin.pinned_by_id,
+ },
+ )
+ end
+
+ def self.publish_unpin!(chat_channel, chat_message, unpinned_by)
+ publish_to_channel!(
+ chat_channel,
+ { type: :unpin, chat_message_id: chat_message.id, unpinned_by_id: unpinned_by.id },
+ )
+ end
+
def self.publish_notice(user_id:, channel_id:, text_content: nil, type: nil, data: nil)
# Notices are either plain text sent to the client, or a "type" with data. The
# client will then translate that type and data into a front-end component.
diff --git a/plugins/chat/app/services/chat/trash_message.rb b/plugins/chat/app/services/chat/trash_message.rb
index 03365150f9f..ca27120069f 100644
--- a/plugins/chat/app/services/chat/trash_message.rb
+++ b/plugins/chat/app/services/chat/trash_message.rb
@@ -29,8 +29,11 @@ module Chat
model :message
policy :invalid_access
+ model :pinned_message, optional: true
+
transaction do
step :trash_message
+ step :destroy_pin
step :destroy_notifications
step :update_last_message_ids
step :update_tracking_state
@@ -56,6 +59,14 @@ module Chat
message.trash!(guardian.user)
end
+ def fetch_pinned_message(message:)
+ message.pinned_message
+ end
+
+ def destroy_pin(pinned_message:)
+ pinned_message&.destroy!
+ end
+
def destroy_notifications(message:)
Notification.where(
id:
@@ -82,10 +93,12 @@ module Chat
message.chat_channel.update_last_message_id!
end
- def publish_events(guardian:, message:)
+ def publish_events(guardian:, message:, pinned_message:)
DiscourseEvent.trigger(:chat_message_trashed, message, message.chat_channel, guardian.user)
Chat::Publisher.publish_delete!(message.chat_channel, message)
+ Chat::Publisher.publish_unpin!(message.chat_channel, message, guardian.user) if pinned_message
+
if message.thread.present?
Chat::Publisher.publish_thread_original_message_metadata!(message.thread)
end
diff --git a/plugins/chat/app/services/chat/unpin_message.rb b/plugins/chat/app/services/chat/unpin_message.rb
new file mode 100644
index 00000000000..67e6f3a9f17
--- /dev/null
+++ b/plugins/chat/app/services/chat/unpin_message.rb
@@ -0,0 +1,46 @@
+# frozen_string_literal: true
+
+module Chat
+ class UnpinMessage
+ include Service::Base
+
+ params do
+ attribute :message_id, :integer
+ attribute :channel_id, :integer
+
+ validates :message_id, presence: true
+ validates :channel_id, presence: true
+ end
+
+ model :message
+ policy :can_unpin
+ model :pin
+ step :destroy_pin
+ step :publish_unpin_event
+
+ private
+
+ def fetch_message(params:)
+ Chat::Message.includes(:chat_channel).find_by(
+ id: params.message_id,
+ chat_channel_id: params.channel_id,
+ )
+ end
+
+ def can_unpin(guardian:, message:)
+ guardian.can_manage_chat_message_pin?(message)
+ end
+
+ def fetch_pin(message:)
+ message.pinned_message
+ end
+
+ def destroy_pin(pin:)
+ pin.destroy!
+ end
+
+ def publish_unpin_event(message:, guardian:)
+ Chat::Publisher.publish_unpin!(message.chat_channel, message, guardian.user)
+ end
+ end
+end
diff --git a/plugins/chat/assets/javascripts/discourse/chat-route-map.js b/plugins/chat/assets/javascripts/discourse/chat-route-map.js
index 1d740512e1c..3313c8c7550 100644
--- a/plugins/chat/assets/javascripts/discourse/chat-route-map.js
+++ b/plugins/chat/assets/javascripts/discourse/chat-route-map.js
@@ -12,6 +12,7 @@ export default function () {
this.route("thread", { path: "/t/:threadId" }, function () {
this.route("near-message", { path: "/:messageId" });
});
+ this.route("pins");
});
this.route("direct-messages");
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message-actions-desktop.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-message-actions-desktop.gjs
index ddfdab88615..aea9e9d0eb1 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat-message-actions-desktop.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message-actions-desktop.gjs
@@ -75,7 +75,12 @@ export default class ChatMessageActionsDesktop extends Component {
return;
}
- const boundary = container.closest(".chat-messages-scroller");
+ const boundary = this.messageContainer.closest(".chat-messages-scroller");
+
+ if (!boundary) {
+ return;
+ }
+
this.size = boundary.clientWidth < REDUCED_WIDTH_THRESHOLD ? REDUCED : FULL;
next(() => {
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs
index 7eed8dcf5df..6a7b983700d 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs
@@ -141,7 +141,11 @@ export default class ChatMessage extends Component {
}
get shouldRenderOpenEmojiPickerButton() {
- return this.chat.userCanInteractWithChat && this.site.desktopView;
+ return (
+ this.args.interactive !== false &&
+ this.chat.userCanInteractWithChat &&
+ this.site.desktopView
+ );
}
get secondaryActionsIsExpanded() {
@@ -339,7 +343,7 @@ export default class ChatMessage extends Component {
}
_setActiveMessage() {
- if (this.args.disableMouseEvents) {
+ if (this.args.disableMouseEvents || this.args.interactive === false) {
return;
}
@@ -396,6 +400,10 @@ export default class ChatMessage extends Component {
@action
onLongPressEnd(element, event) {
+ if (this.args.interactive === false) {
+ return;
+ }
+
if (event.target.tagName === "IMG") {
return;
}
@@ -430,6 +438,10 @@ export default class ChatMessage extends Component {
get hideUserInfo() {
const message = this.args.message;
+ if (message.pinned) {
+ return false;
+ }
+
const previousMessage = message.previousMessage;
if (!previousMessage) {
@@ -561,6 +573,7 @@ export default class ChatMessage extends Component {
(if @message.deletedAt "-deleted")
(if @message.selected "-selected")
(if @message.error "-errored")
+ (if (eq @interactive false) "-not-interactive")
(if this.showThreadIndicator "has-thread-indicator")
(if this.hideUserInfo "-user-info-hidden")
(if this.hasReply "has-reply")
@@ -579,6 +592,8 @@ export default class ChatMessage extends Component {
}}
...attributes
>
+ {{yield to="top"}}
+
{{#if this.show}}
{{#if this.pane.selectingMessages}}
<Input
@@ -627,6 +642,7 @@ export default class ChatMessage extends Component {
<ChatMessageInfo
@message={{@message}}
@show={{not this.hideUserInfo}}
+ @context={{@context}}
@threadContext={{this.threadContext}}
@dateMode={{@dateMode}}
/>
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-pinned-messages-list.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-pinned-messages-list.gjs
new file mode 100644
index 00000000000..add30eb6d9d
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat-pinned-messages-list.gjs
@@ -0,0 +1,155 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { LinkTo } from "@ember/routing";
+import { service } from "@ember/service";
+import { modifier as modifierFn } from "ember-modifier";
+import icon from "discourse/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+import ChatMessage from "discourse/plugins/chat/discourse/components/chat-message";
+
+export default class ChatPinnedMessagesList extends Component {
+ @service messageBus;
+ @service chatApi;
+ @service currentUser;
+
+ @tracked pinnedMessages = this.args.pinnedMessages || [];
+
+ subscribe = modifierFn(() => {
+ const channel = this.args.channel;
+
+ this.messageBus.subscribe(
+ `/chat/${channel.id}`,
+ this.onMessage,
+ channel.channelMessageBusLastId
+ );
+
+ this.#markPinsAsRead(channel);
+
+ return () => {
+ this.messageBus.unsubscribe(`/chat/${channel.id}`, this.onMessage);
+ this.#markPinsAsRead(channel);
+ };
+ });
+
+ onMessage = (busData) => {
+ switch (busData.type) {
+ case "pin":
+ this.handlePinMessage(busData);
+ break;
+ case "unpin":
+ this.handleUnpinMessage(busData);
+ break;
+ }
+ };
+
+ isUnseen = (pin) => {
+ if (pin.pinned_by?.id === this.currentUser?.id) {
+ return false;
+ }
+
+ if (!this.#lastViewedPinsAtSnapshot) {
+ return true;
+ }
+
+ const pinnedAt = new Date(pin.pinned_at);
+ const lastViewed = new Date(this.#lastViewedPinsAtSnapshot);
+ return pinnedAt > lastViewed;
+ };
+
+ decorateMessage = (pin) => {
+ pin.message.isUnseen = this.isUnseen(pin);
+ return pin.message;
+ };
+
+ pinnedByText = (pin) => {
+ if (pin.pinned_by?.id === this.currentUser?.id) {
+ return i18n("chat.pinned_messages.pinned_by_you");
+ }
+ return i18n("chat.pinned_messages.pinned_by_user", {
+ username: pin.pinned_by?.username,
+ });
+ };
+
+ routeModels = (pin) => {
+ return [...this.args.channel.routeModels, pin.message.id];
+ };
+
+ #lastViewedPinsAtSnapshot =
+ this.args.channel.currentUserMembership?.lastViewedPinsAt;
+
+ handlePinMessage(data) {
+ const existingPin = this.pinnedMessages.find(
+ (pin) => pin.message.id === data.chat_message_id
+ );
+
+ if (existingPin) {
+ return;
+ }
+
+ this.chatApi.pinnedMessages(this.args.channel).then((pinnedMessages) => {
+ this.pinnedMessages = pinnedMessages;
+
+ // If current user pinned this message, update timestamp so it doesn't show as unseen
+ if (
+ this.args.channel.currentUserMembership &&
+ data.pinned_by_id === this.currentUser.id
+ ) {
+ this.args.channel.currentUserMembership.lastViewedPinsAt = new Date();
+ }
+ });
+ }
+
+ #markPinsAsRead(channel) {
+ if (channel.currentUserMembership) {
+ channel.currentUserMembership.lastViewedPinsAt = new Date();
+ channel.currentUserMembership.hasUnseenPins = false;
+ this.chatApi.markPinsAsRead(channel.id).catch(() => {});
+ }
+ }
+
+ handleUnpinMessage(data) {
+ this.pinnedMessages = this.pinnedMessages.filter(
+ (pin) => pin.message.id !== data.chat_message_id
+ );
+ }
+
+ <template>
+ <div
+ class="chat-pinned-messages-list chat-messages-scroller"
+ {{this.subscribe}}
+ >
+ <div class="chat-pinned-messages-list__items">
+ {{#each this.pinnedMessages as |pin|}}
+ <LinkTo
+ @route="chat.channel.near-message"
+ @models={{this.routeModels pin}}
+ class="chat-pinned-message"
+ >
+ <ChatMessage
+ @message={{this.decorateMessage pin}}
+ @context="pinned"
+ @includeSeparator={{false}}
+ @interactive={{false}}
+ >
+ <:top>
+ <div class="chat-pinned-message__pinned-by">
+ {{#if (this.isUnseen pin)}}
+ {{icon
+ "thumbtack"
+ class="chat-pinned-message__pinned-by-icon"
+ }}
+ {{/if}}
+ <span>{{this.pinnedByText pin}}</span>
+ </div>
+ </:top>
+ </ChatMessage>
+ </LinkTo>
+ {{else}}
+ <div class="chat-pinned-messages-list__empty">
+ {{i18n "chat.no_pinned_messages"}}
+ </div>
+ {{/each}}
+ </div>
+ </div>
+ </template>
+}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel-pins.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel-pins.gjs
new file mode 100644
index 00000000000..59e2f706d06
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel-pins.gjs
@@ -0,0 +1,51 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import { htmlSafe } from "@ember/template";
+import replaceEmoji from "discourse/helpers/replace-emoji";
+import { i18n } from "discourse-i18n";
+import Navbar from "discourse/plugins/chat/discourse/components/chat/navbar";
+import ChatPinnedMessagesList from "discourse/plugins/chat/discourse/components/chat-pinned-messages-list";
+
+export default class ChatDrawerRoutesChannelPins extends Component {
+ @service chat;
+ @service chatStateManager;
+
+ backLinkTitle = i18n("chat.return_to_list");
+
+ get title() {
+ return htmlSafe(
+ i18n("chat.pinned_messages.title") +
+ " - " +
+ replaceEmoji(this.args.model.channel.escapedTitle)
+ );
+ }
+
+ <template>
+ <div class="c-drawer-routes --channel-pins">
+ {{#if @model}}
+ <Navbar @onClick={{this.chat.toggleDrawer}} as |navbar|>
+ <navbar.BackButton
+ @title={{this.backLinkTitle}}
+ @route="chat.channel"
+ @routeModels={{@model.channel.routeModels}}
+ />
+ <navbar.Title @title={{this.title}} @icon="thumbtack" />
+ <navbar.Actions as |a|>
+ <a.ToggleDrawerButton />
+ <a.FullPageButton />
+ <a.CloseDrawerButton />
+ </navbar.Actions>
+ </Navbar>
+
+ {{#if this.chatStateManager.isDrawerExpanded}}
+ <div class="chat-drawer-content">
+ <ChatPinnedMessagesList
+ @channel={{@model.channel}}
+ @pinnedMessages={{@model.pinnedMessages}}
+ />
+ </div>
+ {{/if}}
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel-threads.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel-threads.gjs
index 6fe19725014..d265037eb54 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel-threads.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel-threads.gjs
@@ -16,7 +16,7 @@ export default class ChatDrawerRoutesChannelThreads extends Component {
return htmlSafe(
i18n("chat.threads.list") +
" - " +
- replaceEmoji(this.args.model.channel.title)
+ replaceEmoji(this.args.model.channel.escapedTitle)
);
}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel.gjs
index 76e5308e95a..d1eb7a714d2 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/drawer-routes/channel.gjs
@@ -49,6 +49,7 @@ export default class ChatDrawerRoutesChannel extends Component {
{{/if}}
<a.ThreadsListButton @channel={{@model.channel}} />
+ <a.PinnedMessagesButton @channel={{@model.channel}} />
<a.ToggleDrawerButton />
<a.FullPageButton />
<a.CloseDrawerButton />
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/message/info.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/message/info.gjs
index 4eddcc87d3c..aa0508fdd6b 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat/message/info.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/message/info.gjs
@@ -10,7 +10,7 @@ import concatClass from "discourse/helpers/concat-class";
import icon from "discourse/helpers/d-icon";
import { bind } from "discourse/lib/decorators";
import { prioritizeNameInUx } from "discourse/lib/settings";
-import { and } from "discourse/truth-helpers";
+import { and, eq, not } from "discourse/truth-helpers";
import { i18n } from "discourse-i18n";
import ChannelTitle from "discourse/plugins/chat/discourse/components/channel-title";
import formatChatDate from "../../../helpers/format-chat-date";
@@ -155,6 +155,17 @@ export default class ChatMessageInfo extends Component {
</span>
{{/if}}
+ {{#if this.siteSettings.chat_pinned_messages}}
+ {{#if (and @message.pinned (not (eq @context "pinned")))}}
+ <span
+ class="chat-message-info__pinned"
+ title={{i18n "chat.pinned"}}
+ >
+ {{icon "thumbtack"}}
+ </span>
+ {{/if}}
+ {{/if}}
+
{{#if this.isFlagged}}
<span class="chat-message-info__flag">
{{#if @message.reviewableId}}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/actions.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/actions.gjs
index e2c13dd60f3..e4fbce851c7 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/actions.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/actions.gjs
@@ -1,6 +1,7 @@
import { hash } from "@ember/helper";
import BrowseChannelsButton from "./browse-channels-button";
import CloseDrawerButton from "./close-drawer-button";
+import ClosePinsButton from "./close-pins-button";
import CloseThreadButton from "./close-thread-button";
import CloseThreadsButton from "./close-threads-button";
import Filter from "./filter";
@@ -8,6 +9,7 @@ import FullPageButton from "./full-page-button";
import NewChannelButton from "./new-channel-button";
import NewDirectMessageButton from "./new-direct-message-button";
import OpenDrawerButton from "./open-drawer-button";
+import PinnedMessagesButton from "./pinned-messages-button";
import ThreadSettingsButton from "./thread-settings-button";
import ThreadTrackingDropdown from "./thread-tracking-dropdown";
import ThreadsListButton from "./threads-list-button";
@@ -24,8 +26,10 @@ const ChatNavbarActions = <template>
ThreadTrackingDropdown=ThreadTrackingDropdown
CloseThreadButton=CloseThreadButton
CloseThreadsButton=CloseThreadsButton
+ ClosePinsButton=ClosePinsButton
ThreadSettingsButton=ThreadSettingsButton
ThreadsListButton=ThreadsListButton
+ PinnedMessagesButton=PinnedMessagesButton
CloseDrawerButton=CloseDrawerButton
ToggleDrawerButton=ToggleDrawerButton
FullPageButton=FullPageButton
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/close-pins-button.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/close-pins-button.gjs
new file mode 100644
index 00000000000..cbf199f0b5e
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/close-pins-button.gjs
@@ -0,0 +1,24 @@
+import Component from "@glimmer/component";
+import { LinkTo } from "@ember/routing";
+import { service } from "@ember/service";
+import icon from "discourse/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+export default class ChatNavbarClosePinsButton extends Component {
+ @service site;
+
+ closeButtonTitle = i18n("chat.pinned_messages.close");
+
+ <template>
+ {{#if this.site.desktopView}}
+ <LinkTo
+ class="c-navbar__close-pins-button btn-transparent btn btn-icon no-text"
+ @route="chat.channel"
+ @models={{@channel.routeModels}}
+ title={{this.closeButtonTitle}}
+ >
+ {{icon "xmark"}}
+ </LinkTo>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/pinned-messages-button.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/pinned-messages-button.gjs
new file mode 100644
index 00000000000..c899f54b8ad
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/pinned-messages-button.gjs
@@ -0,0 +1,42 @@
+import Component from "@glimmer/component";
+import { on } from "@ember/modifier";
+import { LinkTo } from "@ember/routing";
+import { service } from "@ember/service";
+import icon from "discourse/helpers/d-icon";
+import { i18n } from "discourse-i18n";
+
+export default class ChatNavbarPinnedMessagesButton extends Component {
+ @service router;
+ @service siteSettings;
+
+ pinnedMessagesLabel = i18n("chat.pinned_messages.title");
+
+ handleClick = (event) => {
+ event.stopPropagation();
+ };
+
+ get showButton() {
+ return (
+ this.siteSettings.chat_pinned_messages &&
+ this.args.channel?.hasPinnedMessages &&
+ this.router.currentRoute?.name !== "chat.channel.pins"
+ );
+ }
+
+ <template>
+ {{#if this.showButton}}
+ <LinkTo
+ @route="chat.channel.pins"
+ @models={{@channel.routeModels}}
+ title={{this.pinnedMessagesLabel}}
+ class="c-navbar__pinned-messages-btn btn no-text btn-transparent"
+ {{on "click" this.handleClick}}
+ >
+ {{icon "thumbtack"}}
+ {{#if @channel.hasUnseenPins}}
+ <span class="c-navbar__pinned-messages-btn__unread-indicator"></span>
+ {{/if}}
+ </LinkTo>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/pinned-messages-list/header.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/pinned-messages-list/header.gjs
new file mode 100644
index 00000000000..f182bf09aaa
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/pinned-messages-list/header.gjs
@@ -0,0 +1,40 @@
+import Component from "@glimmer/component";
+import { service } from "@ember/service";
+import { htmlSafe } from "@ember/template";
+import replaceEmoji from "discourse/helpers/replace-emoji";
+import { i18n } from "discourse-i18n";
+import Navbar from "discourse/plugins/chat/discourse/components/chat/navbar";
+
+export default class ChatPinnedMessagesListHeader extends Component {
+ @service site;
+
+ pinnedMessagesTitle = i18n("chat.pinned_messages.title");
+
+ get title() {
+ let title = replaceEmoji(this.pinnedMessagesTitle);
+
+ if (this.site.mobileView) {
+ title += " - " + replaceEmoji(this.args.channel.escapedTitle);
+ }
+
+ return htmlSafe(title);
+ }
+
+ <template>
+ <Navbar as |navbar|>
+ {{#if this.site.mobileView}}
+ <navbar.BackButton
+ @route="chat.channel"
+ @routeModels={{@channel.routeModels}}
+ @title={{i18n "chat.return_to_channel"}}
+ />
+ {{/if}}
+
+ <navbar.Title @title={{this.title}} @icon="thumbtack" />
+
+ <navbar.Actions as |action|>
+ <action.ClosePinsButton @channel={{@channel}} />
+ </navbar.Actions>
+ </Navbar>
+ </template>
+}
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel-pins.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel-pins.gjs
new file mode 100644
index 00000000000..b1b687bb176
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel-pins.gjs
@@ -0,0 +1,14 @@
+import ChatPinnedMessagesListHeader from "discourse/plugins/chat/discourse/components/chat/pinned-messages-list/header";
+import ChatPinnedMessagesList from "discourse/plugins/chat/discourse/components/chat-pinned-messages-list";
+
+const ChatRoutesChannelPins = <template>
+ <div class="c-routes --channel-pins c-channel-pins">
+ <ChatPinnedMessagesListHeader @channel={{@channel}} />
+ <ChatPinnedMessagesList
+ @channel={{@channel}}
+ @pinnedMessages={{@pinnedMessages}}
+ />
+ </div>
+</template>;
+
+export default ChatRoutesChannelPins;
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel.gjs
index 17670042c89..a3d72d6e9f7 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel.gjs
@@ -51,6 +51,7 @@ export default class ChatRoutesChannel extends Component {
{{/if}}
<a.OpenDrawerButton />
+ <a.PinnedMessagesButton @channel={{@channel}} />
<a.ThreadsListButton @channel={{@channel}} />
</navbar.Actions>
</Navbar>
diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/thread-list/header.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/thread-list/header.gjs
index e9bf8bf5505..8371609adaa 100644
--- a/plugins/chat/assets/javascripts/discourse/components/chat/thread-list/header.gjs
+++ b/plugins/chat/assets/javascripts/discourse/components/chat/thread-list/header.gjs
@@ -14,7 +14,7 @@ export default class ChatThreadListHeader extends Component {
let title = replaceEmoji(this.threadListTitle);
if (this.site.mobileView) {
- title += " - " + replaceEmoji(this.args.channel.title);
+ title += " - " + replaceEmoji(this.args.channel.escapedTitle);
}
return htmlSafe(title);
diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-channel-subscription-manager.js b/plugins/chat/assets/javascripts/discourse/lib/chat-channel-subscription-manager.js
index 676a8f85e3f..dcefbdd90af 100644
--- a/plugins/chat/assets/javascripts/discourse/lib/chat-channel-subscription-manager.js
+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-channel-subscription-manager.js
@@ -80,6 +80,12 @@ export default class ChatChannelSubscriptionManager {
case "notice":
this.handleNotice(busData);
break;
+ case "pin":
+ this.handlePinMessage(busData);
+ break;
+ case "unpin":
+ this.handleUnpinMessage(busData);
+ break;
}
this.channel.channelMessageBusLastId = lastMessageBusId;
@@ -246,4 +252,44 @@ export default class ChatChannelSubscriptionManager {
}
}
}
+
+ handlePinMessage(data) {
+ const alreadyApplied = this.channel.pendingOptimisticPins.delete(
+ data.chat_message_id
+ );
+
+ const message = this.messagesManager.findMessage(data.chat_message_id);
+ if (message) {
+ message.pinned = true;
+ }
+
+ if (!alreadyApplied) {
+ this.channel.pinnedMessagesCount++;
+ }
+
+ if (
+ this.channel.currentUserMembership &&
+ data.pinned_by_id !== this.currentUser?.id
+ ) {
+ this.channel.currentUserMembership.hasUnseenPins = true;
+ }
+ }
+
+ handleUnpinMessage(data) {
+ const alreadyApplied = this.channel.pendingOptimisticUnpins.delete(
+ data.chat_message_id
+ );
+
+ const message = this.messagesManager.findMessage(data.chat_message_id);
+ if (message) {
+ message.pinned = false;
+ }
+
+ if (!alreadyApplied) {
+ this.channel.pinnedMessagesCount = Math.max(
+ 0,
+ this.channel.pinnedMessagesCount - 1
+ );
+ }
+ }
}
diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-message-container.js b/plugins/chat/assets/javascripts/discourse/lib/chat-message-container.js
index ccf5aef3f14..0268c5fe395 100644
--- a/plugins/chat/assets/javascripts/discourse/lib/chat-message-container.js
+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-message-container.js
@@ -1,10 +1,14 @@
import { MESSAGE_CONTEXT_THREAD } from "discourse/plugins/chat/discourse/components/chat-message";
+export const MESSAGE_CONTEXT_PINNED = "pinned";
+
export default function chatMessageContainer(id, context) {
let selector;
if (context === MESSAGE_CONTEXT_THREAD) {
selector = `.chat-thread .chat-message-container[data-id="${id}"]`;
+ } else if (context === MESSAGE_CONTEXT_PINNED) {
+ selector = `.chat-pinned-messages-list .chat-message-container[data-id="${id}"]`;
} else {
selector = `.chat-channel .chat-message-container[data-id="${id}"]`;
}
diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-message-interactor.js b/plugins/chat/assets/javascripts/discourse/lib/chat-message-interactor.js
index b6a0f05a749..f0b405b88fe 100644
--- a/plugins/chat/assets/javascripts/discourse/lib/chat-message-interactor.js
+++ b/plugins/chat/assets/javascripts/discourse/lib/chat-message-interactor.js
@@ -156,6 +156,13 @@ export default class ChatemojiReactions {
);
}
+ get canPinMessage() {
+ if (!this.siteSettings.chat_pinned_messages) {
+ return false;
+ }
+ return this.message.channel?.canManagePins;
+ }
+
get canRebakeMessage() {
return (
this.currentUser.staff &&
@@ -216,6 +223,22 @@ export default class ChatemojiReactions {
});
}
+ if (this.canPinMessage && !this.message.pinned) {
+ buttons.push({
+ id: "pin",
+ name: i18n("chat.pin_message"),
+ icon: "thumbtack",
+ });
+ }
+
+ if (this.canPinMessage && this.message.pinned) {
+ buttons.push({
+ id: "unpin",
+ name: i18n("chat.unpin_message"),
+ icon: "thumbtack",
+ });
+ }
+
if (this.canFlagMessage) {
buttons.push({
id: "flag",
@@ -420,6 +443,41 @@ export default class ChatemojiReactions {
.catch(popupAjaxError);
}
+ @action
+ pin() {
+ this.message.pinned = true;
+ this.message.channel.pinnedMessagesCount++;
+ this.message.channel.pendingOptimisticPins.add(this.message.id);
+
+ return this.chatApi
+ .pinMessage(this.message.channel.id, this.message.id)
+ .catch((error) => {
+ this.message.pinned = false;
+ this.message.channel.pinnedMessagesCount--;
+ this.message.channel.pendingOptimisticPins.delete(this.message.id);
+ popupAjaxError(error);
+ });
+ }
+
+ @action
+ unpin() {
+ this.message.pinned = false;
+ this.message.channel.pinnedMessagesCount = Math.max(
+ 0,
+ this.message.channel.pinnedMessagesCount - 1
+ );
+ this.message.channel.pendingOptimisticUnpins.add(this.message.id);
+
+ return this.chatApi
+ .unpinMessage(this.message.channel.id, this.message.id)
+ .catch((error) => {
+ this.message.pinned = true;
+ this.message.channel.pinnedMessagesCount++;
+ this.message.channel.pendingOptimisticUnpins.delete(this.message.id);
+ popupAjaxError(error);
+ });
+ }
+
@action
reply() {
this.composer.replyTo(this.message);
diff --git a/plugins/chat/assets/javascripts/discourse/models/chat-channel.js b/plugins/chat/assets/javascripts/discourse/models/chat-channel.js
index 3d67f811828..8ef662bc83d 100644
--- a/plugins/chat/assets/javascripts/discourse/models/chat-channel.js
+++ b/plugins/chat/assets/javascripts/discourse/models/chat-channel.js
@@ -72,9 +72,12 @@ export default class ChatChannel {
@tracked threadingEnabled;
@tracked draft;
@tracked newestMessage;
+ @tracked pinnedMessagesCount;
threadsManager = new ChatThreadsManager(getOwnerWithFallback(this));
messagesManager = new ChatMessagesManager(getOwnerWithFallback(this));
+ pendingOptimisticPins = new Set();
+ pendingOptimisticUnpins = new Set();
@tracked _currentUserMembership;
@tracked _lastMessage;
@@ -100,6 +103,7 @@ export default class ChatChannel {
this.chatable = this.#initChatable(args.chatable ?? []);
this.tracking = new ChatTrackingState(getOwnerWithFallback(this));
+ this.pinnedMessagesCount = args.pinned_messages_count ?? 0;
if (args.archive_completed || args.archive_failed) {
this.archive = ChatChannelArchive.create(args);
@@ -161,6 +165,10 @@ export default class ChatChannel {
return this.meta?.can_remove_members;
}
+ get canManagePins() {
+ return this.meta?.can_manage_pins;
+ }
+
get escapedTitle() {
return escapeExpression(this.title);
}
@@ -227,6 +235,14 @@ export default class ChatChannel {
);
}
+ get hasPinnedMessages() {
+ return this.pinnedMessagesCount > 0;
+ }
+
+ get hasUnseenPins() {
+ return this.currentUserMembership?.hasUnseenPins ?? false;
+ }
+
async stageMessage(message) {
message.id = guid();
message.staged = true;
diff --git a/plugins/chat/assets/javascripts/discourse/models/chat-message.js b/plugins/chat/assets/javascripts/discourse/models/chat-message.js
index d656ebdc0e1..008359ba5e7 100644
--- a/plugins/chat/assets/javascripts/discourse/models/chat-message.js
+++ b/plugins/chat/assets/javascripts/discourse/models/chat-message.js
@@ -53,6 +53,7 @@ export default class ChatMessage {
@tracked manager;
@tracked deletedById;
@tracked streaming;
+ @tracked pinned;
@trackedArray reactions;
@tracked _deletedAt;
@@ -103,6 +104,8 @@ export default class ChatMessage {
if (args.thread) {
this.thread = args.thread;
}
+
+ this.pinned = args.pinned ?? false;
}
get url() {
diff --git a/plugins/chat/assets/javascripts/discourse/models/user-chat-channel-membership.js b/plugins/chat/assets/javascripts/discourse/models/user-chat-channel-membership.js
index 3117199668d..c3021fc6998 100644
--- a/plugins/chat/assets/javascripts/discourse/models/user-chat-channel-membership.js
+++ b/plugins/chat/assets/javascripts/discourse/models/user-chat-channel-membership.js
@@ -11,7 +11,9 @@ export default class UserChatChannelMembership {
@tracked notificationLevel;
@tracked lastReadMessageId;
@tracked lastViewedAt;
+ @tracked lastViewedPinsAt;
@tracked starred;
+ @tracked hasUnseenPins;
@tracked user;
constructor(args = {}) {
@@ -20,7 +22,11 @@ export default class UserChatChannelMembership {
this.notificationLevel = args.notification_level;
this.lastReadMessageId = args.last_read_message_id;
this.lastViewedAt = new Date(args.last_viewed_at);
+ this.lastViewedPinsAt = args.last_viewed_pins_at
+ ? new Date(args.last_viewed_pins_at)
+ : null;
this.starred = args.starred;
+ this.hasUnseenPins = args.has_unseen_pins;
this.user = this.#initUserModel(args.user);
}
diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat/channel/pins.js b/plugins/chat/assets/javascripts/discourse/routes/chat/channel/pins.js
new file mode 100644
index 00000000000..46905b8e915
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/routes/chat/channel/pins.js
@@ -0,0 +1,26 @@
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class ChatChannelPins extends DiscourseRoute {
+ @service chatStateManager;
+ @service chat;
+ @service chatApi;
+
+ async model() {
+ const channel = this.modelFor("chat.channel");
+ const pinnedMessages = await this.chatApi.pinnedMessages(channel);
+ return { channel, pinnedMessages };
+ }
+
+ @action
+ activate() {
+ this.chat.activeMessage = null;
+ this.chatStateManager.openSidePanel();
+ }
+
+ @action
+ deactivate() {
+ this.chatStateManager.closeSidePanel();
+ }
+}
diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-api.js b/plugins/chat/assets/javascripts/discourse/services/chat-api.js
index 4c285b2d951..618b3631264 100644
--- a/plugins/chat/assets/javascripts/discourse/services/chat-api.js
+++ b/plugins/chat/assets/javascripts/discourse/services/chat-api.js
@@ -1,5 +1,6 @@
import Service, { service } from "@ember/service";
import { ajax } from "discourse/lib/ajax";
+import ChatMessage from "discourse/plugins/chat/discourse/models/chat-message";
import UserChatChannelMembership from "discourse/plugins/chat/discourse/models/user-chat-channel-membership";
import Collection from "../lib/collection";
@@ -628,6 +629,40 @@ export default class ChatApi extends Service {
return this.#deleteRequest(`/channels/${channelId}/memberships/${userId}`);
}
+ pinMessage(channelId, messageId) {
+ return this.#postRequest(
+ `/channels/${channelId}/messages/${messageId}/pin`
+ );
+ }
+
+ unpinMessage(channelId, messageId) {
+ return this.#deleteRequest(
+ `/channels/${channelId}/messages/${messageId}/pin`
+ );
+ }
+
+ async pinnedMessages(channel) {
+ const response = await this.#getRequest(`/channels/${channel.id}/pins`);
+ const pinnedMessages = response.pinned_messages.map((pin) => {
+ const message = ChatMessage.create(channel, pin.message);
+ message.channel = channel;
+ return { ...pin, message };
+ });
+
+ if (response.membership && channel.currentUserMembership) {
+ channel.currentUserMembership.hasUnseenPins =
+ response.membership.has_unseen_pins;
+ channel.currentUserMembership.lastViewedPinsAt =
+ response.membership.last_viewed_pins_at;
+ }
+
+ return pinnedMessages;
+ }
+
+ markPinsAsRead(channelId) {
+ return this.#putRequest(`/channels/${channelId}/pins/read`);
+ }
+
get #basePath() {
return "/chat/api";
}
diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-drawer-router.js b/plugins/chat/assets/javascripts/discourse/services/chat-drawer-router.js
index dd74ce0ed55..8a95bfbeb38 100644
--- a/plugins/chat/assets/javascripts/discourse/services/chat-drawer-router.js
+++ b/plugins/chat/assets/javascripts/discourse/services/chat-drawer-router.js
@@ -5,6 +5,7 @@ import ChatDrawerRoutesBrowse from "discourse/plugins/chat/discourse/components/
import ChatDrawerRoutesChannel from "discourse/plugins/chat/discourse/components/chat/drawer-routes/channel";
import ChatDrawerRoutesChannelInfoMembers from "discourse/plugins/chat/discourse/components/chat/drawer-routes/channel-info-members";
import ChatDrawerRoutesChannelInfoSettings from "discourse/plugins/chat/discourse/components/chat/drawer-routes/channel-info-settings";
+import ChatDrawerRoutesChannelPins from "discourse/plugins/chat/discourse/components/chat/drawer-routes/channel-pins";
import ChatDrawerRoutesChannelThread from "discourse/plugins/chat/discourse/components/chat/drawer-routes/channel-thread";
import ChatDrawerRoutesChannelThreads from "discourse/plugins/chat/discourse/components/chat/drawer-routes/channel-threads";
import ChatDrawerRoutesChannels from "discourse/plugins/chat/discourse/components/chat/drawer-routes/channels";
@@ -155,6 +156,29 @@ const ROUTES = {
this.chat.activeChannel = null;
},
},
+ "chat.channel.pins": {
+ name: ChatDrawerRoutesChannelPins,
+
+ extractParams: (route) => {
+ return {
+ channelId: route.parent.params.channelId,
+ };
+ },
+
+ async model(params) {
+ const channel = await this.chatChannelsManager.find(params.channelId);
+ const pinnedMessages = await this.chatApi.pinnedMessages(channel);
+ return { channel, pinnedMessages };
+ },
+
+ afterModel(model) {
+ this.chat.activeChannel = model.channel;
+ },
+
+ deactivate() {
+ this.chat.activeChannel = null;
+ },
+ },
"chat.direct-messages": {
name: ChatDrawerRoutesDirectMessages,
},
@@ -266,6 +290,8 @@ export default class ChatDrawerRouter extends Service {
@service router;
@service chatHistory;
@service chat;
+ // eslint-disable-next-line discourse/no-unused-services -- used in ROUTES model functions
+ @service chatApi;
@service siteSettings;
@service chatChannelsManager;
diff --git a/plugins/chat/assets/javascripts/discourse/templates/chat/channel/pins.gjs b/plugins/chat/assets/javascripts/discourse/templates/chat/channel/pins.gjs
new file mode 100644
index 00000000000..c6025c22458
--- /dev/null
+++ b/plugins/chat/assets/javascripts/discourse/templates/chat/channel/pins.gjs
@@ -0,0 +1,8 @@
+import ChannelPins from "discourse/plugins/chat/discourse/components/chat/routes/channel-pins";
+
+export default <template>
+ <ChannelPins
+ @channel={{@model.channel}}
+ @pinnedMessages={{@model.pinnedMessages}}
+ />
+</template>
diff --git a/plugins/chat/assets/stylesheets/common/base-common.scss b/plugins/chat/assets/stylesheets/common/base-common.scss
index 40535ef0858..9833778bad5 100644
--- a/plugins/chat/assets/stylesheets/common/base-common.scss
+++ b/plugins/chat/assets/stylesheets/common/base-common.scss
@@ -147,11 +147,11 @@ html.ios-device.has-full-page-chat body {
margin: 0;
}
}
+}
- .chat-time {
- color: var(--primary-high);
- font-size: var(--font-down-2);
- }
+.chat-time {
+ color: var(--primary-high);
+ font-size: var(--font-down-2);
}
.chat-emoji-avatar {
diff --git a/plugins/chat/assets/stylesheets/common/chat-message.scss b/plugins/chat/assets/stylesheets/common/chat-message.scss
index 4a31602c0c2..8c5cf09f880 100644
--- a/plugins/chat/assets/stylesheets/common/chat-message.scss
+++ b/plugins/chat/assets/stylesheets/common/chat-message.scss
@@ -264,4 +264,13 @@
.chat-message-reaction-list .chat-message-react-btn {
visibility: hidden;
}
+
+ &.-not-interactive {
+ .chat-message-content a,
+ .chat-message-reaction-list,
+ .chat-message-thread-indicator,
+ .chat-message-info__date {
+ pointer-events: none;
+ }
+ }
}
diff --git a/plugins/chat/assets/stylesheets/common/chat-pinned-messages.scss b/plugins/chat/assets/stylesheets/common/chat-pinned-messages.scss
new file mode 100644
index 00000000000..0258334b6b2
--- /dev/null
+++ b/plugins/chat/assets/stylesheets/common/chat-pinned-messages.scss
@@ -0,0 +1,103 @@
+.c-navbar__title .d-icon-thumbtack,
+.chat-message-actions .d-icon-thumbtack {
+ transform: rotate(45deg);
+}
+
+.chat-pinned-messages-list {
+ display: flex;
+ flex-direction: column;
+ position: relative;
+ overflow-y: scroll;
+ box-sizing: border-box;
+ overscroll-behavior: contain;
+
+ @include chat-scrollbar;
+
+ &.chat-messages-scroller {
+ @include chat-height(
+ calc(var(--chat-header-offset) + env(safe-area-inset-bottom))
+ );
+ }
+}
+
+.chat-pinned-messages-list__empty {
+ padding: 2rem;
+ text-align: center;
+ color: var(--primary-medium);
+}
+
+.chat-pinned-message {
+ display: block;
+ margin-inline: 1rem 0.75rem;
+ border-bottom: 1px solid var(--content-border-color);
+
+ &,
+ &:hover,
+ &:visited,
+ &:active {
+ color: var(--primary);
+ text-decoration: none;
+ }
+
+ .chat-message-container {
+ background-color: transparent;
+ }
+
+ .chat-user-avatar {
+ width: auto;
+ }
+
+ .chat-message-container:not(.-user-info-hidden) .chat-message {
+ padding-inline: 0;
+ }
+
+ .no-touch &:hover,
+ .touch &:active {
+ background-color: var(--d-hover);
+ margin-inline: 0;
+ padding-inline: 1rem 0.75rem;
+ }
+
+ &__pinned-by {
+ display: flex;
+ align-items: center;
+ gap: 0.25em;
+ padding: 0.5em 0 0;
+ color: var(--primary-medium);
+ font-size: var(--font-down-1);
+ }
+
+ &__pinned-by-icon {
+ color: var(--tertiary);
+ transform: rotate(45deg);
+ }
+}
+
+.chat-message-info__pinned {
+ color: var(--primary-medium);
+ margin-left: 0.25rem;
+
+ .d-icon {
+ font-size: var(--font-down-2);
+ transform: rotate(45deg);
+ }
+}
+
+.c-navbar__pinned-messages-btn {
+ position: relative;
+
+ .d-icon {
+ transform: rotate(45deg);
+ }
+
+ &__unread-indicator {
+ position: absolute;
+ top: 5px;
+ right: 5px;
+ width: 8px;
+ height: 8px;
+ background: var(--tertiary);
+ border-radius: 50%;
+ border: 2px solid var(--secondary);
+ }
+}
diff --git a/plugins/chat/assets/stylesheets/common/index.scss b/plugins/chat/assets/stylesheets/common/index.scss
index b479caac3e0..d3ada729e03 100644
--- a/plugins/chat/assets/stylesheets/common/index.scss
+++ b/plugins/chat/assets/stylesheets/common/index.scss
@@ -75,3 +75,4 @@
@import "chat-channel-filter-bar";
@import "chat-search";
@import "edit-category-chat";
+@import "chat-pinned-messages";
diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.yml
index 47f254f5f44..e2832762d10 100644
--- a/plugins/chat/config/locales/client.en.yml
+++ b/plugins/chat/config/locales/client.en.yml
@@ -65,6 +65,15 @@ en:
starred: "Starred"
starred_channels: "Starred channels"
starred_channels_empty: "You haven't starred any channels yet. Star channels to see them here for quick access."
+ pinned_messages:
+ title: "Pinned messages"
+ close: "Close pinned messages"
+ pinned_by_you: "Pinned by you"
+ pinned_by_user: "Pinned by %{username}"
+ no_pinned_messages: "No pinned messages in this channel."
+ pin_message: "Pin message"
+ unpin_message: "Unpin message"
+ pinned: "Pinned"
browse_all_channels: "Browse all channels"
see_in: "See in"
open_channel_menu: "Open channel menu"
diff --git a/plugins/chat/config/locales/server.en.yml b/plugins/chat/config/locales/server.en.yml
index e4caff7607e..0c32054c884 100644
--- a/plugins/chat/config/locales/server.en.yml
+++ b/plugins/chat/config/locales/server.en.yml
@@ -2,6 +2,7 @@ en:
site_settings:
chat_separate_sidebar_mode: "Show separate sidebar modes for forum and chat."
chat_enabled: "Enable chat."
+ chat_pinned_messages: "Enable pinned messages in chat channels."
enable_public_channels: "Enable public channels based on categories."
chat_allowed_groups: "Users in these groups can chat. Note that admins and moderators can always access chat."
chat_channel_retention_days: "Chat messages in regular channels will be retained for this many days. Set to '0' to retain messages forever."
@@ -17,6 +18,7 @@ en:
chat_archive_destination_topic_status: "The status that the destination topic should be once a channel archive is completed. This only applies when the destination topic is a new topic, not an existing one."
direct_message_enabled_groups: "Allow users within these groups to create user-to-user Personal Chats. Note: staff can always create Personal Chats, and users will be able to reply to Personal Chats initiated by users who have permission to create them."
chat_message_flag_allowed_groups: "Users in these groups are allowed to flag chat messages. Note that admins and moderators can always flag chat messages."
+ chat_pinning_messages_allowed_groups: "Users in these groups are allowed to pin chat messages in channels that they can access. Note that admins and moderators can always pin chat messages. Any member of a group chat or DM can pin messages there."
max_mentions_per_chat_message: "Maximum number of @name notifications a user can use in a chat message."
chat_max_direct_message_users: "Users cannot add more than this number of other users when creating a new direct message. Set to 0 to only allow messages to oneself. Staff are exempt from this setting."
chat_allow_archiving_channels: "Allow staff to archive messages to a topic when closing a channel."
@@ -100,6 +102,9 @@ en:
thread_invalid_for_channel: "Thread is not part of the provided channel."
thread_does_not_match_parent: "Thread does not match parent message."
invalid_direct_message: "You are not allowed to create this direct message."
+ pin_limit_reached: "This channel has reached the maximum number of pinned messages (%{limit})."
+ message_already_pinned: "This message is already pinned."
+ message_not_pinned: "This message is not pinned."
reviewables:
message_already_handled: "Thanks, but we've already reviewed this message and determined it does not need to be flagged again."
actions:
diff --git a/plugins/chat/config/routes.rb b/plugins/chat/config/routes.rb
index e507873c17c..92bffa4d1da 100644
--- a/plugins/chat/config/routes.rb
+++ b/plugins/chat/config/routes.rb
@@ -36,6 +36,11 @@ Chat::Engine.routes.draw do
put "/channels/:channel_id/notifications-settings/me" =>
"channels_current_user_notifications_settings#update"
+ get "/channels/:channel_id/pins" => "channel_pins#index"
+ put "/channels/:channel_id/pins/read" => "channel_pins#mark_read"
+ post "/channels/:channel_id/messages/:message_id/pin" => "channel_pins#create"
+ delete "/channels/:channel_id/messages/:message_id/pin" => "channel_pins#destroy"
+
# Category chatables controller hints. Only used by staff members, we don't want to leak category permissions.
get "/category-chatables/:id/permissions" => "category_chatables#permissions",
:format => :json,
diff --git a/plugins/chat/config/settings.yml b/plugins/chat/config/settings.yml
index 6600a050f3a..cae36e38d2f 100644
--- a/plugins/chat/config/settings.yml
+++ b/plugins/chat/config/settings.yml
@@ -2,6 +2,13 @@ chat:
chat_enabled:
default: true
client: true
+ chat_pinned_messages:
+ default: false
+ hidden: true
+ client: true
+ upcoming_change:
+ status: "experimental"
+ impact: "feature,all_members"
enable_public_channels:
default: true
client: true
@@ -102,6 +109,14 @@ chat:
refresh: true
validator: "Chat::DirectMessageEnabledGroupsValidator"
area: "group_permissions"
+ chat_pinning_messages_allowed_groups:
+ default: "1|2" # @admins, @moderators
+ mandatory_values: "1|2" # @admins, @moderators
+ type: group_list
+ list_type: compact
+ allow_any: false
+ refresh: true
+ area: "group_permissions"
chat_message_flag_allowed_groups:
default: "1|2|11" # @admins, @moderators, @trust_level_1
mandatory_values: "1|2" # @admins, @moderators
diff --git a/plugins/chat/db/migrate/20260122134202_create_chat_pinned_messages.rb b/plugins/chat/db/migrate/20260122134202_create_chat_pinned_messages.rb
new file mode 100644
index 00000000000..8c030dad4ea
--- /dev/null
+++ b/plugins/chat/db/migrate/20260122134202_create_chat_pinned_messages.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+class CreateChatPinnedMessages < ActiveRecord::Migration[7.2]
+ def change
+ create_table :chat_pinned_messages do |t|
+ t.bigint :chat_message_id, null: false
+ t.bigint :chat_channel_id, null: false
+ t.bigint :pinned_by_id, null: false
+ t.timestamps
+ end
+
+ add_index :chat_pinned_messages, :chat_message_id, unique: true
+ add_index :chat_pinned_messages,
+ %i[chat_channel_id created_at],
+ order: {
+ created_at: :desc,
+ },
+ name: "idx_chat_pinned_messages_channel_created"
+ end
+end
diff --git a/plugins/chat/db/migrate/20260122214226_add_last_viewed_pins_at_to_user_chat_channel_memberships.rb b/plugins/chat/db/migrate/20260122214226_add_last_viewed_pins_at_to_user_chat_channel_memberships.rb
new file mode 100644
index 00000000000..1bb7105060e
--- /dev/null
+++ b/plugins/chat/db/migrate/20260122214226_add_last_viewed_pins_at_to_user_chat_channel_memberships.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+class AddLastViewedPinsAtToUserChatChannelMemberships < ActiveRecord::Migration[7.2]
+ def change
+ add_column :user_chat_channel_memberships, :last_viewed_pins_at, :datetime
+ end
+end
diff --git a/plugins/chat/lib/chat/channel_fetcher.rb b/plugins/chat/lib/chat/channel_fetcher.rb
index fecdf75dba8..75c64bb8306 100644
--- a/plugins/chat/lib/chat/channel_fetcher.rb
+++ b/plugins/chat/lib/chat/channel_fetcher.rb
@@ -225,6 +225,7 @@ module Chat
options.merge(include_archives: true, filter_on_category_name: true),
)
+ channels = channels.includes(:pinned_messages) if SiteSetting.chat_pinned_messages
channels = channels.to_a
preload_custom_fields_for(channels)
channels
@@ -267,6 +268,7 @@ module Chat
)
query = query.includes(chatable: [{ users: :user_status }]) if SiteSetting.enable_user_status
+ query = query.includes(:pinned_messages) if SiteSetting.chat_pinned_messages
if options[:filter]
filter_term = options[:filter].downcase
diff --git a/plugins/chat/lib/chat/guardian_extensions.rb b/plugins/chat/lib/chat/guardian_extensions.rb
index 8754bb01cde..fd8dda4d28d 100644
--- a/plugins/chat/lib/chat/guardian_extensions.rb
+++ b/plugins/chat/lib/chat/guardian_extensions.rb
@@ -274,5 +274,20 @@ module Chat
def can_remove_members?(channel)
is_admin? && (channel.category_channel? || channel.direct_message_group?)
end
+
+ def can_manage_chat_channel_pins?(channel)
+ return false unless can_chat?
+ return false unless can_preview_chat_channel?(channel)
+
+ if channel.direct_message_channel?
+ true
+ else
+ @user.in_any_groups?(SiteSetting.chat_pinning_messages_allowed_groups_map)
+ end
+ end
+
+ def can_manage_chat_message_pin?(message)
+ can_manage_chat_channel_pins?(message.chat_channel)
+ end
end
end
diff --git a/plugins/chat/spec/fabricators/chat_pinned_message_fabricator.rb b/plugins/chat/spec/fabricators/chat_pinned_message_fabricator.rb
new file mode 100644
index 00000000000..7fea7b90f1d
--- /dev/null
+++ b/plugins/chat/spec/fabricators/chat_pinned_message_fabricator.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+Fabricator(:chat_pinned_message, class_name: "Chat::PinnedMessage") do
+ chat_message { Fabricate(:chat_message) }
+ chat_channel { |attrs| attrs[:chat_message].chat_channel }
+ user { Fabricate(:user) }
+end
diff --git a/plugins/chat/spec/jobs/scheduled/delete_old_chat_messages_spec.rb b/plugins/chat/spec/jobs/scheduled/delete_old_chat_messages_spec.rb
index e460a538db9..4d7c40effdb 100644
--- a/plugins/chat/spec/jobs/scheduled/delete_old_chat_messages_spec.rb
+++ b/plugins/chat/spec/jobs/scheduled/delete_old_chat_messages_spec.rb
@@ -90,6 +90,26 @@ describe Jobs::Chat::DeleteOldMessages do
end
describe "public channels" do
+ context "when a message is pinned" do
+ fab!(:old_pinned_message) do
+ Fabricate(:chat_message, chat_channel: public_channel, created_at: base_date - 400.days)
+ end
+ fab!(:pin) do
+ Fabricate(
+ :chat_pinned_message,
+ chat_message: old_pinned_message,
+ chat_channel: public_channel,
+ )
+ end
+
+ it "does not delete the pinned message" do
+ SiteSetting.chat_channel_retention_days = 20
+ described_class.new.execute
+
+ expect(Chat::Message.exists?(old_pinned_message.id)).to eq(true)
+ end
+ end
+
it "deletes public messages correctly" do
SiteSetting.chat_channel_retention_days = 20
described_class.new.execute
@@ -123,6 +143,26 @@ describe Jobs::Chat::DeleteOldMessages do
end
describe "dm channels" do
+ context "when a message is pinned" do
+ fab!(:old_pinned_dm_message) do
+ Fabricate(:chat_message, chat_channel: dm_channel, created_at: base_date - 400.days)
+ end
+ fab!(:dm_pin) do
+ Fabricate(
+ :chat_pinned_message,
+ chat_message: old_pinned_dm_message,
+ chat_channel: dm_channel,
+ )
+ end
+
+ it "does not delete the pinned message" do
+ SiteSetting.chat_dm_retention_days = 20
+ described_class.new.execute
+
+ expect(Chat::Message.exists?(old_pinned_dm_message.id)).to eq(true)
+ end
+ end
+
it "deletes public messages correctly" do
SiteSetting.chat_dm_retention_days = 20
described_class.new.execute
diff --git a/plugins/chat/spec/lib/chat/guardian_extensions_spec.rb b/plugins/chat/spec/lib/chat/guardian_extensions_spec.rb
index 990f5e71a12..21aff8ca1a7 100644
--- a/plugins/chat/spec/lib/chat/guardian_extensions_spec.rb
+++ b/plugins/chat/spec/lib/chat/guardian_extensions_spec.rb
@@ -926,4 +926,81 @@ RSpec.describe Chat::GuardianExtensions do
end
end
end
+
+ describe "#can_manage_chat_message_pin?" do
+ fab!(:pin_channel, :chat_channel)
+ fab!(:message) { Fabricate(:chat_message, chat_channel: pin_channel) }
+ fab!(:pin_dm_channel) { Fabricate(:direct_message_channel, users: [user, Fabricate(:user)]) }
+ fab!(:dm_message) { Fabricate(:chat_message, chat_channel: pin_dm_channel) }
+
+ context "when user cannot chat" do
+ before { SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:admins] }
+
+ it "returns false" do
+ expect(guardian.can_manage_chat_message_pin?(message)).to eq(false)
+ end
+ end
+
+ context "for category channels" do
+ context "when user is not staff" do
+ it "returns false" do
+ expect(guardian.can_manage_chat_message_pin?(message)).to eq(false)
+ end
+ end
+
+ context "when user is staff" do
+ it "returns true" do
+ expect(staff_guardian.can_manage_chat_message_pin?(message)).to eq(true)
+ end
+ end
+
+ context "when user is in pinning group but cannot access the channel" do
+ fab!(:private_group, :group)
+ fab!(:private_category) { Fabricate(:private_category, group: private_group) }
+ fab!(:private_pin_channel) { Fabricate(:category_channel, chatable: private_category) }
+ fab!(:private_message) { Fabricate(:chat_message, chat_channel: private_pin_channel) }
+
+ before do
+ SiteSetting.chat_pinning_messages_allowed_groups = "#{Group::AUTO_GROUPS[:trust_level_0]}"
+ end
+
+ it "returns false" do
+ expect(guardian.can_manage_chat_message_pin?(private_message)).to eq(false)
+ end
+ end
+
+ context "when user is in pinning group and can access the channel" do
+ fab!(:accessible_group, :group)
+ fab!(:accessible_category) { Fabricate(:private_category, group: accessible_group) }
+ fab!(:accessible_channel) { Fabricate(:category_channel, chatable: accessible_category) }
+ fab!(:accessible_message) { Fabricate(:chat_message, chat_channel: accessible_channel) }
+
+ before do
+ accessible_group.add(user)
+ SiteSetting.chat_pinning_messages_allowed_groups = "#{Group::AUTO_GROUPS[:trust_level_0]}"
+ end
+
+ it "returns true" do
+ expect(guardian.can_manage_chat_message_pin?(accessible_message)).to eq(true)
+ end
+ end
+ end
+
+ context "for direct message channels" do
+ context "when user is a member" do
+ it "returns true" do
+ expect(guardian.can_manage_chat_message_pin?(dm_message)).to eq(true)
+ end
+ end
+
+ context "when user is not a member" do
+ fab!(:other_user) { Fabricate(:user, group_ids: [chatters.id], refresh_auto_groups: true) }
+ let(:other_guardian) { Guardian.new(other_user) }
+
+ it "returns false" do
+ expect(other_guardian.can_manage_chat_message_pin?(dm_message)).to eq(false)
+ end
+ end
+ end
+ end
end
diff --git a/plugins/chat/spec/models/chat/pinned_message_spec.rb b/plugins/chat/spec/models/chat/pinned_message_spec.rb
new file mode 100644
index 00000000000..2e915c6c7d8
--- /dev/null
+++ b/plugins/chat/spec/models/chat/pinned_message_spec.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+RSpec.describe Chat::PinnedMessage do
+ describe "associations" do
+ it { is_expected.to belong_to(:chat_message).class_name("Chat::Message") }
+ it { is_expected.to belong_to(:chat_channel).class_name("Chat::Channel") }
+ it { is_expected.to belong_to(:user).with_foreign_key(:pinned_by_id) }
+ end
+
+ describe "validations" do
+ subject { Fabricate(:chat_pinned_message) }
+
+ it { is_expected.to validate_uniqueness_of(:chat_message_id) }
+ end
+
+ describe ".for_channel" do
+ fab!(:channel, :chat_channel)
+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: channel) }
+ fab!(:message_2) { Fabricate(:chat_message, chat_channel: channel) }
+ fab!(:other_channel, :chat_channel)
+ fab!(:other_message) { Fabricate(:chat_message, chat_channel: other_channel) }
+
+ before do
+ Fabricate(:chat_pinned_message, chat_message: message_1, chat_channel: channel)
+ Fabricate(:chat_pinned_message, chat_message: message_2, chat_channel: channel)
+ Fabricate(:chat_pinned_message, chat_message: other_message, chat_channel: other_channel)
+ end
+
+ it "returns pins for the specified channel ordered by created_at desc" do
+ pins = described_class.for_channel(channel)
+ expect(pins.count).to eq(2)
+ expect(pins.map(&:chat_message_id)).to contain_exactly(message_1.id, message_2.id)
+ end
+ end
+end
diff --git a/plugins/chat/spec/models/chat/user_chat_channel_membership_spec.rb b/plugins/chat/spec/models/chat/user_chat_channel_membership_spec.rb
new file mode 100644
index 00000000000..feb3a1a12ed
--- /dev/null
+++ b/plugins/chat/spec/models/chat/user_chat_channel_membership_spec.rb
@@ -0,0 +1,69 @@
+# frozen_string_literal: true
+
+RSpec.describe Chat::UserChatChannelMembership do
+ describe "#has_unseen_pins?" do
+ fab!(:channel, :chat_channel)
+ fab!(:user)
+ fab!(:membership) do
+ Fabricate(:user_chat_channel_membership, chat_channel: channel, user: user)
+ end
+
+ context "when channel has no pins" do
+ it "returns false" do
+ expect(membership.has_unseen_pins?).to eq(false)
+ end
+ end
+
+ context "when user has never viewed pins" do
+ fab!(:message) { Fabricate(:chat_message, chat_channel: channel) }
+ fab!(:pin) { Fabricate(:chat_pinned_message, chat_channel: channel, chat_message: message) }
+
+ it "returns true" do
+ expect(membership.has_unseen_pins?).to eq(true)
+ end
+ end
+
+ context "when user viewed pins before new pin was added" do
+ fab!(:message) { Fabricate(:chat_message, chat_channel: channel) }
+
+ before do
+ membership.update!(last_viewed_pins_at: 1.hour.ago)
+ Fabricate(:chat_pinned_message, chat_channel: channel, chat_message: message)
+ end
+
+ it "returns true" do
+ expect(membership.has_unseen_pins?).to eq(true)
+ end
+ end
+
+ context "when the only unseen pin was created by the user" do
+ fab!(:message) { Fabricate(:chat_message, chat_channel: channel) }
+
+ before do
+ Fabricate(:chat_pinned_message, chat_channel: channel, chat_message: message, user: user)
+ end
+
+ it "returns false" do
+ expect(membership.has_unseen_pins?).to eq(false)
+ end
+ end
+
+ context "when user viewed pins after all pins were created" do
+ fab!(:message) { Fabricate(:chat_message, chat_channel: channel, created_at: 2.hours.ago) }
+
+ before do
+ Fabricate(
+ :chat_pinned_message,
+ chat_channel: channel,
+ chat_message: message,
+ created_at: 2.hours.ago,
+ )
+ membership.update!(last_viewed_pins_at: 1.hour.ago)
+ end
+
+ it "returns false" do
+ expect(membership.has_unseen_pins?).to eq(false)
+ end
+ end
+ end
+end
diff --git a/plugins/chat/spec/requests/chat/api/channel_pins_controller_spec.rb b/plugins/chat/spec/requests/chat/api/channel_pins_controller_spec.rb
new file mode 100644
index 00000000000..43850540f56
--- /dev/null
+++ b/plugins/chat/spec/requests/chat/api/channel_pins_controller_spec.rb
@@ -0,0 +1,112 @@
+# frozen_string_literal: true
+
+RSpec.describe Chat::Api::ChannelPinsController do
+ fab!(:admin)
+ fab!(:user)
+ fab!(:channel, :chat_channel)
+ fab!(:message) { Fabricate(:chat_message, chat_channel: channel) }
+
+ before do
+ SiteSetting.chat_enabled = true
+ SiteSetting.chat_pinned_messages = true
+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]
+ sign_in(admin)
+ end
+
+ describe "#index" do
+ fab!(:pin) { Fabricate(:chat_pinned_message, chat_message: message, chat_channel: channel) }
+
+ it "returns pinned messages for the channel" do
+ Fabricate(:user_chat_channel_membership, chat_channel: channel, user: admin)
+ get "/chat/api/channels/#{channel.id}/pins"
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["pinned_messages"].length).to eq(1)
+ expect(response.parsed_body["pinned_messages"][0]["chat_message_id"]).to eq(message.id)
+ end
+
+ it "does not mark pins as read" do
+ membership = Fabricate(:user_chat_channel_membership, chat_channel: channel, user: admin)
+
+ get "/chat/api/channels/#{channel.id}/pins"
+
+ expect(membership.reload.last_viewed_pins_at).to be_nil
+ end
+
+ context "when user cannot access channel" do
+ before { sign_in(user) }
+
+ it "returns 403" do
+ channel.update!(chatable: Fabricate(:private_category, group: Fabricate(:group)))
+ get "/chat/api/channels/#{channel.id}/pins"
+
+ expect(response.status).to eq(403)
+ end
+ end
+ end
+
+ describe "#mark_read" do
+ it "marks pins as read for the current user" do
+ membership = Fabricate(:user_chat_channel_membership, chat_channel: channel, user: admin)
+ expect(membership.last_viewed_pins_at).to be_nil
+
+ freeze_time do
+ put "/chat/api/channels/#{channel.id}/pins/read"
+
+ expect(response.status).to eq(200)
+ expect(membership.reload.last_viewed_pins_at).to eq_time(Time.zone.now)
+ end
+ end
+
+ context "when user cannot access channel" do
+ before { sign_in(user) }
+
+ it "returns 404" do
+ channel.update!(chatable: Fabricate(:private_category, group: Fabricate(:group)))
+ put "/chat/api/channels/#{channel.id}/pins/read"
+
+ expect(response.status).to eq(404)
+ end
+ end
+ end
+
+ describe "#create" do
+ it "pins a message" do
+ post "/chat/api/channels/#{channel.id}/messages/#{message.id}/pin"
+
+ expect(response.status).to eq(200)
+ expect(Chat::PinnedMessage.exists?(chat_message_id: message.id)).to eq(true)
+ end
+
+ context "when user is not staff" do
+ before { sign_in(user) }
+
+ it "returns 403" do
+ post "/chat/api/channels/#{channel.id}/messages/#{message.id}/pin"
+
+ expect(response.status).to eq(403)
+ end
+ end
+ end
+
+ describe "#destroy" do
+ fab!(:pin) { Fabricate(:chat_pinned_message, chat_message: message, chat_channel: channel) }
+
+ it "unpins a message" do
+ delete "/chat/api/channels/#{channel.id}/messages/#{message.id}/pin"
+
+ expect(response.status).to eq(200)
+ expect(Chat::PinnedMessage.exists?(chat_message_id: message.id)).to eq(false)
+ end
+
+ context "when user is not staff" do
+ before { sign_in(user) }
+
+ it "returns 403" do
+ delete "/chat/api/channels/#{channel.id}/messages/#{message.id}/pin"
+
+ expect(response.status).to eq(403)
+ end
+ end
+ end
+end
diff --git a/plugins/chat/spec/requests/chat/api/channels_current_user_notifications_settings_controller_spec.rb b/plugins/chat/spec/requests/chat/api/channels_current_user_notifications_settings_controller_spec.rb
index 729778c1509..5ae6546d134 100644
--- a/plugins/chat/spec/requests/chat/api/channels_current_user_notifications_settings_controller_spec.rb
+++ b/plugins/chat/spec/requests/chat/api/channels_current_user_notifications_settings_controller_spec.rb
@@ -6,6 +6,7 @@ RSpec.describe Chat::Api::ChannelsCurrentUserNotificationsSettingsController do
before do
SiteSetting.chat_enabled = true
SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]
+ SiteSetting.chat_pinned_messages = true
end
describe "#update" do
diff --git a/plugins/chat/spec/services/chat/list_channel_pins_spec.rb b/plugins/chat/spec/services/chat/list_channel_pins_spec.rb
new file mode 100644
index 00000000000..86d796678ed
--- /dev/null
+++ b/plugins/chat/spec/services/chat/list_channel_pins_spec.rb
@@ -0,0 +1,74 @@
+# frozen_string_literal: true
+
+RSpec.describe Chat::ListChannelPins do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:channel_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:chatters, :group)
+ fab!(:user) { Fabricate(:user, group_ids: [chatters.id]) }
+ fab!(:channel, :chat_channel)
+ fab!(:membership) do
+ Fabricate(:user_chat_channel_membership, chat_channel: channel, user: user)
+ end
+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: channel) }
+ fab!(:message_2) { Fabricate(:chat_message, chat_channel: channel) }
+ fab!(:pin_1) { Fabricate(:chat_pinned_message, chat_channel: channel, chat_message: message_1) }
+ fab!(:pin_2) { Fabricate(:chat_pinned_message, chat_channel: channel, chat_message: message_2) }
+
+ let(:guardian) { Guardian.new(user) }
+ let(:params) { { channel_id: channel.id } }
+ let(:dependencies) { { guardian: } }
+
+ before { SiteSetting.chat_allowed_groups = chatters }
+
+ context "when params are not valid" do
+ let(:params) { {} }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when channel is not found" do
+ let(:params) { { channel_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:channel) }
+ end
+
+ context "when user cannot access channel" do
+ fab!(:private_category) { Fabricate(:private_category, group: Fabricate(:group)) }
+
+ before { channel.update!(chatable: private_category) }
+
+ it { is_expected.to fail_a_policy(:can_view_channel) }
+ end
+
+ context "when all conditions are met" do
+ it { is_expected.to run_successfully }
+
+ it "returns pinned messages" do
+ expect(result[:pins]).to contain_exactly(pin_1, pin_2)
+ end
+
+ it "returns membership" do
+ expect(result[:membership]).to eq(membership)
+ end
+
+ context "when user has no membership" do
+ before { membership.destroy! }
+
+ it { is_expected.to run_successfully }
+
+ it "returns pinned messages" do
+ expect(result[:pins]).to contain_exactly(pin_1, pin_2)
+ end
+
+ it "returns nil membership" do
+ expect(result[:membership]).to be_nil
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/chat/spec/services/chat/mark_pins_as_read_spec.rb b/plugins/chat/spec/services/chat/mark_pins_as_read_spec.rb
new file mode 100644
index 00000000000..8810acf4d32
--- /dev/null
+++ b/plugins/chat/spec/services/chat/mark_pins_as_read_spec.rb
@@ -0,0 +1,60 @@
+# frozen_string_literal: true
+
+RSpec.describe Chat::MarkPinsAsRead do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:channel_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:chatters, :group)
+ fab!(:user) { Fabricate(:user, group_ids: [chatters.id]) }
+ fab!(:channel, :chat_channel)
+ fab!(:membership) do
+ Fabricate(:user_chat_channel_membership, chat_channel: channel, user: user)
+ end
+
+ let(:guardian) { Guardian.new(user) }
+ let(:params) { { channel_id: channel.id } }
+ let(:dependencies) { { guardian: } }
+
+ before { SiteSetting.chat_allowed_groups = chatters }
+
+ context "when params are not valid" do
+ let(:params) { {} }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when channel is not found" do
+ let(:params) { { channel_id: -1 } }
+
+ it { is_expected.to fail_to_find_a_model(:channel) }
+ end
+
+ context "when membership is not found" do
+ before { membership.destroy! }
+
+ it { is_expected.to fail_to_find_a_model(:membership) }
+ end
+
+ context "when user cannot access channel" do
+ fab!(:private_category) { Fabricate(:private_category, group: Fabricate(:group)) }
+
+ before { channel.update!(chatable: private_category) }
+
+ it { is_expected.to fail_a_policy(:can_access_channel) }
+ end
+
+ context "when all conditions are met" do
+ it { is_expected.to run_successfully }
+
+ it "updates last_viewed_pins_at timestamp" do
+ freeze_time
+ result
+ expect(membership.reload.last_viewed_pins_at).to be_within(1.second).of(Time.zone.now)
+ end
+ end
+ end
+end
diff --git a/plugins/chat/spec/services/chat/pin_message_spec.rb b/plugins/chat/spec/services/chat/pin_message_spec.rb
new file mode 100644
index 00000000000..ea2ebcfa4fa
--- /dev/null
+++ b/plugins/chat/spec/services/chat/pin_message_spec.rb
@@ -0,0 +1,76 @@
+# frozen_string_literal: true
+
+RSpec.describe Chat::PinMessage do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:message_id) }
+ it { is_expected.to validate_presence_of(:channel_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:current_user, :admin)
+ fab!(:channel, :chat_channel)
+ fab!(:message) { Fabricate(:chat_message, chat_channel: channel) }
+
+ let(:guardian) { Guardian.new(current_user) }
+ let(:params) { { message_id: message.id, channel_id: channel.id } }
+ let(:dependencies) { { guardian: } }
+
+ context "when params are not valid" do
+ let(:params) { {} }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when message is not found" do
+ let(:params) { { message_id: -1, channel_id: channel.id } }
+
+ it { is_expected.to fail_to_find_a_model(:message) }
+ end
+
+ context "when user cannot pin" do
+ fab!(:current_user, :user)
+
+ it { is_expected.to fail_a_policy(:can_pin) }
+ end
+
+ context "when pin limit is reached" do
+ before do
+ Chat::PinnedMessage::MAX_PINS_PER_CHANNEL.times do
+ Fabricate(:chat_pinned_message, chat_channel: channel)
+ end
+ end
+
+ it { is_expected.to fail_a_policy(:within_pin_limit) }
+ end
+
+ context "when message is already pinned" do
+ before { Fabricate(:chat_pinned_message, chat_message: message, chat_channel: channel) }
+
+ it { is_expected.to fail_a_policy(:not_already_pinned) }
+ end
+
+ context "when all conditions are met" do
+ it { is_expected.to run_successfully }
+
+ it "creates a pinned message record" do
+ expect { result }.to change { Chat::PinnedMessage.count }.by(1)
+
+ pin = Chat::PinnedMessage.last
+ expect(pin.chat_message_id).to eq(message.id)
+ expect(pin.chat_channel_id).to eq(channel.id)
+ expect(pin.pinned_by_id).to eq(current_user.id)
+ end
+
+ it "publishes a MessageBus event" do
+ messages = MessageBus.track_publish { result }
+ pin_event = messages.find { |m| m.data["type"] == "pin" }
+
+ expect(pin_event).to be_present
+ expect(pin_event.channel).to eq("/chat/#{channel.id}")
+ expect(pin_event.data["chat_message_id"]).to eq(message.id)
+ end
+ end
+ end
+end
diff --git a/plugins/chat/spec/services/chat/trash_message_spec.rb b/plugins/chat/spec/services/chat/trash_message_spec.rb
index 31519765c93..6f179299700 100644
--- a/plugins/chat/spec/services/chat/trash_message_spec.rb
+++ b/plugins/chat/spec/services/chat/trash_message_spec.rb
@@ -201,6 +201,22 @@ RSpec.describe Chat::TrashMessage do
end
end
+ context "when message is pinned" do
+ fab!(:pin) do
+ Fabricate(
+ :chat_pinned_message,
+ chat_message: message,
+ chat_channel: message.chat_channel,
+ )
+ end
+
+ it "destroys the pin" do
+ pin_id = pin.id
+ expect { result }.to change { Chat::PinnedMessage.count }.by(-1)
+ expect(Chat::PinnedMessage.find_by(id: pin_id)).to be_nil
+ end
+ end
+
context "when message is already deleted" do
before { message.trash! }
diff --git a/plugins/chat/spec/services/chat/unpin_message_spec.rb b/plugins/chat/spec/services/chat/unpin_message_spec.rb
new file mode 100644
index 00000000000..173cb470b7d
--- /dev/null
+++ b/plugins/chat/spec/services/chat/unpin_message_spec.rb
@@ -0,0 +1,64 @@
+# frozen_string_literal: true
+
+RSpec.describe Chat::UnpinMessage do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:message_id) }
+ it { is_expected.to validate_presence_of(:channel_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:current_user, :admin)
+ fab!(:channel, :chat_channel)
+ fab!(:message) { Fabricate(:chat_message, chat_channel: channel) }
+ fab!(:pin) { Fabricate(:chat_pinned_message, chat_message: message, chat_channel: channel) }
+
+ let(:guardian) { Guardian.new(current_user) }
+ let(:params) { { message_id: message.id, channel_id: channel.id } }
+ let(:dependencies) { { guardian: } }
+
+ context "when params are not valid" do
+ let(:params) { {} }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when message is not found" do
+ let(:params) { { message_id: -1, channel_id: channel.id } }
+
+ it { is_expected.to fail_to_find_a_model(:message) }
+ end
+
+ context "when user cannot unpin" do
+ fab!(:current_user, :user)
+
+ it { is_expected.to fail_a_policy(:can_unpin) }
+ end
+
+ context "when message is not pinned" do
+ before { pin.destroy! }
+
+ it { is_expected.to fail_to_find_a_model(:pin) }
+ end
+
+ context "when all conditions are met" do
+ it { is_expected.to run_successfully }
+
+ it "destroys the pinned message record" do
+ pin_id = pin.id
+ expect { result }.to change { Chat::PinnedMessage.count }.by(-1)
+ expect(Chat::PinnedMessage.find_by(id: pin_id)).to be_nil
+ end
+
+ it "publishes a MessageBus event" do
+ messages = MessageBus.track_publish { result }
+ unpin_event = messages.find { |m| m.data["type"] == "unpin" }
+
+ expect(unpin_event).to be_present
+ expect(unpin_event.channel).to eq("/chat/#{channel.id}")
+ expect(unpin_event.data["chat_message_id"]).to eq(message.id)
+ end
+ end
+ end
+end
diff --git a/plugins/chat/spec/support/api/schemas/user_chat_channel_membership.json b/plugins/chat/spec/support/api/schemas/user_chat_channel_membership.json
index 48b77132a51..80c99cc9c7a 100644
--- a/plugins/chat/spec/support/api/schemas/user_chat_channel_membership.json
+++ b/plugins/chat/spec/support/api/schemas/user_chat_channel_membership.json
@@ -15,6 +15,7 @@
"notification_level": { "type": "string" },
"following": { "type": "boolean" },
"starred": { "type": "boolean" },
+ "has_unseen_pins": { "type": "boolean" },
"user": {
"type": ["object", "null"],
"required": ["id", "name", "avatar_template", "username"],
@@ -27,6 +28,7 @@
"has_chat_enabled": { "type": "boolean" }
}
},
- "last_viewed_at": { "type": "datetime" }
+ "last_viewed_at": { "type": "datetime" },
+ "last_viewed_pins_at": { "type": ["datetime", "null"] }
}
}
diff --git a/plugins/chat/spec/system/pinned_messages_spec.rb b/plugins/chat/spec/system/pinned_messages_spec.rb
new file mode 100644
index 00000000000..3a9cf112b22
--- /dev/null
+++ b/plugins/chat/spec/system/pinned_messages_spec.rb
@@ -0,0 +1,130 @@
+# frozen_string_literal: true
+
+RSpec.describe "Chat pinned messages", type: :system do
+ fab!(:admin)
+ fab!(:channel, :chat_channel)
+ fab!(:message) { Fabricate(:chat_message, chat_channel: channel, message: "Important message") }
+
+ let(:chat_page) { PageObjects::Pages::Chat.new }
+ let(:channel_page) { PageObjects::Pages::ChatChannel.new }
+
+ before do
+ chat_system_bootstrap
+ SiteSetting.chat_pinned_messages = true
+ channel.add(admin)
+ sign_in(admin)
+ end
+
+ it "allows staff to pin and unpin messages" do
+ chat_page.visit_channel(channel)
+
+ channel_page.messages.find(id: message.id).secondary_action("pin")
+
+ expect(page).to have_css(".chat-message-info__pinned")
+ expect(page).to have_css(".c-navbar__pinned-messages-btn")
+
+ find(".c-navbar__pinned-messages-btn").click
+ expect(page).to have_css(".c-routes.--channel-pins")
+ expect(page).to have_content("Important message")
+
+ find(".c-navbar__close-pins-button").click
+ channel_page.messages.find(id: message.id).secondary_action("unpin")
+
+ expect(page).to have_no_css(".chat-message-info__pinned")
+ end
+
+ it "shows unread indicator for unseen pins" do
+ chat_page.visit_channel(channel)
+
+ # Another user pins the message while admin is viewing
+ pin =
+ Chat::PinnedMessage.create!(
+ chat_message: message,
+ chat_channel: channel,
+ user: Fabricate(:admin),
+ )
+ Chat::Publisher.publish_pin!(channel, message, pin)
+
+ expect(page).to have_css(".c-navbar__pinned-messages-btn__unread-indicator")
+
+ find(".c-navbar__pinned-messages-btn").click
+ expect(page).to have_css(".c-routes.--channel-pins")
+
+ find(".c-navbar__close-pins-button").click
+
+ expect(page).to have_no_css(".c-navbar__pinned-messages-btn__unread-indicator")
+ end
+
+ it "marks pins as read when viewing the panel" do
+ Chat::PinnedMessage.create!(
+ chat_message: message,
+ chat_channel: channel,
+ user: Fabricate(:admin),
+ )
+
+ chat_page.visit_channel(channel)
+ expect(page).to have_css(".c-navbar__pinned-messages-btn__unread-indicator")
+
+ find(".c-navbar__pinned-messages-btn").click
+ expect(page).to have_css(".c-routes.--channel-pins")
+
+ # Reload while panel is open — pins should stay marked as read
+ page.refresh
+
+ chat_page.visit_channel(channel)
+ expect(page).to have_no_css(".c-navbar__pinned-messages-btn__unread-indicator")
+ end
+
+ it "shows unseen pin icon in the panel for pins not yet viewed" do
+ other_user = Fabricate(:admin)
+ Chat::PinnedMessage.create!(chat_message: message, chat_channel: channel, user: other_user)
+
+ chat_page.visit_channel(channel)
+ find(".c-navbar__pinned-messages-btn").click
+ expect(page).to have_css(".c-routes.--channel-pins")
+ expect(page).to have_css(".chat-pinned-message__pinned-by-icon")
+
+ find(".c-navbar__close-pins-button").click
+ find(".c-navbar__pinned-messages-btn").click
+ expect(page).to have_css(".c-routes.--channel-pins")
+ expect(page).to have_no_css(".chat-pinned-message__pinned-by-icon")
+ end
+
+ context "when viewing pinned messages attribution" do
+ it "shows 'Pinned by you' when current user pinned the message" do
+ chat_page.visit_channel(channel)
+ channel_page.messages.find(id: message.id).secondary_action("pin")
+ find(".c-navbar__pinned-messages-btn").click
+
+ expect(page).to have_css(".c-routes.--channel-pins")
+ expect(page).to have_css(
+ ".chat-pinned-message__pinned-by",
+ text: I18n.t("js.chat.pinned_messages.pinned_by_you"),
+ )
+ end
+
+ context "when another user pinned the message" do
+ fab!(:other_user, :user)
+
+ before do
+ channel.add(other_user)
+ Chat::PinnedMessage.create!(
+ chat_message: message,
+ chat_channel: channel,
+ pinned_by_id: other_user.id,
+ )
+ end
+
+ it "shows 'Pinned by [username]'" do
+ chat_page.visit_channel(channel)
+ find(".c-navbar__pinned-messages-btn").click
+
+ expect(page).to have_css(".c-routes.--channel-pins")
+ expect(page).to have_css(
+ ".chat-pinned-message__pinned-by",
+ text: I18n.t("js.chat.pinned_messages.pinned_by_user", username: other_user.username),
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/chat/test/javascripts/components/chat-message-test.gjs b/plugins/chat/test/javascripts/components/chat-message-test.gjs
index cccc3358c5f..c668d10bfa6 100644
--- a/plugins/chat/test/javascripts/components/chat-message-test.gjs
+++ b/plugins/chat/test/javascripts/components/chat-message-test.gjs
@@ -87,6 +87,17 @@ module("Discourse Chat | Component | chat-message", function (hooks) {
.exists("has the correct css class");
});
+ test("Non-interactive message", async function (assert) {
+ this.message = new ChatFabricators(getOwner(this)).message();
+ await render(
+ <template>
+ <ChatMessage @message={{this.message}} @interactive={{false}} />
+ </template>
+ );
+
+ assert.dom(".chat-message-container.-not-interactive").exists();
+ });
+
test("Message with streaming", async function (assert) {
// admin
this.currentUser.admin = true;
diff --git a/public/images/upcoming_changes/chat_pinned_messages.png b/public/images/upcoming_changes/chat_pinned_messages.png
new file mode 100644
index 00000000000..d2ddbba0717
Binary files /dev/null and b/public/images/upcoming_changes/chat_pinned_messages.png differ