A platform for community discussion. Free, open, simple.
FEATURE: allow anonymous users to view public chat channels (#40688)
Penar Musaraj7cfe964e8de2
diff --git a/frontend/discourse/app/components/sidebar/anonymous/sections.gjs b/frontend/discourse/app/components/sidebar/anonymous/sections.gjsindex 910c0480868..b47209683e2 100644--- a/frontend/discourse/app/components/sidebar/anonymous/sections.gjs+++ b/frontend/discourse/app/components/sidebar/anonymous/sections.gjs@@ -1,6 +1,7 @@import Component from "@glimmer/component";import { service } from "@ember/service";import BlockOutlet from "discourse/blocks/block-outlet";+import ApiSections from "../api-sections";import CategoriesSection from "./categories-section";import CustomSections from "./custom-sections";import TagsSection from "./tags-section";@@ -21,6 +22,8 @@ export default class SidebarAnonymousSections extends Component {{{#if this.siteSettings.tagging_enabled}}<TagsSection @collapsable={{@collapsableSections}} />{{/if}}++ <ApiSections @collapsable={{@collapsableSections}} /></div></template>}diff --git a/plugins/chat/app/controllers/chat/api/channel_messages_controller.rb b/plugins/chat/app/controllers/chat/api/channel_messages_controller.rbindex 1ff8586b39c..bac168687c0 100644--- a/plugins/chat/app/controllers/chat/api/channel_messages_controller.rb+++ b/plugins/chat/app/controllers/chat/api/channel_messages_controller.rb@@ -102,4 +102,10 @@ class Chat::Api::ChannelMessagesController < Chat::ApiControllerendendend++ private++ def allow_anonymous_public_chat_access?+ action_name == "index" && anonymous_public_chat_access_enabled?+ endenddiff --git a/plugins/chat/app/controllers/chat/api/channel_thread_messages_controller.rb b/plugins/chat/app/controllers/chat/api/channel_thread_messages_controller.rbindex e67d37c46e3..18cc98e819f 100644--- a/plugins/chat/app/controllers/chat/api/channel_thread_messages_controller.rb+++ b/plugins/chat/app/controllers/chat/api/channel_thread_messages_controller.rb@@ -29,4 +29,10 @@ class Chat::Api::ChannelThreadMessagesController < Chat::ApiControllerendendend++ private++ def allow_anonymous_public_chat_access?+ anonymous_public_chat_access_enabled?+ endenddiff --git a/plugins/chat/app/controllers/chat/api/channel_threads_controller.rb b/plugins/chat/app/controllers/chat/api/channel_threads_controller.rbindex faed48572a1..10f246d483e 100644--- a/plugins/chat/app/controllers/chat/api/channel_threads_controller.rb+++ b/plugins/chat/app/controllers/chat/api/channel_threads_controller.rb@@ -94,4 +94,10 @@ class Chat::Api::ChannelThreadsController < Chat::ApiControlleron_failure { render(json: failed_json, status: :unprocessable_entity) }endend++ private++ def allow_anonymous_public_chat_access?+ action_name == "show" && anonymous_public_chat_access_enabled?+ endenddiff --git a/plugins/chat/app/controllers/chat/api/channels_controller.rb b/plugins/chat/app/controllers/chat/api/channels_controller.rbindex ccbbea392d0..f6d0ef12c91 100644--- a/plugins/chat/app/controllers/chat/api/channels_controller.rb+++ b/plugins/chat/app/controllers/chat/api/channels_controller.rb@@ -28,7 +28,7 @@ class Chat::Api::ChannelsController < Chat::ApiController)end- memberships = Chat::ChannelMembershipManager.all_for_user(current_user)+ memberships = current_user ? Chat::ChannelMembershipManager.all_for_user(current_user) : []channels = Chat::ChannelFetcher.secured_public_channels(guardian, options)serialized_channels =channels.map do |channel|diff --git a/plugins/chat/app/controllers/chat/api/current_user_channels_controller.rb b/plugins/chat/app/controllers/chat/api/current_user_channels_controller.rbindex a1e0853bfa0..05d20993560 100644--- a/plugins/chat/app/controllers/chat/api/current_user_channels_controller.rb+++ b/plugins/chat/app/controllers/chat/api/current_user_channels_controller.rb@@ -14,4 +14,10 @@ class Chat::Api::CurrentUserChannelsController < Chat::ApiControlleron_failure { render(json: failed_json, status: :unprocessable_entity) }endend++ private++ def allow_anonymous_public_chat_access?+ anonymous_public_chat_access_enabled?+ endenddiff --git a/plugins/chat/app/controllers/chat/base_controller.rb b/plugins/chat/app/controllers/chat/base_controller.rbindex 8ea85a50e07..eb61c2f5f56 100644--- a/plugins/chat/app/controllers/chat/base_controller.rb+++ b/plugins/chat/app/controllers/chat/base_controller.rb@@ -4,8 +4,8 @@ module Chatclass BaseController < ::ApplicationControllerrequires_plugin PLUGIN_NAME- before_action :ensure_logged_in- before_action :ensure_can_chat+ before_action :ensure_logged_in, unless: :allow_anonymous_public_chat_access?+ before_action :ensure_can_chat, unless: :allow_anonymous_public_chat_access?private@@ -13,6 +13,14 @@ module Chatguardian.ensure_can_chat!end+ def allow_anonymous_public_chat_access?+ false+ end++ def anonymous_public_chat_access_enabled?+ !current_user && Chat.anonymous_public_channel_access_allowed?+ end+def set_channel_and_chatable_with_access_check(chat_channel_id: nil)params.require(:chat_channel_id) if chat_channel_id.blank?id_or_name = chat_channel_id || params[:chat_channel_id]diff --git a/plugins/chat/app/queries/chat/messages_query.rb b/plugins/chat/app/queries/chat/messages_query.rbindex b0632249d6a..bb6c275917e 100644--- a/plugins/chat/app/queries/chat/messages_query.rb+++ b/plugins/chat/app/queries/chat/messages_query.rb@@ -53,7 +53,8 @@ module Chattarget_date: nil,include_target_message_id: false)- messages = base_query(channel: channel)+ include_bookmarks = guardian.user.present?+ messages = base_query(channel: channel, include_bookmarks: include_bookmarks)messages = messages.with_deleted if guardian.can_moderate_chat?(channel.chatable)if thread_id.present?include_thread_messages = true@@ -78,7 +79,12 @@ module Chatendif target_message_id.present? && direction.blank?- query_around_target(target_message_id, channel, messages)+ query_around_target(+ target_message_id,+ channel,+ messages,+ include_bookmarks: include_bookmarks,+ )elseif target_date.present?query_by_date(target_date, channel, messages)@@ -95,7 +101,7 @@ module Chatendend- def self.base_query(channel:)+ def self.base_query(channel:, include_bookmarks: true)query =Chat::Message.includes(in_reply_to: [:user, chat_webhook_event: [:incoming_chat_webhook]])@@ -103,12 +109,13 @@ module Chat.includes(user: :primary_group).includes(chat_webhook_event: :incoming_chat_webhook).includes(reactions: :user)- .includes(:bookmarks).includes(uploads: { optimized_videos: :optimized_upload }).includes(chat_channel: :chatable).includes(:pinned_message).where(chat_channel_id: channel.id)+ query = query.includes(:bookmarks) if include_bookmarks+user_includes = SiteSetting.enable_user_status ? %i[user_status user_option] : %i[user_option]query.includes(user: user_includes,@@ -122,8 +129,11 @@ module Chat)end- def self.query_around_target(target_message_id, channel, messages)- target_message = base_query(channel: channel).with_deleted.find_by(id: target_message_id)+ def self.query_around_target(target_message_id, channel, messages, include_bookmarks: true)+ target_message =+ base_query(channel: channel, include_bookmarks: include_bookmarks).with_deleted.find_by(+ id: target_message_id,+ )past_messages =messagesdiff --git a/plugins/chat/app/serializers/chat/channel_index_serializer.rb b/plugins/chat/app/serializers/chat/channel_index_serializer.rbindex 31c3eebe286..6b8f8309ef0 100644--- a/plugins/chat/app/serializers/chat/channel_index_serializer.rb+++ b/plugins/chat/app/serializers/chat/channel_index_serializer.rb@@ -7,5 +7,9 @@ module Chatdef global_presence_channel_statePresenceChannelStateSerializer.new(PresenceChannel.new("/chat/online").state, root: nil)end++ def include_global_presence_channel_state?+ !scope.anonymous?+ endendenddiff --git a/plugins/chat/app/serializers/chat/channel_serializer.rb b/plugins/chat/app/serializers/chat/channel_serializer.rbindex 0b02436f1c2..725bbfc37ab 100644--- a/plugins/chat/app/serializers/chat/channel_serializer.rb+++ b/plugins/chat/app/serializers/chat/channel_serializer.rb@@ -129,13 +129,14 @@ module Chatenddef meta- ids = {- channel_message_bus_last_id: channel_message_bus_last_id,- new_messages: new_messages_message_bus_id,- new_mentions: new_mentions_message_bus_id,- }+ ids = { channel_message_bus_last_id: channel_message_bus_last_id }++ if !scope.anonymous?+ ids[:new_messages] = new_messages_message_bus_id+ ids[:new_mentions] = new_mentions_message_bus_id+ ids[:kick] = kick_message_bus_id if !object.direct_message_channel?+ end- ids[:kick] = kick_message_bus_id if !object.direct_message_channel?data = { message_bus_last_ids: ids }if @opts.key?(:can_join_chat_channel)diff --git a/plugins/chat/app/serializers/chat/message_serializer.rb b/plugins/chat/app/serializers/chat/message_serializer.rbindex b821acdfa76..807c5bb4b60 100644--- a/plugins/chat/app/serializers/chat/message_serializer.rb+++ b/plugins/chat/app/serializers/chat/message_serializer.rb@@ -91,6 +91,8 @@ module Chatenddef users_bookmark+ return if scope&.user.blank?+@user_bookmark ||= object.bookmarks.find { |bookmark| bookmark.user_id == scope&.user&.id }enddiff --git a/plugins/chat/app/serializers/chat/structured_channel_serializer.rb b/plugins/chat/app/serializers/chat/structured_channel_serializer.rbindex 47c3832ed63..188f28dd486 100644--- a/plugins/chat/app/serializers/chat/structured_channel_serializer.rb+++ b/plugins/chat/app/serializers/chat/structured_channel_serializer.rb@@ -23,22 +23,36 @@ module Chatdef public_channelsobject[:public_channels].map do |channel|+ message_bus_last_ids = {+ channel_message_bus_last_id:+ chat_message_bus_last_ids[Chat::Publisher.root_message_bus_channel(channel.id)],+ }++ if !scope.anonymous?+ message_bus_last_ids.merge!(+ new_messages_message_bus_last_id:+ chat_message_bus_last_ids[+ Chat::Publisher.new_messages_message_bus_channel(channel.id)+ ],+ new_mentions_message_bus_last_id:+ chat_message_bus_last_ids[+ Chat::Publisher.new_mentions_message_bus_channel(channel.id)+ ],+ kick_message_bus_last_id:+ chat_message_bus_last_ids[Chat::Publisher.kick_users_message_bus_channel(channel.id)],+ )+ end+Chat::ChannelSerializer.new(channel,root: nil,scope: scope,membership: channel_membership(channel.id),- new_messages_message_bus_last_id:- chat_message_bus_last_ids[Chat::Publisher.new_messages_message_bus_channel(channel.id)],- new_mentions_message_bus_last_id:- chat_message_bus_last_ids[Chat::Publisher.new_mentions_message_bus_channel(channel.id)],- kick_message_bus_last_id:- chat_message_bus_last_ids[Chat::Publisher.kick_users_message_bus_channel(channel.id)],- channel_message_bus_last_id:- chat_message_bus_last_ids[Chat::Publisher.root_message_bus_channel(channel.id)],- # NOTE: This is always true because the public channels passed into this serializer- # have been fetched with [Chat::ChannelFetcher], which only returns channels that- # the user has access to based on category permissions.+ **message_bus_last_ids,+ # NOTE: The public channels passed into this serializer have been fetched with+ # [Chat::ChannelFetcher], which only returns channels that the user has access to based+ # on category permissions. Anonymous users get a join CTA, but the client sends them to+ # the login/signup flow before attempting to join.can_join_chat_channel: true,post_allowed_category_ids: @options[:post_allowed_category_ids],)@@ -68,6 +82,8 @@ module Chatenddef meta+ return { message_bus_last_ids: {} } if scope.anonymous?+last_ids = {channel_metadata:chat_message_bus_last_ids[Chat::Publisher::CHANNEL_METADATA_MESSAGE_BUS_CHANNEL],@@ -80,21 +96,19 @@ module Chatchat_message_bus_last_ids[Chat::Publisher::CHANNEL_ARCHIVE_STATUS_MESSAGE_BUS_CHANNEL],}- if !scope.anonymous?- user_tracking_state_last_id =- chat_message_bus_last_ids[- Chat::Publisher.user_tracking_state_message_bus_channel(scope.user.id)- ]+ user_tracking_state_last_id =+ chat_message_bus_last_ids[+ Chat::Publisher.user_tracking_state_message_bus_channel(scope.user.id)+ ]- last_ids[:user_tracking_state] = user_tracking_state_last_id if user_tracking_state_last_id+ last_ids[:user_tracking_state] = user_tracking_state_last_id if user_tracking_state_last_id- user_has_threads_last_id =- chat_message_bus_last_ids[- Chat::Publisher.user_has_threads_message_bus_channel(scope.user.id)- ]+ user_has_threads_last_id =+ chat_message_bus_last_ids[+ Chat::Publisher.user_has_threads_message_bus_channel(scope.user.id)+ ]- last_ids[:user_has_threads] = user_has_threads_last_id if user_has_threads_last_id- end+ last_ids[:user_has_threads] = user_has_threads_last_id if user_has_threads_last_id{ message_bus_last_ids: last_ids }end@@ -104,35 +118,48 @@ module Chatdef chat_message_bus_last_ids@chat_message_bus_last_ids ||=begin- message_bus_channels = [- Chat::Publisher::CHANNEL_METADATA_MESSAGE_BUS_CHANNEL,- Chat::Publisher::CHANNEL_EDITS_MESSAGE_BUS_CHANNEL,- Chat::Publisher::CHANNEL_STATUS_MESSAGE_BUS_CHANNEL,- Chat::Publisher::NEW_CHANNEL_MESSAGE_BUS_CHANNEL,- Chat::Publisher::CHANNEL_ARCHIVE_STATUS_MESSAGE_BUS_CHANNEL,- ]-- if !scope.anonymous?- message_bus_channels.push(- Chat::Publisher.user_tracking_state_message_bus_channel(scope.user.id),- Chat::Publisher.user_has_threads_message_bus_channel(scope.user.id),- )- end+ message_bus_channels =+ if scope.anonymous?+ []+ else+ [+ Chat::Publisher::CHANNEL_METADATA_MESSAGE_BUS_CHANNEL,+ Chat::Publisher::CHANNEL_EDITS_MESSAGE_BUS_CHANNEL,+ Chat::Publisher::CHANNEL_STATUS_MESSAGE_BUS_CHANNEL,+ Chat::Publisher::NEW_CHANNEL_MESSAGE_BUS_CHANNEL,+ Chat::Publisher::CHANNEL_ARCHIVE_STATUS_MESSAGE_BUS_CHANNEL,+ Chat::Publisher.user_tracking_state_message_bus_channel(scope.user.id),+ Chat::Publisher.user_has_threads_message_bus_channel(scope.user.id),+ ]+ endobject[:public_channels].each do |channel|- message_bus_channels.push(Chat::Publisher.new_messages_message_bus_channel(channel.id))- message_bus_channels.push(Chat::Publisher.new_mentions_message_bus_channel(channel.id))- message_bus_channels.push(Chat::Publisher.kick_users_message_bus_channel(channel.id))message_bus_channels.push(Chat::Publisher.root_message_bus_channel(channel.id))++ if !scope.anonymous?+ message_bus_channels.push(+ Chat::Publisher.new_messages_message_bus_channel(channel.id),+ )+ message_bus_channels.push(+ Chat::Publisher.new_mentions_message_bus_channel(channel.id),+ )+ message_bus_channels.push(Chat::Publisher.kick_users_message_bus_channel(channel.id))+ endend- object[:direct_message_channels].each do |channel|- message_bus_channels.push(Chat::Publisher.new_messages_message_bus_channel(channel.id))- message_bus_channels.push(Chat::Publisher.new_mentions_message_bus_channel(channel.id))- message_bus_channels.push(Chat::Publisher.root_message_bus_channel(channel.id))+ if !scope.anonymous?+ object[:direct_message_channels].each do |channel|+ message_bus_channels.push(+ Chat::Publisher.new_messages_message_bus_channel(channel.id),+ )+ message_bus_channels.push(+ Chat::Publisher.new_mentions_message_bus_channel(channel.id),+ )+ message_bus_channels.push(Chat::Publisher.root_message_bus_channel(channel.id))+ endend- MessageBus.last_ids(*message_bus_channels)+ message_bus_channels.present? ? MessageBus.last_ids(*message_bus_channels) : {}endendenddiff --git a/plugins/chat/app/services/chat/list_channel_messages.rb b/plugins/chat/app/services/chat/list_channel_messages.rbindex 6a0df00aef9..75fbf546b6b 100644--- a/plugins/chat/app/services/chat/list_channel_messages.rb+++ b/plugins/chat/app/services/chat/list_channel_messages.rb@@ -70,10 +70,17 @@ module Chatenddef can_view_channel(guardian:, channel:)+ if guardian.anonymous?+ return false if !Chat.anonymous_public_channel_access_allowed?+ return false if !channel&.category_channel?+ end+guardian.can_preview_chat_channel?(channel)enddef fetch_membership(channel:, guardian:)+ return if guardian.anonymous?+channel.membership_for(guardian.user)end@@ -92,13 +99,23 @@ module Chat)end- def fetch_messages(metadata:)- [+ def fetch_messages(metadata:, guardian:)+ messages = [metadata[:messages],metadata[:past_messages]&.reverse,(metadata[:target_message] unless metadata[:target_message]&.thread_reply?),metadata[:future_messages],].flatten.compact++ if guardian.user.blank?+ messages.each do |message|+ association = message.association(:bookmarks)+ association.target = []+ association.loaded!+ end+ end++ messagesenddef fetch_thread_ids(messages:)@@ -106,6 +123,8 @@ module Chatenddef fetch_tracking(guardian:, thread_ids:)+ return ::Chat::TrackingStateReport.new if guardian.anonymous?+::Chat::TrackingStateReportQuery.(guardian:, thread_ids:, include_threads: true)end@@ -116,7 +135,7 @@ module Chatenddef fetch_thread_memberships(guardian:, thread_ids:)- return if thread_ids.blank?+ return if thread_ids.blank? || guardian.anonymous?::Chat::UserChatThreadMembership.where(thread_id: thread_ids, user_id: guardian.user.id)end@@ -128,6 +147,8 @@ module Chatenddef update_user_last_channel(guardian:, channel:)+ return if guardian.anonymous?+Scheduler::Defer.later "Chat::ListChannelMessages - defer update_user_last_channel" donext if guardian.user.custom_fields[::Chat::LAST_CHAT_CHANNEL_ID] == channel.idguardian.user.upsert_custom_fields(::Chat::LAST_CHAT_CHANNEL_ID => channel.id)diff --git a/plugins/chat/app/services/chat/list_channel_thread_messages.rb b/plugins/chat/app/services/chat/list_channel_thread_messages.rbindex e4332ab05bd..1ac73b696e8 100644--- a/plugins/chat/app/services/chat/list_channel_thread_messages.rb+++ b/plugins/chat/app/services/chat/list_channel_thread_messages.rb@@ -108,13 +108,23 @@ module Chat)end- def fetch_messages(metadata:)- [+ def fetch_messages(metadata:, guardian:)+ messages = [metadata[:messages],metadata[:past_messages]&.reverse,metadata[:target_message],metadata[:future_messages],].flatten.compact++ if guardian.user.blank?+ messages.each do |message|+ association = message.association(:bookmarks)+ association.target = []+ association.loaded!+ end+ end++ messagesendendenddiff --git a/plugins/chat/app/services/chat/list_user_channels.rb b/plugins/chat/app/services/chat/list_user_channels.rbindex 9848702314d..27337fb4944 100644--- a/plugins/chat/app/services/chat/list_user_channels.rb+++ b/plugins/chat/app/services/chat/list_user_channels.rb@@ -25,10 +25,20 @@ module Chatenddef inject_has_threads(structured:, guardian:)+ if guardian.anonymous?+ structured[:has_threads] = false+ return+ end+structured[:has_threads] = ::Chat::Thread.viewable_by_user(guardian.user).exists?enddef inject_unread_thread_overview(structured:, guardian:)+ if guardian.anonymous?+ structured[:unread_thread_overview] = {}+ return+ end+channel_ids =structured[:public_channels].map(&:id) + structured[:direct_message_channels].map(&:id)structured[:unread_thread_overview] = ::Chat::TrackingStateReportQuery.call(diff --git a/plugins/chat/app/services/chat/publisher.rb b/plugins/chat/app/services/chat/publisher.rbindex a57c7365b76..5a635995297 100644--- a/plugins/chat/app/services/chat/publisher.rb+++ b/plugins/chat/app/services/chat/publisher.rb@@ -503,6 +503,8 @@ module Chatdef self.permissions(channel)group_ids = channel.allowed_group_ids.presenceif group_ids.blank? && channel.category_channel? && !channel.read_restricted?+ return {} if Chat.anonymous_public_channel_access_allowed?+group_ids = chat_allowed_group_idsend@@ -511,8 +513,10 @@ module Chatdef self.chat_allowed_group_idspseudo_everyone_ids = [Group::AUTO_GROUPS[:everyone], Group::AUTO_GROUPS[:logged_in_users]]+ excluded_group_ids = [Group::AUTO_GROUPS[:anonymous_users]]Chat.allowed_group_ids+ .reject { |group_id| excluded_group_ids.include?(group_id) }.map do |group_id|pseudo_everyone_ids.include?(group_id) ? Group::AUTO_GROUPS[:trust_level_0] : group_idenddiff --git a/plugins/chat/assets/javascripts/discourse/components/channels-list-public.gjs b/plugins/chat/assets/javascripts/discourse/components/channels-list-public.gjsindex bc198d87936..265f553cd6e 100644--- a/plugins/chat/assets/javascripts/discourse/components/channels-list-public.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/channels-list-public.gjs@@ -19,6 +19,7 @@ export default class ChannelsListPublic extends Component {@service chatTrackingStateManager;@service site;@service router;+ @service currentUser;get inSidebar() {return this.args.inSidebar ?? false;@@ -32,6 +33,10 @@ export default class ChannelsListPublic extends Component {return this.chatChannelsManager.shouldShowMyThreads;}+ get canBrowseChannels() {+ return !!this.currentUser;+ }+get channelList() {if (this.inSidebar) {return this.chatChannelsManager.unstarredPublicMessageChannelsByActivity;@@ -84,13 +89,15 @@ export default class ChannelsListPublic extends Component {<span class="channel-title">{{i18n "chat.chat_channels"}}</span>- <LinkTo- @route="chat.browse"- class="btn no-text btn-flat open-browse-page-btn title-action"- title={{i18n "chat.channels_list_popup.browse"}}- >- {{dIcon "pencil"}}- </LinkTo>+ {{#if this.canBrowseChannels}}+ <LinkTo+ @route="chat.browse"+ class="btn no-text btn-flat open-browse-page-btn title-action"+ title={{i18n "chat.channels_list_popup.browse"}}+ >+ {{dIcon "pencil"}}+ </LinkTo>+ {{/if}}</div>{{/if}}@@ -108,10 +115,13 @@ export default class ChannelsListPublic extends Component {@svgContent={{ChatZero}}@title={{i18n "chat.no_public_channels"}}@ctaLabel={{if- this.chatChannelsManager.displayPublicChannels+ (and+ this.canBrowseChannels+ this.chatChannelsManager.displayPublicChannels+ )(i18n "chat.no_public_channels_cta")}}- @ctaAction={{this.openBrowseChannels}}+ @ctaAction={{if this.canBrowseChannels this.openBrowseChannels}}/>{{else}}{{#each this.channelList as |channel|}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-preview-card.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-preview-card.gjsindex f232491998d..a2eebce42cc 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-preview-card.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-preview-card.gjs@@ -1,6 +1,7 @@import Component from "@glimmer/component";import { hash } from "@ember/helper";import { LinkTo } from "@ember/routing";+import { service } from "@ember/service";import { isEmpty } from "@ember/utils";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import { i18n } from "discourse-i18n";@@ -8,10 +9,16 @@ import ChannelTitle from "./channel-title";import ToggleChannelMembershipButton from "./toggle-channel-membership-button";export default class ChatChannelPreviewCard extends Component {+ @service currentUser;+get showJoinButton() {return this.args.channel?.isOpen && this.args.channel?.canJoin;}+ get showBrowseAllLink() {+ return !!this.currentUser;+ }+get hasDescription() {return !isEmpty(this.args.channel?.description);}@@ -36,12 +43,14 @@ export default class ChatChannelPreviewCard extends Component {@options={{hash joinClass="btn-primary"}}/>{{/if}}- <LinkTo- @route="chat.browse"- class="chat-channel-preview-card__browse-all"- >- {{i18n "chat.browse_all_channels"}}- </LinkTo>+ {{#if this.showBrowseAllLink}}+ <LinkTo+ @route="chat.browse"+ class="chat-channel-preview-card__browse-all"+ >+ {{i18n "chat.browse_all_channels"}}+ </LinkTo>+ {{/if}}</div></template>}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjsindex ccb15e88b96..34165836129 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs@@ -346,7 +346,7 @@ export default class ChatChannel extends Component {result?.messages?.forEach((messageData, index) => {messageData.firstOfResults = index === 0;- if (this.currentUser.ignored_users) {+ if (this.currentUser?.ignored_users) {// If a message has been hidden it is because the current user is ignoring// the user who sent it, so we want to unconditionally hide it, even if// we are going directly to the targetdiff --git a/plugins/chat/assets/javascripts/discourse/components/chat-composer.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-composer.gjsindex e79af40f18e..d73e4f6dc86 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-composer.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-composer.gjs@@ -175,6 +175,24 @@ export default class ChatComposer extends Component {);}+ get disabled() {+ return !this.currentUser || this.args.disabled;+ }++ @action+ focusOrPromptLogin() {+ if (!this.currentUser) {+ this.showLogin();+ return;+ }++ this.composer.focus();+ }++ showLogin() {+ getOwner(this).lookup("route:application").send("showLogin");+ }+@actionsetup() {this.composer.scroller = this.args.scroller;@@ -265,6 +283,11 @@ export default class ChatComposer extends Component {@actionasync onSend(event) {+ if (!this.currentUser) {+ this.showLogin();+ return;+ }+if (!this.sendEnabled) {return;}@@ -368,6 +391,11 @@ export default class ChatComposer extends Component {@actiononTextareaFocusIn() {+ if (!this.currentUser) {+ this.showLogin();+ return;+ }+this.forceScrollPosition();this.isFocused = true;}@@ -771,7 +799,7 @@ export default class ChatComposer extends Component {<divclass="chat-composer__input-container"- {{on "click" this.composer.focus}}+ {{on "click" this.focusOrPromptLogin}}><DTextarea{{preventScrollOnFocus}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-drawer.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-drawer.gjsindex 67d1b825657..fd5944e47c8 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-drawer.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-drawer.gjs@@ -34,7 +34,7 @@ export default class ChatDrawer extends Component {didInsertElement() {super.didInsertElement(...arguments);- if (!this.chat.userCanChat) {+ if (!this.chat.userCanChat && !this.chat.anonymousUserCanViewPublicChat) {return;}@@ -59,7 +59,7 @@ export default class ChatDrawer extends Component {willDestroyElement() {super.willDestroyElement(...arguments);- if (!this.chat.userCanChat) {+ if (!this.chat.userCanChat && !this.chat.anonymousUserCanViewPublicChat) {return;}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-footer.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-footer.gjsindex aea891b0c7a..2c1c528a965 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-footer.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-footer.gjs@@ -18,9 +18,14 @@ export default class ChatFooter extends Component {@service site;@service chatChannelsManager;@service chatStateManager;+ @service currentUser;get includeStarred() {- return this.chatChannelsManager.hasStarredChannels;+ return this.currentUser && this.chatChannelsManager.hasStarredChannels;+ }++ get includeSearch() {+ return this.currentUser && this.siteSettings.chat_search_enabled;}get includeThreads() {@@ -125,7 +130,7 @@ export default class ChatFooter extends Component {</DButton>{{/if}}- {{#if this.siteSettings.chat_search_enabled}}+ {{#if this.includeSearch}}<DButton@route="chat.search"@icon="magnifying-glass"diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message-reaction.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-message-reaction.gjsindex 5caed7b9dcd..ea014bfc091 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-message-reaction.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message-reaction.gjs@@ -2,6 +2,7 @@ import Component from "@glimmer/component";import { cached } from "@glimmer/tracking";import { on } from "@ember/modifier";import { action } from "@ember/object";+import { getOwner } from "@ember/owner";import { service } from "@ember/service";import { trustHTML } from "@ember/template";import { modifier } from "ember-modifier";@@ -50,6 +51,11 @@ export default class ChatMessageReaction extends Component {handleClick(event) {event.stopPropagation();+ if (!this.currentUser) {+ getOwner(this).lookup("route:application").send("showLogin");+ return;+ }+this.args.onReaction?.(this.args.reaction.emoji,this.args.reaction.reacted ? "remove" : "add"diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-message.gjsindex c0d78b43691..6a19ba41cf7 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message.gjs@@ -261,12 +261,16 @@ export default class ChatMessage extends Component {get show() {return (!this.args.message?.deletedAt ||- this.currentUser.id === this.args.message?.user?.id ||- this.currentUser.staff ||+ this.currentUser?.id === this.args.message?.user?.id ||+ this.currentUser?.staff ||this.args.message?.channel?.canModerate);}+ get isByCurrentUser() {+ return this.currentUser?.id === this.args.message?.user?.id;+ }+@actiononMouseEnter() {if (this.site.mobileView) {@@ -521,8 +525,8 @@ export default class ChatMessage extends Component {get shouldRenderStopMessageStreamingButton() {return (this.args.message.streaming &&- (this.currentUser.admin ||- this.args.message.inReplyTo?.user?.id === this.currentUser.id)+ (this.currentUser?.admin ||+ this.args.message.inReplyTo?.user?.id === this.currentUser?.id));}@@ -565,8 +569,7 @@ export default class ChatMessage extends Component {(if @message.highlighted "-highlighted")(if @message.streaming "-streaming")(if (lt @message.user.id 0) "is-bot")- (if (eq @message.user.id this.currentUser.id) "is-by-current-user")- (if (eq @message.id this.currentUser.id) "is-by-current-user")+ (if this.isByCurrentUser "is-by-current-user")(if(eq@message.iddiff --git a/plugins/chat/assets/javascripts/discourse/components/chat-thread-title-prompt.js b/plugins/chat/assets/javascripts/discourse/components/chat-thread-title-prompt.jsindex bfbff1a0d34..e67d7a361c9 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-thread-title-prompt.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-thread-title-prompt.js@@ -65,6 +65,7 @@ export default class ChatThreadTitlePrompt extends Component {get canShowToast() {if (+ !this.currentUser ||this.site.desktopView ||(this.args.thread.originalMessage?.user?.id !== this.currentUser.id &&!this.currentUser.admin)diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjsindex 4ae2209bfdf..32e70f85941 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-thread.gjs@@ -91,16 +91,18 @@ export default class ChatThread extends Component {this.uploadDropZone = element;this.messagesManager.clear();- this.args.thread.draft =- this.chatDraftsManager.get(- this.args.thread.channel?.id,- this.args.thread.id- ) ||- ChatMessage.createDraftMessage(this.args.thread.channel, {- user: this.currentUser,- thread: this.args.thread,- });- this.chatThreadComposer.focus();+ if (this.currentUser) {+ this.args.thread.draft =+ this.chatDraftsManager.get(+ this.args.thread.channel?.id,+ this.args.thread.id+ ) ||+ ChatMessage.createDraftMessage(this.args.thread.channel, {+ user: this.currentUser,+ thread: this.args.thread,+ });+ this.chatThreadComposer.focus();+ }this.loadMessages();}@@ -373,7 +375,7 @@ export default class ChatThread extends Component {@bindprocessMessages(thread, result) {const messages = result.messages.map((messageData) => {- const ignored = this.currentUser.ignored_users || [];+ const ignored = this.currentUser?.ignored_users || [];const hidden = ignored.includes(messageData.user.username);return ChatMessage.create(thread.channel, {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.gjsindex d1eb7a714d2..382cda8b2a3 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@@ -11,6 +11,7 @@ export default class ChatDrawerRoutesChannel extends Component {@service chatStateManager;@service chatHistory;@service siteSettings;+ @service currentUser;@tracked isFiltering = false;@@ -19,6 +20,10 @@ export default class ChatDrawerRoutesChannel extends Component {this.isFiltering = !this.isFiltering;}+ get canSearchChat() {+ return this.currentUser && this.siteSettings.chat_search_enabled;+ }+get backBtnRoute() {if (this.chatHistory.previousRoute?.name === "chat.browse") {return "chat.browse";@@ -40,7 +45,7 @@ export default class ChatDrawerRoutesChannel extends Component {<navbar.BackButton @route={{this.backBtnRoute}} /><navbar.ChannelTitle @channel={{@model.channel}} /><navbar.Actions as |a|>- {{#if this.siteSettings.chat_search_enabled}}+ {{#if this.canSearchChat}}<a.Filter@channel={{@model.channel}}@onToggleFilter={{this.toggleIsFiltering}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/header/icon.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/header/icon.gjsindex aed9ba2c5e7..7c6402acf33 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/header/icon.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat/header/icon.gjs@@ -24,7 +24,7 @@ export default class ChatHeaderIcon extends Component {}get currentUserInDnD() {- return this.args.currentUserInDnD || this.currentUser.isInDoNotDisturb();+ return this.args.currentUserInDnD || this.currentUser?.isInDoNotDisturb();}get chatSeparateSidebarMode() {diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/browse-channels-button.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/browse-channels-button.gjsindex dac1d4d3232..09af6f8bc0d 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/browse-channels-button.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/browse-channels-button.gjs@@ -6,11 +6,14 @@ import { i18n } from "discourse-i18n";export default class ChatNavbarBrowseChannelsButton extends Component {@service router;+ @service currentUser;browseChannelsLabel = i18n("chat.channels_list_popup.browse");get showBrowseChannelsButton() {- return this.router.currentRoute.name === "chat.channels";+ return (+ this.currentUser && this.router.currentRoute.name === "chat.channels"+ );}<template>diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/channel-title.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/channel-title.gjsindex c8c79dfb3fc..874c6059979 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/channel-title.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/channel-title.gjs@@ -12,6 +12,7 @@ import ChannelTitle from "discourse/plugins/chat/discourse/components/channel-tiexport default class ChatNavbarChannelTitle extends Component {@service chatApi;@service chatStateManager;+ @service currentUser;@tracked isTogglingStarred = false;@@ -37,7 +38,7 @@ export default class ChatNavbarChannelTitle extends Component {}get showStarButton() {- return !!this.args.channel?.currentUserMembership;+ return this.currentUser && !!this.args.channel?.currentUserMembership;}@actiondiff --git a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/thread-settings-button.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/thread-settings-button.gjsindex 43e567477be..d1291b7fcd2 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/navbar/thread-settings-button.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat/navbar/thread-settings-button.gjs@@ -14,8 +14,8 @@ export default class ChatNavbarThreadSettingsButton extends Component {}return (- this.currentUser.staff ||- this.currentUser.id === this.args.thread.originalMessage.user.id+ this.currentUser?.staff ||+ this.currentUser?.id === this.args.thread.originalMessage.user.id);}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel.gjsindex b671f343246..95482f41726 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel.gjs@@ -12,6 +12,7 @@ export default class ChatRoutesChannel extends Component {@service chat;@service chatHistory;@service chatTrackingStateManager;+ @service currentUser;@tracked isFiltering = false;@@ -21,6 +22,10 @@ export default class ChatRoutesChannel extends Component {this.chat.activeMessage = null;}+ get canSearchChat() {+ return this.currentUser && this.siteSettings.chat_search_enabled;+ }+get getChannelsRoute() {if (this.chatHistory.previousRoute?.name === "chat.browse") {return "chat.browse";@@ -73,7 +78,7 @@ export default class ChatRoutesChannel extends Component {{{/if}}<navbar.ChannelTitle @channel={{@channel}} /><navbar.Actions as |a|>- {{#if this.siteSettings.chat_search_enabled}}+ {{#if this.canSearchChat}}<a.Filter@channel={{@channel}}@isFiltering={{this.isFiltering}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/thread/header-unread-indicator.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/thread/header-unread-indicator.gjsindex fc2b2c8abc0..788968ff277 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/thread/header-unread-indicator.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat/thread/header-unread-indicator.gjs@@ -14,7 +14,7 @@ export default class ThreadHeaderUnreadIndicator extends Component {}get showUnreadIndicator() {- return !this.currentUser.isInDoNotDisturb() && this.unreadCount > 0;+ return !this.currentUser?.isInDoNotDisturb() && this.unreadCount > 0;}get cappedUnreadCount() {diff --git a/plugins/chat/assets/javascripts/discourse/components/chat/thread/header.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/thread/header.gjsindex ba28b52b62f..bd523f0d477 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/thread/header.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat/thread/header.gjs@@ -32,7 +32,7 @@ export default class ChatThreadHeader extends Component {route = "chat.threads";title = i18n("chat.my_threads.title");models = [];- } else if (!this.currentUser.isInDoNotDisturb() && this.unreadCount > 0) {+ } else if (!this.currentUser?.isInDoNotDisturb() && this.unreadCount > 0) {route = "chat.channel.threads";title = i18n("chat.return_to_threads_list");models = this.channel?.routeModels;@@ -65,8 +65,8 @@ export default class ChatThreadHeader extends Component {get openThreadTitleModal() {if (- this.currentUser.admin ||- this.currentUser.id === this.args.thread?.originalMessage?.user?.id+ this.currentUser?.admin ||+ this.currentUser?.id === this.args.thread?.originalMessage?.user?.id) {return () =>this.modal.show(ThreadSettingsModal, { model: this.args.thread });@@ -95,8 +95,10 @@ export default class ChatThreadHeader extends Component {class={{if this.openThreadTitleModal "clickable"}}/><navbar.Actions as |action|>- <action.ThreadTrackingDropdown @thread={{@thread}} />- <action.ThreadSettingsButton @thread={{@thread}} />+ {{#if this.currentUser}}+ <action.ThreadTrackingDropdown @thread={{@thread}} />+ <action.ThreadSettingsButton @thread={{@thread}} />+ {{/if}}<action.CloseThreadButton @thread={{@thread}} /></navbar.Actions></Navbar>diff --git a/plugins/chat/assets/javascripts/discourse/components/toggle-channel-membership-button.gjs b/plugins/chat/assets/javascripts/discourse/components/toggle-channel-membership-button.gjsindex 8f07da27202..177a64e9da2 100644--- a/plugins/chat/assets/javascripts/discourse/components/toggle-channel-membership-button.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/toggle-channel-membership-button.gjs@@ -1,6 +1,7 @@import Component from "@glimmer/component";import { tracked } from "@glimmer/tracking";import { action } from "@ember/object";+import { getOwner } from "@ember/owner";import { service } from "@ember/service";import PluginOutlet from "discourse/components/plugin-outlet";import lazyHash from "discourse/helpers/lazy-hash";@@ -12,6 +13,8 @@ import { i18n } from "discourse-i18n";export default class ToggleChannelMembershipButton extends Component {@service chat;@service chatApi;+ @service chatStateManager;+ @service currentUser;@tracked isLoading = false;@@ -38,22 +41,35 @@ export default class ToggleChannelMembershipButton extends Component {}if (this.options.labelType === "short") {- if (this.args.channel.currentUserMembership.following) {+ if (this.isFollowing) {return i18n("chat.channel_settings.leave");} else {return i18n("chat.channel_settings.join");}}- if (this.args.channel.currentUserMembership.following) {+ if (this.isFollowing) {return i18n("chat.channel_settings.leave_channel");} else {return i18n("chat.channel_settings.join_channel");}}+ get isFollowing() {+ return this.args.channel.currentUserMembership?.following;+ }+@actiononJoinChannel() {+ if (!this.currentUser) {+ if (this.chatStateManager.isDrawerActive) {+ this.chatStateManager.didCloseDrawer();+ }++ this.showLogin();+ return;+ }+this.isLoading = true;return this.chat@@ -71,6 +87,10 @@ export default class ToggleChannelMembershipButton extends Component {});}+ showLogin() {+ getOwner(this).lookup("route:application").send("showLogin");+ }+@actionasync onLeaveChannel() {this.isLoading = true;@@ -93,7 +113,7 @@ export default class ToggleChannelMembershipButton extends Component {}<template>- {{#if @channel.currentUserMembership.following}}+ {{#if this.isFollowing}}<DButton@action={{this.onLeaveChannel}}@translatedLabel={{this.label}}diff --git a/plugins/chat/assets/javascripts/discourse/initializers/chat-setup.js b/plugins/chat/assets/javascripts/discourse/initializers/chat-setup.jsindex b495479f55d..7976c29e0d4 100644--- a/plugins/chat/assets/javascripts/discourse/initializers/chat-setup.js+++ b/plugins/chat/assets/javascripts/discourse/initializers/chat-setup.js@@ -48,6 +48,15 @@ class ChatSetupInit {});if (!this.chatService.userCanChat) {+ // include chat elements for anons (except header icon)+ if (+ this.chatService.anonymousUserCanViewPublicChat &&+ !EmbedMode.enabled+ ) {+ document.body.classList.add("chat-enabled");+ api.addCardClickListenerSelector(".chat-drawer-outlet");+ }+return;}diff --git a/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js b/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.jsindex 4e747a10644..9b985db251c 100644--- a/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js+++ b/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js@@ -75,7 +75,7 @@ function createChannelLink(BaseCustomSidebarSectionLink, options = {}) {get classNames() {const classes = [];- if (this.channel.currentUserMembership.muted) {+ if (this.channel.currentUserMembership?.muted) {classes.push("sidebar-section-link--muted");}@@ -244,13 +244,16 @@ export default {name: "chat-sidebar",initialize(container) {this.chatService = container.lookup("service:chat");+ this.siteSettings = container.lookup("service:site-settings");+ this.currentUser = container.lookup("service:current-user");- if (!this.chatService.userCanChat) {+ const canViewPublicChatAnonymously =+ this.chatService.anonymousUserCanViewPublicChat;++ if (!this.chatService.userCanChat && !canViewPublicChatAnonymously) {return;}- this.siteSettings = container.lookup("service:site-settings");- this.currentUser = container.lookup("service:current-user");this.capabilities = container.lookup("service:capabilities");withPluginApi((api) => {@@ -269,7 +272,13 @@ export default {});- initSidebarState(api, api.getCurrentUser());+ if (canViewPublicChatAnonymously) {+ api.setCombinedSidebarMode();+ api.showSidebarSwitchPanelButtons();+ this.chatService.loadChannels();+ } else {+ initSidebarState(api, api.getCurrentUser());+ }});withPluginApi((api) => {@@ -278,7 +287,7 @@ export default {);const chatStateManager = container.lookup("service:chat-state-manager");- if (this.siteSettings.chat_search_enabled) {+ if (this.siteSettings.chat_search_enabled && this.currentUser) {api.addSidebarSection((BaseCustomSidebarSection, BaseCustomSidebarSectionLink) => {const SidebarChatSearchSectionLink = class extends BaseCustomSidebarSectionLink {@@ -499,6 +508,7 @@ export default {constructor({channel,chatService,+ currentUser,siteSettings,menuService,capabilities,@@ -506,6 +516,7 @@ export default {super(...arguments);this.channel = channel;this.chatService = chatService;+ this.currentUser = currentUser;this.menuService = menuService;this.chatStateManager = chatStateManager;this.siteSettings = siteSettings;@@ -513,6 +524,10 @@ export default {}get hoverValue() {+ if (!this.currentUser) {+ return;+ }+return this.capabilities.isIpadOS ? null : "ellipsis-vertical";}@@ -523,7 +538,7 @@ export default {get classNames() {const classes = [];- if (this.channel.currentUserMembership.muted) {+ if (this.channel.currentUserMembership?.muted) {classes.push("sidebar-section-link--muted");}@@ -595,7 +610,7 @@ export default {}get hoverAction() {- if (this.capabilities.isIpadOS) {+ if (!this.currentUser || this.capabilities.isIpadOS) {return noop;}@@ -647,6 +662,7 @@ export default {channel,chatService: this.chatService,menuService: this.menuService,+ currentUser: this.currentUser,siteSettings: this.siteSettings,capabilities: this.capabilities,})@@ -666,6 +682,10 @@ export default {}get actions() {+ if (!this.currentUser) {+ return [];+ }+return [{id: "browseChannels",@@ -782,7 +802,7 @@ export default {get classNames() {const classes = [];- if (this.channel.currentUserMembership.muted) {+ if (this.channel.currentUserMembership?.muted) {classes.push("sidebar-section-link--muted");}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.jsindex 11c7e2f2e87..8ca82466702 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@@ -92,7 +92,7 @@ export default class ChatChannelSubscriptionManager {}handleSentMessage(data) {- if (data.chat_message.user.id === this.currentUser.id && data.staged_id) {+ if (data.chat_message.user.id === this.currentUser?.id && data.staged_id) {const stagedMessage = this.handleStagedMessage(this.channel,this.messagesManager,@@ -144,7 +144,7 @@ export default class ChatChannelSubscriptionManager {handleReactionMessage(data) {const message = this.messagesManager.findMessage(data.chat_message_id);if (message) {- message.react(data.emoji, data.action, data.user, this.currentUser.id);+ message.react(data.emoji, data.action, data.user, this.currentUser?.id);}}@@ -185,9 +185,9 @@ export default class ChatChannelSubscriptionManager {}if (- this.currentUser.staff ||+ this.currentUser?.staff ||this.channel.canModerate ||- this.currentUser.id === targetMsg.user.id+ this.currentUser?.id === targetMsg.user.id) {targetMsg.deletedAt = data.deleted_at;targetMsg.deletedById = data.deleted_by_id;@@ -196,7 +196,9 @@ export default class ChatChannelSubscriptionManager {this.messagesManager.removeMessage(targetMsg);}- if (this.channel.currentUserMembership.lastReadMessageId === targetMsg.id) {+ if (+ this.channel.currentUserMembership?.lastReadMessageId === targetMsg.id+ ) {this.channel.currentUserMembership.lastReadMessageId =data.latest_not_deleted_message_id;}diff --git a/plugins/chat/assets/javascripts/discourse/models/chat-channel.js b/plugins/chat/assets/javascripts/discourse/models/chat-channel.jsindex 7cb61a97a92..942504473c1 100644--- a/plugins/chat/assets/javascripts/discourse/models/chat-channel.js+++ b/plugins/chat/assets/javascripts/discourse/models/chat-channel.js@@ -111,7 +111,7 @@ export default class ChatChannel {}get unreadThreadsCountSinceLastViewed() {- if (!this.threadingEnabled) {+ if (!this.threadingEnabled || !this.currentUserMembership) {return 0;}@@ -226,7 +226,7 @@ export default class ChatChannel {}get isFollowing() {- return this.currentUserMembership.following;+ return this.currentUserMembership?.following;}get canJoin() {@@ -289,6 +289,11 @@ export default class ChatChannel {}set currentUserMembership(membership) {+ if (membership === null) {+ this._currentUserMembership = null;+ return;+ }+if (membership instanceof UserChatChannelMembership) {this._currentUserMembership = membership;} else {diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat.js b/plugins/chat/assets/javascripts/discourse/routes/chat.jsindex 37e2556c3f5..947e0d26769 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat.js@@ -22,7 +22,7 @@ export default class ChatRoute extends DiscourseRoute {}beforeModel(transition) {- if (!this.chat.userCanChat) {+ if (!this.chat.userCanChat && !this.chat.anonymousUserCanViewPublicChat) {return this.router.transitionTo(`discovery.${defaultHomepage()}`);}@@ -80,6 +80,10 @@ export default class ChatRoute extends DiscourseRoute {withPluginApi((api) => {api.setSidebarPanel(CHAT_PANEL);+ if (!this.currentUser) {+ return;+ }+const chatSeparateSidebarMode = getUserChatSeparateSidebarMode(this.currentUser);diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat/browse.js b/plugins/chat/assets/javascripts/discourse/routes/chat/browse.jsindex 57afbfcba99..3d3b490f563 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat/browse.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat/browse.js@@ -1,3 +1,13 @@import Route from "@ember/routing/route";+import { service } from "@ember/service";-export default class extends Route {}+export default class extends Route {+ @service router;+ @service currentUser;++ beforeModel() {+ if (!this.currentUser) {+ return this.router.replaceWith("chat.channels");+ }+ }+}diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat/channels.js b/plugins/chat/assets/javascripts/discourse/routes/chat/channels.jsindex 860d36abc4c..b3783dbdf92 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat/channels.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat/channels.js@@ -11,8 +11,8 @@ export default class ChatChannelsRoute extends DiscourseRoute {}beforeModel() {- const id = this.currentUser.custom_fields.last_chat_channel_id;- if (this.site.desktopView) {+ const id = this.currentUser?.custom_fields?.last_chat_channel_id;+ if (this.site.desktopView && this.currentUser) {if (id) {this.chatChannelsManager.find(id).then((c) => {return this.router.replaceWith("chat.channel", ...c.routeModels);diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat/direct-messages.js b/plugins/chat/assets/javascripts/discourse/routes/chat/direct-messages.jsindex 38a274fe80d..b5c03b701c0 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat/direct-messages.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat/direct-messages.js@@ -4,6 +4,7 @@ import DiscourseRoute from "discourse/routes/discourse";export default class ChatDirectMessagesRoute extends DiscourseRoute {@service chat;@service chatChannelsManager;+ @service currentUser;@service router;activate() {@@ -11,6 +12,10 @@ export default class ChatDirectMessagesRoute extends DiscourseRoute {}beforeModel() {+ if (!this.currentUser) {+ return this.router.replaceWith("chat.channels");+ }+if (this.site.desktopView) {if (this.chatChannelsManager.directMessageChannels.length === 0) {// first time browsing chat and the preferred index is dms@@ -18,7 +23,7 @@ export default class ChatDirectMessagesRoute extends DiscourseRoute {} else {// there should be at least one dm channel// we can reroute using the last channel id- const id = this.currentUser.custom_fields.last_chat_channel_id;+ const id = this.currentUser?.custom_fields?.last_chat_channel_id;this.chatChannelsManager.find(id).then((c) => {return this.router.replaceWith("chat.channel", ...c.routeModels);});diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat/index.js b/plugins/chat/assets/javascripts/discourse/routes/chat/index.jsindex bf30cdab604..dfb065da3cb 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat/index.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat/index.js@@ -6,6 +6,7 @@ export default class ChatIndexRoute extends DiscourseRoute {@service chatChannelsManager;@service router;@service siteSettings;+ @service currentUser;get hasThreads() {if (!this.siteSettings.chat_threads_enabled) {@@ -51,6 +52,10 @@ export default class ChatIndexRoute extends DiscourseRoute {if (!this.isPublicChannelsEnabled && this.hasDirectMessages) {return this.router.replaceWith("chat.direct-messages");}+ if (!this.currentUser && this.isPublicChannelsEnabled) {+ return this.router.replaceWith("chat.channels");+ }+return this.router.replaceWith("chat.browse.open");}}diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat/new-message.js b/plugins/chat/assets/javascripts/discourse/routes/chat/new-message.jsindex 1a9990fa1cb..70f2f220225 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat/new-message.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat/new-message.js@@ -13,6 +13,12 @@ export default class ChatNewMessageRoute extends DiscourseRoute {@service router;async beforeModel(transition) {+ if (!this.currentUser) {+ transition.abort();+ this.router.transitionTo("chat.channels");+ return;+ }+const params = this.paramsFor(this.routeName);const recipients = params.recipients?.split(",");diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat/search.js b/plugins/chat/assets/javascripts/discourse/routes/chat/search.jsindex 1197592f55a..e0da141903f 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat/search.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat/search.js@@ -3,6 +3,7 @@ import DiscourseRoute from "discourse/routes/discourse";export default class ChatSearchRoute extends DiscourseRoute {@service chat;+ @service currentUser;@service router;@service siteSettings;@@ -13,6 +14,11 @@ export default class ChatSearchRoute extends DiscourseRoute {}redirect() {+ if (!this.currentUser) {+ this.router.transitionTo("chat.channels");+ return;+ }+if (!this.siteSettings.chat_search_enabled) {this.router.transitionTo("chat");}diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat/starred-channels.js b/plugins/chat/assets/javascripts/discourse/routes/chat/starred-channels.jsindex 822fad4af66..b3e784b3205 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat/starred-channels.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat/starred-channels.js@@ -4,6 +4,7 @@ import DiscourseRoute from "discourse/routes/discourse";export default class ChatStarredChannelsRoute extends DiscourseRoute {@service chat;@service chatChannelsManager;+ @service currentUser;@service router;@service site;@@ -12,6 +13,10 @@ export default class ChatStarredChannelsRoute extends DiscourseRoute {}async beforeModel() {+ if (!this.currentUser) {+ return this.router.replaceWith("chat.channels");+ }+if (this.site.desktopView) {const channel = this.chat.activeChannel;diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat/threads.js b/plugins/chat/assets/javascripts/discourse/routes/chat/threads.jsindex 789cc6c57a0..fe31b563a33 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat/threads.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat/threads.js@@ -4,6 +4,14 @@ import DiscourseRoute from "discourse/routes/discourse";export default class ChatChannelThreads extends DiscourseRoute {@service chat;@service chatStateManager;+ @service currentUser;+ @service router;++ beforeModel() {+ if (!this.currentUser) {+ return this.router.replaceWith("chat.channels");+ }+ }activate() {this.chat.activeChannel = null;diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-channels-manager.js b/plugins/chat/assets/javascripts/discourse/services/chat-channels-manager.jsindex cbe9b9a66fc..40571aebcdd 100644--- a/plugins/chat/assets/javascripts/discourse/services/chat-channels-manager.js+++ b/plugins/chat/assets/javascripts/discourse/services/chat-channels-manager.js@@ -3,6 +3,7 @@ import { trackedObject } from "@ember/reactive/collections";import Service, { service } from "@ember/service";import Promise from "rsvp";import { popupAjaxError } from "discourse/lib/ajax-error";+import { AUTO_GROUPS } from "discourse/lib/constants";import { debounce } from "discourse/lib/decorators";import ChatChannel from "discourse/plugins/chat/discourse/models/chat-channel";import ChatMessage from "discourse/plugins/chat/discourse/models/chat-message";@@ -108,6 +109,10 @@ export default class ChatChannelsManager extends Service {}async follow(model) {+ if (!this.currentUser || !model.currentUserMembership) {+ return model;+ }+this.chatSubscriptionsManager.startChannelSubscription(model);if (!model.currentUserMembership.following) {@@ -165,12 +170,26 @@ export default class ChatChannelsManager extends Service {);}+ get anonymousUserCanViewPublicChat() {+ return (+ !this.currentUser &&+ this.siteSettings.enable_public_channels &&+ (this.siteSettings.chat_allowed_groups || "")+ .toString()+ .split("|")+ .map((groupId) => parseInt(groupId, 10))+ .includes(AUTO_GROUPS.anonymous_users.id)+ );+ }+@cachedget publicMessageChannels() {return this.#sortChannelsByProperty(this.channels.filter((channel) =>- channel.isCategoryChannel && channel.currentUserMembership.following+ channel.isCategoryChannel &&+ (channel.currentUserMembership?.following ||+ this.anonymousUserCanViewPublicChat)),"slug");@@ -208,7 +227,8 @@ export default class ChatChannelsManager extends Service {this.channels.filter((channel) =>channel.isCategoryChannel &&- channel.currentUserMembership?.following &&+ (channel.currentUserMembership?.following ||+ this.anonymousUserCanViewPublicChat) &&!channel.currentUserMembership?.starred));@@ -390,7 +410,8 @@ export default class ChatChannelsManager extends Service {this.channels.filter((channel) =>channel.isCategoryChannel &&- channel.currentUserMembership?.following &&+ (channel.currentUserMembership?.following ||+ this.anonymousUserCanViewPublicChat) &&!channel.currentUserMembership?.starred),"slug"diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-subscriptions-manager.js b/plugins/chat/assets/javascripts/discourse/services/chat-subscriptions-manager.jsindex 529697a524d..1a6fc2042a6 100644--- a/plugins/chat/assets/javascripts/discourse/services/chat-subscriptions-manager.js+++ b/plugins/chat/assets/javascripts/discourse/services/chat-subscriptions-manager.js@@ -11,22 +11,26 @@ export default class ChatSubscriptionsManager extends Service {@service appEvents;@service chat;@service dialog;+ @service messageBus;@service router;_channelSubscriptions = new Set();- startChannelSubscription(channel) {+ startChannelSubscription(channel, { readOnly = false } = {}) {if (- channel.currentUserMembership.muted ||+ (!readOnly && channel.currentUserMembership?.muted) ||this._channelSubscriptions.has(channel.id)) {return;}this._channelSubscriptions.add(channel.id);- this._startChannelMentionsSubscription(channel);- if (!channel.isDirectMessageChannel) {+ if (this.currentUser && !readOnly) {+ this._startChannelMentionsSubscription(channel);+ }++ if (this.currentUser && !readOnly && !channel.isDirectMessageChannel) {this._startKickFromChannelSubscription(channel);}@@ -79,7 +83,7 @@ export default class ChatSubscriptionsManager extends Service {}_startChannelArchiveStatusSubscription(lastId) {- if (this.currentUser.admin) {+ if (this.currentUser?.admin) {this.messageBus.subscribe("/chat/channel-archive-status",this._onChannelArchiveStatusUpdate,@@ -89,7 +93,7 @@ export default class ChatSubscriptionsManager extends Service {}_stopChannelArchiveStatusSubscription() {- if (this.currentUser.admin) {+ if (this.currentUser?.admin) {this.messageBus.unsubscribe("/chat/channel-archive-status",this._onChannelArchiveStatusUpdate@@ -188,6 +192,11 @@ export default class ChatSubscriptionsManager extends Service {_onNewChannelMessage(busData) {this.chatChannelsManager.find(busData.channel_id).then((channel) => {channel.lastMessage = busData.message;++ if (!this.currentUser) {+ return;+ }+const user = busData.message.user;if (user.id === this.currentUser.id) {// User sent message, update tracking state to no unread@@ -231,11 +240,17 @@ export default class ChatSubscriptionsManager extends Service {return;}+ channel.lastMessage = busData.message;+channel.threadsManager.find(busData.channel_id, busData.thread_id).then((thread) => {thread.lastMessageId = busData.message.id;+ if (!this.currentUser) {+ return;+ }+if (busData.message.user.id === this.currentUser.id) {// Thread should no longer be considered unread.if (thread.currentUserMembership) {@@ -439,6 +454,14 @@ export default class ChatSubscriptionsManager extends Service {channel.meta = data.channel.meta;channel.currentUserMembership = data.channel.current_user_membership;+ if (!this.currentUser) {+ if (channel.isCategoryChannel) {+ this.startChannelSubscription(channel, { readOnly: true });+ }++ return;+ }+if (channel.isDirectMessageChannel &&!channel.currentUserMembership.followingdiff --git a/plugins/chat/assets/javascripts/discourse/services/chat.js b/plugins/chat/assets/javascripts/discourse/services/chat.jsindex 157aa663182..462de82d8b8 100644--- a/plugins/chat/assets/javascripts/discourse/services/chat.js+++ b/plugins/chat/assets/javascripts/discourse/services/chat.js@@ -5,6 +5,7 @@ import Service, { service } from "@ember/service";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import { uniqueItemsFromArray } from "discourse/lib/array-tools";+import { AUTO_GROUPS } from "discourse/lib/constants";import { bind } from "discourse/lib/decorators";import deprecated from "discourse/lib/deprecated";import EmbedMode from "discourse/lib/embed-mode";@@ -26,6 +27,7 @@ export default class Chat extends Service {@service chatStateManager;@service presence;@service router;+ @service siteSettings;@service chatChannelsManager;@service chatTrackingStateManager;@service chatPanePendingManager;@@ -54,8 +56,11 @@ export default class Chat extends Service {willDestroy() {super.willDestroy(...arguments);- if (this.userCanChat && !EmbedMode.enabled) {+ if (this.canSubscribeToChat && !EmbedMode.enabled) {this.chatSubscriptionsManager.stopChannelsSubscriptions();+ }++ if (this.userCanChat && !EmbedMode.enabled) {removeOnPresenceChange(this.onPresenceChangeCallback);}}@@ -67,6 +72,22 @@ export default class Chat extends Service {);}+ get anonymousUserCanViewPublicChat() {+ return (+ !this.currentUser &&+ this.siteSettings.enable_public_channels &&+ (this.siteSettings.chat_allowed_groups || "")+ .toString()+ .split("|")+ .map((groupId) => parseInt(groupId, 10))+ .includes(AUTO_GROUPS.anonymous_users.id)+ );+ }++ get canSubscribeToChat() {+ return this.userCanChat || this.anonymousUserCanViewPublicChat;+ }+get activeChannel() {return this._activeChannel;}@@ -170,7 +191,7 @@ export default class Chat extends Service {}}- async loadChannels() {+ async loadChannels({ subscribe = Boolean(this.currentUser) } = {}) {// We want to be able to call this method multiple times, but only// actually load the channels once. This is because we might call// this method before the chat is fully initialized, and we don't@@ -183,7 +204,7 @@ export default class Chat extends Service {if (!this.loadingChannels) {this.loadingChannels = new Promise((resolve) => {this.chatApi.listCurrentUserChannels().then((result) => {- this.setupWithPreloadedChannels(result);+ this.setupWithPreloadedChannels(result, { subscribe });this.chatStateManager.hasPreloadedChannels = true;resolve();});@@ -196,11 +217,21 @@ export default class Chat extends Service {}}- setupWithPreloadedChannels(channelsView) {- this.chatSubscriptionsManager.startChannelsSubscriptions(- channelsView.meta.message_bus_last_ids- );- this.presenceChannel.subscribe(channelsView.global_presence_channel_state);+ setupWithPreloadedChannels(+ channelsView,+ { subscribe = Boolean(this.currentUser) } = {}+ ) {+ if (subscribe && this.canSubscribeToChat) {+ this.chatSubscriptionsManager.startChannelsSubscriptions(+ channelsView.meta.message_bus_last_ids+ );+ }++ if (this.currentUser) {+ this.presenceChannel?.subscribe(+ channelsView.global_presence_channel_state+ );+ }this.chatChannelsManager.userHasThreads = channelsView.has_threads ?? false;@@ -215,12 +246,22 @@ export default class Chat extends Service {channelsView.unread_thread_overview[storedChannel.id];}- return this.chatChannelsManager.follow(storedChannel);+ if (this.currentUser) {+ return this.chatChannelsManager.follow(storedChannel);+ }++ if (subscribe && storedChannel.isCategoryChannel) {+ this.chatSubscriptionsManager.startChannelSubscription(storedChannel, {+ readOnly: true,+ });+ }});- this.chatTrackingStateManager.setupWithPreloadedState(- channelsView.tracking- );+ if (channelsView.tracking) {+ this.chatTrackingStateManager.setupWithPreloadedState(+ channelsView.tracking+ );+ }}updatePresence() {@@ -229,7 +270,7 @@ export default class Chat extends Service {return;}- if (this.currentUser.user_option?.hide_presence) {+ if (!this.currentUser || this.currentUser.user_option?.hide_presence) {return;}diff --git a/plugins/chat/assets/stylesheets/common/chat-channel-row.scss b/plugins/chat/assets/stylesheets/common/chat-channel-row.scssindex 8c462de4085..fb2c42650fe 100644--- a/plugins/chat/assets/stylesheets/common/chat-channel-row.scss+++ b/plugins/chat/assets/stylesheets/common/chat-channel-row.scss@@ -136,4 +136,13 @@display: none;margin-left: auto;}++ .full-page-chat & {+ padding: var(--space-2) var(--space-4);+ border-bottom: 1px solid var(--content-border-color);++ &:first-child {+ border-top: 1px solid var(--content-border-color);+ }+ }}diff --git a/plugins/chat/config/locales/server.en.yml b/plugins/chat/config/locales/server.en.ymlindex 52303e0e52a..2d66cad5d4a 100644--- a/plugins/chat/config/locales/server.en.yml+++ b/plugins/chat/config/locales/server.en.yml@@ -4,7 +4,7 @@ en: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_allowed_groups: "Users in these groups can chat, except anonymous users who can only view chat when added to this setting. 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."chat_dm_retention_days: "Chat messages in personal chat channels will be retained for this many days. Set to '0' to retain messages forever."chat_auto_silence_duration: "Number of minutes that users will be silenced for when they exceed the chat message creation rate limit. Set to '0' to disable auto-silencing."diff --git a/plugins/chat/config/settings.yml b/plugins/chat/config/settings.ymlindex 7250ab3d3bb..37442909d56 100644--- a/plugins/chat/config/settings.yml+++ b/plugins/chat/config/settings.yml@@ -19,6 +19,7 @@ chat:default: "1|2|11" # @admins, @moderators, @trust_level_1mandatory_values: "1|2" # @admins, @moderatorsallow_any: false+ client: truerefresh: truearea: "group_permissions"chat_threads_enabled:diff --git a/plugins/chat/lib/chat/channel_fetcher.rb b/plugins/chat/lib/chat/channel_fetcher.rbindex 75c64bb8306..a3ffc9abdd5 100644--- a/plugins/chat/lib/chat/channel_fetcher.rb+++ b/plugins/chat/lib/chat/channel_fetcher.rb@@ -13,9 +13,10 @@ module ChatMATCH_QUALITY_PARTIAL = 3def self.structured(guardian, include_threads: false)- memberships = Chat::ChannelMembershipManager.all_for_user(guardian.user)+ memberships = guardian.user ? Chat::ChannelMembershipManager.all_for_user(guardian.user) : []public_channels = secured_public_channels(guardian, status: :open, following: true)- direct_message_channels = secured_direct_message_channels(guardian.user.id, guardian)+ direct_message_channels =+ guardian.user ? secured_direct_message_channels(guardian.user.id, guardian) : []{public_channels:,direct_message_channels:,@@ -43,9 +44,15 @@ module Chatenddef self.generate_allowed_channel_ids_sql(guardian, exclude_dm_channels: false)+ category_scope =+ if guardian.anonymous? && Chat.anonymous_public_channel_access_allowed?+ Category.secured(guardian)+ else+ Category.post_create_allowed(guardian)+ end+category_channel_sql =- Category- .post_create_allowed(guardian)+ category_scope.joins("INNER JOIN chat_channels ON chat_channels.chatable_id = categories.id AND chat_channels.chatable_type = 'Category'",)@@ -54,7 +61,7 @@ module Chatdm_channel_sql = ""- if !exclude_dm_channels+ if !exclude_dm_channels && guardian.userdm_channel_sql = <<~SQLUNION@@ -191,7 +198,7 @@ module Chatchannels = channels.where("chat_channels.slug IN (:slugs)", slugs: options[:slugs])end- if options.key?(:following)+ if options.key?(:following) && guardian.userif options[:following]channels =channels.joins(:user_chat_channel_memberships).where(@@ -340,6 +347,8 @@ module Chatenddef self.tracking_state(channel_ids, guardian, include_threads: false)+ return Chat::TrackingStateReport.new if guardian.anonymous?+Chat::TrackingState.call(guardian:,params: {diff --git a/plugins/chat/lib/chat/engine.rb b/plugins/chat/lib/chat/engine.rbindex 1d92de0f19a..ced8449bb20 100644--- a/plugins/chat/lib/chat/engine.rb+++ b/plugins/chat/lib/chat/engine.rb@@ -27,6 +27,11 @@ module ChatSiteSetting.chat_allowed_groups_mapend+ def self.anonymous_public_channel_access_allowed?+ SiteSetting.enable_public_channels &&+ allowed_group_ids.include?(Group::AUTO_GROUPS[:anonymous_users])+ end+def self.message_onebox_templatereturn File.read(MESSAGE_ONEBOX_TEMPLATE_PATH) if Rails.env.development?diff --git a/plugins/chat/lib/chat/guardian_extensions.rb b/plugins/chat/lib/chat/guardian_extensions.rbindex 294fdf9261d..7067bb67436 100644--- a/plugins/chat/lib/chat/guardian_extensions.rb+++ b/plugins/chat/lib/chat/guardian_extensions.rb@@ -28,6 +28,8 @@ module Chatenddef can_create_chat_message?+ return false if anonymous?+!SpamRule::AutoSilence.prevent_posting?(@user)enddiff --git a/plugins/chat/spec/requests/chat/api/channel_messages_controller_spec.rb b/plugins/chat/spec/requests/chat/api/channel_messages_controller_spec.rbindex 14df3cb5ebf..80c629eb8c8 100644--- a/plugins/chat/spec/requests/chat/api/channel_messages_controller_spec.rb+++ b/plugins/chat/spec/requests/chat/api/channel_messages_controller_spec.rb@@ -24,6 +24,47 @@ RSpec.describe Chat::Api::ChannelMessagesController domessage_1.id,)end++ context "as anonymous user" do+ before do+ delete "/session/#{current_user.username}.json"+ SiteSetting.chat_allowed_groups =+ "#{Group::AUTO_GROUPS[:everyone]}|#{Group::AUTO_GROUPS[:anonymous_users]}"+ end++ it "returns messages for a public category channel" do+ thread = Fabricate(:chat_thread, channel:, original_message: message_1)+ thread_reply = Fabricate(:chat_message, chat_channel: channel, thread:)++ get "/chat/api/channels/#{channel.id}/messages"++ expect(response.status).to eq(200)+ expect(response.parsed_body["messages"].map { |message| message["id"] }).to eq(+ [message_1.id, thread_reply.id],+ )+ end++ it "returns an error for a direct message channel" do+ direct_message_channel =+ Fabricate(:direct_message_channel, group: true, users: Fabricate.times(3, :user))++ get "/chat/api/channels/#{direct_message_channel.id}/messages"++ expect(response.status).to eq(403)+ end++ it "skips bookmark queries" do+ queries =+ track_sql_queries do+ get "/chat/api/channels/#{channel.id}/messages"+ expect(response.status).to eq(200)+ end++ bookmark_queries = queries.select { |query| query.include?('FROM "bookmarks"') }++ expect(bookmark_queries).to be_empty+ end+ endendcontext "when params are invalid" dodiff --git a/plugins/chat/spec/requests/chat/api/channel_thread_messages_controller_spec.rb b/plugins/chat/spec/requests/chat/api/channel_thread_messages_controller_spec.rbindex 53594182659..56972fad5a2 100644--- a/plugins/chat/spec/requests/chat/api/channel_thread_messages_controller_spec.rb+++ b/plugins/chat/spec/requests/chat/api/channel_thread_messages_controller_spec.rb@@ -32,6 +32,23 @@ RSpec.describe Chat::Api::ChannelThreadMessagesController do]expect(thread_json).not_to have_key("original_message")end++ context "as anonymous user" do+ before do+ sign_out+ SiteSetting.chat_allowed_groups =+ "#{Group::AUTO_GROUPS[:everyone]}|#{Group::AUTO_GROUPS[:anonymous_users]}"+ end++ it "returns messages for a public category channel thread" do+ get "/chat/api/channels/#{thread.channel.id}/threads/#{thread.id}/messages"++ expect(response.status).to eq(200)+ expect(response.parsed_body["messages"].map { |message| message["id"] }).to eq(+ [thread.original_message.id, message_1.id],+ )+ end+ endendcontext "when thread doesn’t exist" dodiff --git a/plugins/chat/spec/requests/chat/api/channel_threads_controller_spec.rb b/plugins/chat/spec/requests/chat/api/channel_threads_controller_spec.rbindex b55baa1e4ac..8feef9c3bd6 100644--- a/plugins/chat/spec/requests/chat/api/channel_threads_controller_spec.rb+++ b/plugins/chat/spec/requests/chat/api/channel_threads_controller_spec.rb@@ -41,6 +41,21 @@ RSpec.describe Chat::Api::ChannelThreadsController doexpect(response.parsed_body["thread"]["id"]).to eq(thread.id)end+ context "as anonymous user" do+ before do+ sign_out+ SiteSetting.chat_allowed_groups =+ "#{Group::AUTO_GROUPS[:everyone]}|#{Group::AUTO_GROUPS[:anonymous_users]}"+ end++ it "returns a public category channel thread" do+ get "/chat/api/channels/#{thread.channel_id}/threads/#{thread.id}"++ expect(response.status).to eq(200)+ expect(response.parsed_body["thread"]["id"]).to eq(thread.id)+ end+ end+context "with user status enabled" dobefore { SiteSetting.enable_user_status = true }diff --git a/plugins/chat/spec/requests/chat/api/channels_controller_spec.rb b/plugins/chat/spec/requests/chat/api/channels_controller_spec.rbindex 685625cb12c..36fb16bb297 100644--- a/plugins/chat/spec/requests/chat/api/channels_controller_spec.rb+++ b/plugins/chat/spec/requests/chat/api/channels_controller_spec.rb@@ -13,6 +13,29 @@ RSpec.describe Chat::Api::ChannelsController doexpect(response.status).to eq(403)end++ context "when anonymous users can view public chat channels" do+ before do+ SiteSetting.chat_allowed_groups =+ "#{Group::AUTO_GROUPS[:everyone]}|#{Group::AUTO_GROUPS[:anonymous_users]}"+ end++ it "returns an error" do+ Fabricate(:category_channel)++ get "/chat/api/channels"++ expect(response.status).to eq(403)+ end++ it "does not return private category channels" do+ Fabricate(:private_category_channel)++ get "/chat/api/channels"++ expect(response.status).to eq(403)+ end+ endendcontext "as disallowed user" dodiff --git a/plugins/chat/spec/requests/chat/api/current_user_channels_spec.rb b/plugins/chat/spec/requests/chat/api/current_user_channels_spec.rbindex 5473f1410dd..ab2f5cd7272 100644--- a/plugins/chat/spec/requests/chat/api/current_user_channels_spec.rb+++ b/plugins/chat/spec/requests/chat/api/current_user_channels_spec.rb@@ -14,6 +14,50 @@ describe Chat::Api::CurrentUserChannelsController doget "/chat/api/me/channels"expect(response.status).to eq(403)end++ context "when anonymous users can view public chat channels" do+ before do+ SiteSetting.chat_allowed_groups =+ "#{Group::AUTO_GROUPS[:everyone]}|#{Group::AUTO_GROUPS[:anonymous_users]}"+ end++ it "returns public category channels without direct message channels" do+ public_channel = Fabricate(:category_channel)+ Fabricate(:chat_message, chat_channel: public_channel)+ Fabricate(:private_category_channel)+ Fabricate(:direct_message_channel)++ get "/chat/api/me/channels"++ expect(response.status).to eq(200)+ public_channels = response.parsed_body["public_channels"]++ expect(public_channels.map { |channel| channel["id"] }).to eq([public_channel.id])+ expect(public_channels.first["meta"]["can_join_chat_channel"]).to eq(true)+ expect(public_channels.first["meta"]["message_bus_last_ids"].keys).to eq(+ %w[channel_message_bus_last_id],+ )+ expect(response.parsed_body["direct_message_channels"]).to be_blank+ end++ it "omits global presence channel state" do+ Fabricate(:category_channel)++ get "/chat/api/me/channels"++ expect(response.status).to eq(200)+ expect(response.parsed_body).not_to have_key("global_presence_channel_state")+ end++ it "returns an error when public channels are disabled" do+ SiteSetting.enable_public_channels = false+ Fabricate(:category_channel)++ get "/chat/api/me/channels"++ expect(response.status).to eq(403)+ end+ endendcontext "as disallowed user" dodiff --git a/plugins/chat/spec/services/chat/list_channel_messages_spec.rb b/plugins/chat/spec/services/chat/list_channel_messages_spec.rbindex f2a9267954d..dd1d26fb9a2 100644--- a/plugins/chat/spec/services/chat/list_channel_messages_spec.rb+++ b/plugins/chat/spec/services/chat/list_channel_messages_spec.rb@@ -87,6 +87,18 @@ RSpec.describe Chat::ListChannelMessages doit { is_expected.to fail_a_policy(:can_view_channel) }end+ context "when anonymous users can view public chat but public channels are disabled" do+ let(:guardian) { Guardian.new(nil) }++ before do+ SiteSetting.chat_allowed_groups =+ "#{Group::AUTO_GROUPS[:everyone]}|#{Group::AUTO_GROUPS[:anonymous_users]}"+ SiteSetting.enable_public_channels = false+ end++ it { is_expected.to fail_a_policy(:can_view_channel) }+ end+context "when target message is not found" dolet(:optional_params) { { target_message_id: -1 } }diff --git a/plugins/chat/spec/services/chat/publisher_spec.rb b/plugins/chat/spec/services/chat/publisher_spec.rbindex 78fffa5a0bb..d0b98f32c45 100644--- a/plugins/chat/spec/services/chat/publisher_spec.rb+++ b/plugins/chat/spec/services/chat/publisher_spec.rb@@ -283,6 +283,41 @@ describe Chat::Publisher do).to eq(false)end+ it "allows anonymous clients when anonymous public chat access is enabled" do+ SiteSetting.chat_allowed_groups =+ "#{Group::AUTO_GROUPS[:everyone]}|#{Group::AUTO_GROUPS[:anonymous_users]}"++ messages =+ MessageBus.track_publish("/chat/#{channel.id}") do+ described_class.publish_new!(channel, message_1, staged_id)+ end++ expect(messages.first.group_ids).to eq(nil)+ expect(messages.first.user_ids).to eq(nil)+ expect(+ MessageBus::Client.new(client_id: "anonymous", message_bus: MessageBus).allowed?(+ messages.first,+ ),+ ).to eq(true)+ end++ it "does not allow anonymous clients when public channels are disabled" do+ SiteSetting.chat_allowed_groups =+ "#{Group::AUTO_GROUPS[:everyone]}|#{Group::AUTO_GROUPS[:anonymous_users]}"+ SiteSetting.enable_public_channels = false++ messages =+ MessageBus.track_publish("/chat/#{channel.id}") do+ described_class.publish_new!(channel, message_1, staged_id)+ end++ expect(+ MessageBus::Client.new(client_id: "anonymous", message_bus: MessageBus).allowed?(+ messages.first,+ ),+ ).to eq(false)+ end+it "publishes to trust level 0 when everyone is mapped to logged_in_users" doSiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]SiteSetting.granular_anonymous_and_logged_in_groups_permissions = truediff --git a/plugins/chat/spec/system/anonymous_public_channels_spec.rb b/plugins/chat/spec/system/anonymous_public_channels_spec.rbnew file mode 100644index 00000000000..a5d30390070--- /dev/null+++ b/plugins/chat/spec/system/anonymous_public_channels_spec.rb@@ -0,0 +1,91 @@+# frozen_string_literal: true++RSpec.describe "Anonymous public chat channels" do+ fab!(:public_channel) { Fabricate(:category_channel, name: "general") }+ fab!(:private_channel, :private_category_channel)+ fab!(:existing_message) do+ Fabricate(+ :chat_message,+ chat_channel: public_channel,+ message: "Existing public channel update",+ )+ end++ let(:chat_page) { PageObjects::Pages::Chat.new }+ let(:channel_page) { PageObjects::Pages::ChatChannel.new }+ let(:thread_page) { PageObjects::Pages::ChatThread.new }+ let(:chat_drawer_page) { PageObjects::Pages::ChatDrawer.new }+ let(:chat_sidebar_page) { PageObjects::Pages::ChatSidebar.new }+ let(:login_page) { PageObjects::Pages::Login.new }++ before do+ chat_system_bootstrap+ SiteSetting.chat_allowed_groups =+ "#{Group::AUTO_GROUPS[:everyone]}|#{Group::AUTO_GROUPS[:anonymous_users]}"+ end++ it "lets visitors read public channel activity without write or browse controls" do+ chat_page.visit_channels++ expect(chat_page).to have_public_channel(public_channel)+ expect(chat_page).to have_no_public_channel(private_channel)+ expect(chat_page).to have_no_browse_page_button++ chat_page.open_public_channel(public_channel)++ expect(channel_page.messages).to have_message(+ id: existing_message.id,+ text: "Existing public channel update",+ )+ expect(channel_page).to have_join_channel_button+ expect(channel_page).to have_no_composer+ expect(channel_page).to have_no_search_button+ expect(channel_page).to have_no_star_button+ expect(channel_page).to have_no_browse_all_link++ channel_page.join_channel++ expect(login_page).to be_open+ end++ it "lets visitors open public chat channels from the sidebar drawer" do+ SiteSetting.navigation_menu = "sidebar"++ visit("/")+ chat_page.prefers_drawer++ expect(chat_sidebar_page).to have_channel(public_channel)+ expect(chat_sidebar_page).to have_no_channel(private_channel)++ chat_sidebar_page.open_channel(public_channel)++ expect(chat_drawer_page).to have_open_channel(public_channel)++ chat_drawer_page.join_channel+ expect(login_page).to be_open+ end++ it "keeps visitors out of browse" do+ visit("/chat/browse/open")++ expect(page).to have_current_path("/chat/channels")+ end++ it "renders threaded public channels for visitors" do+ public_channel.update!(threading_enabled: true)++ chat_page.visit_channels++ expect(chat_page).to have_public_channel(public_channel)+ end++ it "lets visitors jump from a public thread to its original message" do+ public_channel.update!(threading_enabled: true)+ thread = Fabricate(:chat_thread, channel: public_channel, original_message: existing_message)++ chat_page.visit_thread(thread)+ thread_page.open_original_message++ expect(channel_page.messages).to have_message(id: thread.original_message.id, highlighted: true)+ end+enddiff --git a/plugins/chat/spec/system/page_objects/chat/chat.rb b/plugins/chat/spec/system/page_objects/chat/chat.rbindex 04269ef23dd..6c068063ac1 100644--- a/plugins/chat/spec/system/page_objects/chat/chat.rb+++ b/plugins/chat/spec/system/page_objects/chat/chat.rb@@ -69,6 +69,15 @@ module PageObjectshas_finished_loading?(with_preloaded_channels: with_preloaded_channels) if checkend+ def visit_channels+ visit("/chat/channels")+ end++ def open_public_channel(channel)+ find(public_channel_selector(channel)).click+ has_finished_loading?+ end+def visit_user_threadsvisit("/chat/threads")has_css?(".c-user-threads.--loaded")@@ -149,6 +158,18 @@ module PageObjectshas_css?(".direct-message-channels-section")end+ def has_public_channel?(channel)+ has_css?(public_channel_selector(channel))+ end++ def has_no_public_channel?(channel)+ has_no_css?(public_channel_selector(channel))+ end++ def has_no_browse_page_button?+ has_no_css?(".open-browse-page-btn")+ end+def has_add_member_button?has_css?(".c-channel-members__list-item.-add-member")end@@ -159,6 +180,10 @@ module PageObjectsprivate+ def public_channel_selector(channel)+ ".public-channels .chat-channel-row[data-chat-channel-id='#{channel.id}']"+ end+def drawer?(expectation:, channel_id: nil, expanded: true)selector = ".chat-drawer"selector += ".is-expanded" if expandeddiff --git a/plugins/chat/spec/system/page_objects/chat/chat_channel.rb b/plugins/chat/spec/system/page_objects/chat/chat_channel.rbindex 817ef943d9e..b3919d6b701 100644--- a/plugins/chat/spec/system/page_objects/chat/chat_channel.rb+++ b/plugins/chat/spec/system/page_objects/chat/chat_channel.rb@@ -48,6 +48,10 @@ module PageObjectsfind(".chat-composer.is-send-enabled .chat-composer-button.-send").clickend+ def join_channel+ find(".toggle-channel-membership-button.-join").click+ end+def message_by_id_selector(id)".chat-channel .chat-messages-container .chat-message-container[data-id=\"#{id}\"]"end@@ -231,6 +235,26 @@ module PageObjectshas_no_css?("#{thread_list_button_selector}.has-unreads")end+ def has_join_channel_button?+ has_css?(".toggle-channel-membership-button.-join")+ end++ def has_no_composer?+ has_no_css?(".chat-composer")+ end++ def has_no_search_button?+ has_no_css?(".c-navbar__filter")+ end++ def has_no_star_button?+ has_no_css?(".c-navbar__star-channel-button")+ end++ def has_no_browse_all_link?+ has_no_css?(".chat-channel-preview-card__browse-all")+ end+def thread_list_button_selector".c-navbar__threads-list-button"enddiff --git a/plugins/chat/spec/system/page_objects/chat/chat_thread.rb b/plugins/chat/spec/system/page_objects/chat/chat_thread.rbindex 6ab475d3134..d66a81b9119 100644--- a/plugins/chat/spec/system/page_objects/chat/chat_thread.rb+++ b/plugins/chat/spec/system/page_objects/chat/chat_thread.rb@@ -56,6 +56,10 @@ module PageObjectsheader.find(".c-navbar__close-thread-button").clickend+ def open_original_message+ find(".chat-message-info__original-message").click+ end+def has_back_link_to_thread_list?(channel)header.has_css?(".c-navbar__back-button[href='#{channel.relative_url + "/t"}']")enddiff --git a/plugins/chat/spec/system/page_objects/chat/components/channels_index.rb b/plugins/chat/spec/system/page_objects/chat/components/channels_index.rbindex f61b651ce86..edaa17cd964 100644--- a/plugins/chat/spec/system/page_objects/chat/components/channels_index.rb+++ b/plugins/chat/spec/system/page_objects/chat/components/channels_index.rb@@ -37,6 +37,10 @@ module PageObjectshas_no_css?(channel_row_selector(channel))end+ def has_no_browse_page_button?+ has_no_css?(".open-browse-page-btn")+ end+def has_unread_channel?(channel,count: nil,diff --git a/plugins/chat/spec/system/page_objects/chat_drawer/chat_drawer.rb b/plugins/chat/spec/system/page_objects/chat_drawer/chat_drawer.rbindex e6aee2628e1..91972a977cb 100644--- a/plugins/chat/spec/system/page_objects/chat_drawer/chat_drawer.rb+++ b/plugins/chat/spec/system/page_objects/chat_drawer/chat_drawer.rb@@ -9,6 +9,10 @@ module PageObjects@channels_index ||= ::PageObjects::Components::Chat::ChannelsIndex.new(VISIBLE_DRAWER)end+ def messages+ @messages ||= PageObjects::Components::Chat::Messages.new(VISIBLE_DRAWER)+ end+def browse@browse ||= ::PageObjects::Pages::ChatBrowse.new(".c-drawer-routes.--browse")end@@ -62,6 +66,10 @@ module PageObjectshas_no_css?(".chat-skeleton")end+ def join_channel+ find("#{VISIBLE_DRAWER} .toggle-channel-membership-button.-join").click+ end+def open_channel_row(channel)find("#{VISIBLE_DRAWER} .chat-channel-row[data-chat-channel-id='#{channel.id}']").clickhas_no_css?(".chat-skeleton")@@ -75,6 +83,10 @@ module PageObjectschannels_index.has_no_channel?(channel)end+ def has_no_browse_page_button?+ channels_index.has_no_browse_page_button?+ end+def has_channel_at_position?(channel, position)find("#{VISIBLE_DRAWER} .chat-channel-row:nth-child(#{position})[data-chat-channel-id='#{channel.id}']",diff --git a/plugins/chat/spec/system/page_objects/sidebar/chat_sidebar.rb b/plugins/chat/spec/system/page_objects/sidebar/chat_sidebar.rbindex 6403293979c..40421246ca1 100644--- a/plugins/chat/spec/system/page_objects/sidebar/chat_sidebar.rb+++ b/plugins/chat/spec/system/page_objects/sidebar/chat_sidebar.rb@@ -81,8 +81,12 @@ module PageObjectsselfend+ def has_channel?(channel)+ has_css?(".sidebar-section-link.channel-#{channel.id}")+ end+def has_no_channel?(channel)- has_no_css?(".sidebar-row.channel-#{channel.id}")+ has_no_css?(".sidebar-section-link.channel-#{channel.id}")enddef has_user_threads_section?diff --git a/plugins/chat/test/javascripts/components/chat-channel-preview-card-test.gjs b/plugins/chat/test/javascripts/components/chat-channel-preview-card-test.gjsindex 9fba19307ad..bb418e4dd19 100644--- a/plugins/chat/test/javascripts/components/chat-channel-preview-card-test.gjs+++ b/plugins/chat/test/javascripts/components/chat-channel-preview-card-test.gjs@@ -96,3 +96,22 @@ module("Component | ChatChannelPreviewCard", function (hooks) {.doesNotExist("it does not show the join channel button");});});++module("Component | ChatChannelPreviewCard | anonymous", function (hooks) {+ setupRenderingTest(hooks, { anonymous: true });++ hooks.beforeEach(function () {+ this.channel = new ChatFabricators(getOwner(this)).channel({+ chatable_type: "Category",+ meta: { can_join_chat_channel: true },+ });+ });++ test("browse all link is hidden", async function (assert) {+ await render(+ <template><ChatChannelPreviewCard @channel={{this.channel}} /></template>+ );++ assert.dom(".chat-channel-preview-card__browse-all").doesNotExist();+ });+});diff --git a/plugins/chat/test/javascripts/components/toggle-channel-membership-button-test.gjs b/plugins/chat/test/javascripts/components/toggle-channel-membership-button-test.gjsnew file mode 100644index 00000000000..ee3de5ddc26--- /dev/null+++ b/plugins/chat/test/javascripts/components/toggle-channel-membership-button-test.gjs@@ -0,0 +1,45 @@+import { getOwner } from "@ember/owner";+import { click, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import ToggleChannelMembershipButton from "discourse/plugins/chat/discourse/components/toggle-channel-membership-button";+import ChatFabricators from "discourse/plugins/chat/discourse/lib/fabricators";++module("Component | ToggleChannelMembershipButton", function (hooks) {+ setupRenderingTest(hooks, { anonymous: true });++ hooks.beforeEach(function () {+ this.showLogin = sinon.stub();+ this.chatStateManager = this.owner.lookup("service:chat-state-manager");+ this.chatStateManager.isDrawerActive = true;+ sinon.stub(this.chatStateManager, "didCloseDrawer");++ this.owner.register(+ "route:application",+ { send: this.showLogin },+ { instantiate: false }+ );++ this.channel = new ChatFabricators(getOwner(this)).channel({+ chatable_type: "Category",+ current_user_membership: null,+ meta: { can_join_chat_channel: true },+ });+ });++ test("anonymous users are sent to login when joining a channel", async function (assert) {+ await render(+ <template>+ <ToggleChannelMembershipButton @channel={{this.channel}} />+ </template>+ );++ assert.dom(".toggle-channel-membership-button.-join").exists();++ await click(".toggle-channel-membership-button.-join");++ assert.true(this.chatStateManager.didCloseDrawer.calledOnce);+ assert.true(this.showLogin.calledWith("showLogin"));+ });+});diff --git a/plugins/chat/test/javascripts/unit/models/chat-channel-test.js b/plugins/chat/test/javascripts/unit/models/chat-channel-test.jsindex 9935e7355f9..9440ed5c064 100644--- a/plugins/chat/test/javascripts/unit/models/chat-channel-test.js+++ b/plugins/chat/test/javascripts/unit/models/chat-channel-test.js@@ -35,6 +35,15 @@ module("Unit | Models | chat-channel", function (hooks) {assert.strictEqual(channel.unreadThreadsCountSinceLastViewed, 0);});+ test("returns 0 when current user membership is missing", function (assert) {+ const channel = new ChatFabricators(getOwner(this)).channel();+ channel.threadingEnabled = true;+ channel.currentUserMembership = null;+ channel.threadsManager.markThreadUnread(1, new Date());++ assert.strictEqual(channel.unreadThreadsCountSinceLastViewed, 0);+ });+test("returns count of threads since last viewed when threading is enabled", function (assert) {const channel = new ChatFabricators(getOwner(this)).channel();channel.threadingEnabled = true;diff --git a/plugins/chat/test/javascripts/unit/routes/chat-anonymous-test.js b/plugins/chat/test/javascripts/unit/routes/chat-anonymous-test.jsnew file mode 100644index 00000000000..c228dcaa609--- /dev/null+++ b/plugins/chat/test/javascripts/unit/routes/chat-anonymous-test.js@@ -0,0 +1,63 @@+import { getOwner } from "@ember/owner";+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import sinon from "sinon";++module("Unit | Routes | chat | anonymous", function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ this.testOwner = getOwner(this);+ });++ hooks.afterEach(function () {+ sinon.restore();+ });++ test("direct messages redirects anonymous users to public channels", function (assert) {+ const route = this.testOwner.lookup("route:chat.direct-messages");+ sinon.stub(route.router, "replaceWith");++ route.beforeModel();++ assert.true(route.router.replaceWith.calledWith("chat.channels"));+ });++ test("new message redirects anonymous users to public channels", async function (assert) {+ const route = this.testOwner.lookup("route:chat.new-message");+ const transition = { abort: sinon.stub() };+ sinon.stub(route.router, "transitionTo");++ await route.beforeModel(transition);++ assert.true(transition.abort.calledOnce);+ assert.true(route.router.transitionTo.calledWith("chat.channels"));+ });++ test("search redirects anonymous users to public channels", function (assert) {+ const route = this.testOwner.lookup("route:chat.search");+ sinon.stub(route.router, "transitionTo");++ route.redirect();++ assert.true(route.router.transitionTo.calledWith("chat.channels"));+ });++ test("starred channels redirects anonymous users to public channels", async function (assert) {+ const route = this.testOwner.lookup("route:chat.starred-channels");+ sinon.stub(route.router, "replaceWith");++ await route.beforeModel();++ assert.true(route.router.replaceWith.calledWith("chat.channels"));+ });++ test("threads redirects anonymous users to public channels", function (assert) {+ const route = this.testOwner.lookup("route:chat.threads");+ sinon.stub(route.router, "replaceWith");++ route.beforeModel();++ assert.true(route.router.replaceWith.calledWith("chat.channels"));+ });+});diff --git a/plugins/chat/test/javascripts/unit/services/chat-anonymous-test.js b/plugins/chat/test/javascripts/unit/services/chat-anonymous-test.jsnew file mode 100644index 00000000000..97d04182ca8--- /dev/null+++ b/plugins/chat/test/javascripts/unit/services/chat-anonymous-test.js@@ -0,0 +1,67 @@+import { getOwner } from "@ember/owner";+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import sinon from "sinon";+import { AUTO_GROUPS } from "discourse/lib/constants";+import ChatFabricators from "discourse/plugins/chat/discourse/lib/fabricators";++module("Unit | Service | chat | anonymous", function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ const owner = getOwner(this);++ this.chat = owner.lookup("service:chat");+ this.chatSubscriptionsManager = owner.lookup(+ "service:chat-subscriptions-manager"+ );+ this.siteSettings = owner.lookup("service:site-settings");+ this.fabricators = new ChatFabricators(owner);++ this.siteSettings.chat_allowed_groups =+ AUTO_GROUPS.anonymous_users.id.toString();++ sinon.stub(this.chatSubscriptionsManager, "startChannelsSubscriptions");+ sinon.stub(this.chatSubscriptionsManager, "startChannelSubscription");+ });++ hooks.afterEach(function () {+ sinon.restore();+ });++ test("setupWithPreloadedChannels skips realtime subscriptions by default", function (assert) {+ const channel = this.fabricators.channel({+ meta: {+ message_bus_last_ids: {+ channel_message_bus_last_id: 1,+ },+ },+ });++ this.chat.setupWithPreloadedChannels({+ public_channels: [channel],+ direct_message_channels: [],+ has_threads: false,+ meta: {+ message_bus_last_ids: {+ channel_metadata: 1,+ channel_edits: 1,+ channel_status: 1,+ },+ },+ tracking: {+ channel_tracking: {},+ thread_tracking: {},+ },+ });++ assert.false(+ this.chatSubscriptionsManager.startChannelsSubscriptions.called,+ "global channel subscriptions are skipped"+ );+ assert.false(+ this.chatSubscriptionsManager.startChannelSubscription.called,+ "per-channel subscriptions are skipped"+ );+ });+});diff --git a/plugins/chat/test/javascripts/unit/services/chat-subscriptions-manager-test.js b/plugins/chat/test/javascripts/unit/services/chat-subscriptions-manager-test.jsnew file mode 100644index 00000000000..35a18354eb8--- /dev/null+++ b/plugins/chat/test/javascripts/unit/services/chat-subscriptions-manager-test.js@@ -0,0 +1,71 @@+import { getOwner } from "@ember/owner";+import { settled } from "@ember/test-helpers";+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import sinon from "sinon";+import ChatFabricators from "discourse/plugins/chat/discourse/lib/fabricators";++module("Unit | Service | chat-subscriptions-manager", function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ const owner = getOwner(this);++ this.subject = owner.lookup("service:chat-subscriptions-manager");+ this.chatChannelsManager = owner.lookup("service:chat-channels-manager");+ this.fabricators = new ChatFabricators(owner);++ const messageBus = owner.lookup("service:message-bus");+ sinon.stub(messageBus, "subscribe");+ sinon.stub(messageBus, "unsubscribe");+ });++ hooks.afterEach(function () {+ sinon.restore();+ });++ test("read-only channel subscriptions skip user-scoped streams", function (assert) {+ const channel = this.fabricators.channel({+ id: 44,+ meta: {+ message_bus_last_ids: {+ new_messages: 3,+ new_mentions: 4,+ kick: 5,+ },+ },+ });++ this.subject.startChannelSubscription(channel, { readOnly: true });++ assert.deepEqual(this.subject.messageBus.subscribe.args, [+ ["/chat/44/new-messages", this.subject._onNewMessages, 3],+ ]);+ });++ test("new message updates public channel activity for anonymous users", async function (assert) {+ const channel = {+ id: 45,+ lastMessage: null,+ threadingEnabled: false,+ tracking: { unreadCount: 0 },+ };+ const message = {+ id: 99,+ user: { id: 2, username: "other_user" },+ };++ sinon.stub(this.chatChannelsManager, "find").resolves(channel);++ this.subject._onNewMessages({+ type: "channel",+ channel_id: channel.id,+ message,+ });++ await settled();++ assert.strictEqual(channel.lastMessage, message);+ assert.strictEqual(channel.tracking.unreadCount, 0);+ });+});