A platform for community discussion. Free, open, simple.
DEV: start glimmer-ification and optimisations of chat plugin (#19531)
Joffrey JAFFEUXd2e24f95699e
diff --git a/app/assets/javascripts/discourse/app/initializers/subscribe-user-notifications.js b/app/assets/javascripts/discourse/app/initializers/subscribe-user-notifications.jsindex 94fb9385ce5..e963f2fa003 100644--- a/app/assets/javascripts/discourse/app/initializers/subscribe-user-notifications.js+++ b/app/assets/javascripts/discourse/app/initializers/subscribe-user-notifications.js@@ -58,7 +58,11 @@ export default {this.onDoNotDisturb);- this.messageBus.subscribe(`/user-status`, this.onUserStatus);+ this.messageBus.subscribe(+ `/user-status`,+ this.onUserStatus,+ this.currentUser.status?.message_bus_last_id+ );this.messageBus.subscribe("/categories", this.onCategories);diff --git a/app/serializers/user_status_serializer.rb b/app/serializers/user_status_serializer.rbindex 2866398d1b2..aba929520c2 100644--- a/app/serializers/user_status_serializer.rb+++ b/app/serializers/user_status_serializer.rb@@ -1,5 +1,9 @@# frozen_string_literal: trueclass UserStatusSerializer < ApplicationSerializer- attributes :description, :emoji, :ends_at+ attributes :description, :emoji, :ends_at, :message_bus_last_id++ def message_bus_last_id+ MessageBus.last_id("/user-status")+ endenddiff --git a/plugins/chat/app/controllers/api/chat_channel_memberships_controller.rb b/plugins/chat/app/controllers/api/chat_channel_memberships_controller.rbdeleted file mode 100644index 727811c9ca6..00000000000--- a/plugins/chat/app/controllers/api/chat_channel_memberships_controller.rb+++ /dev/null@@ -1,20 +0,0 @@-# frozen_string_literal: true--class Chat::Api::ChatChannelMembershipsController < Chat::Api::ChatChannelsController- def index- channel = find_chat_channel-- offset = (params[:offset] || 0).to_i- limit = (params[:limit] || 50).to_i.clamp(1, 50)-- memberships =- ChatChannelMembershipsQuery.call(- channel,- offset: offset,- limit: limit,- username: params[:username],- )-- render_serialized(memberships, UserChatChannelMembershipSerializer, root: false)- end-enddiff --git a/plugins/chat/app/controllers/api/chat_channel_notifications_settings_controller.rb b/plugins/chat/app/controllers/api/chat_channel_notifications_settings_controller.rbdeleted file mode 100644index 57c0055424d..00000000000--- a/plugins/chat/app/controllers/api/chat_channel_notifications_settings_controller.rb+++ /dev/null@@ -1,12 +0,0 @@-# frozen_string_literal: true--MEMBERSHIP_EDITABLE_PARAMS = %i[muted desktop_notification_level mobile_notification_level]--class Chat::Api::ChatChannelNotificationsSettingsController < Chat::Api::ChatChannelsController- def update- settings_params = params.permit(MEMBERSHIP_EDITABLE_PARAMS)- membership = find_membership- membership.update!(settings_params.to_h)- render_serialized(membership, UserChatChannelMembershipSerializer, root: false)- end-enddiff --git a/plugins/chat/app/controllers/api/chat_channels_archives_controller.rb b/plugins/chat/app/controllers/api/chat_channels_archives_controller.rbnew file mode 100644index 00000000000..759348ef4ec--- /dev/null+++ b/plugins/chat/app/controllers/api/chat_channels_archives_controller.rb@@ -0,0 +1,42 @@+# frozen_string_literal: true++class Chat::Api::ChatChannelsArchivesController < Chat::Api::ChatChannelsController+ def create+ existing_archive = channel_from_params.chat_channel_archive++ if existing_archive.present?+ guardian.ensure_can_change_channel_status!(channel_from_params, :archived)+ raise Discourse::InvalidAccess if !existing_archive.failed?+ Chat::ChatChannelArchiveService.retry_archive_process(chat_channel: channel_from_params)+ else+ archive_params =+ params+ .require(:archive)+ .tap do |ca|+ ca.require(:type)+ ca.permit(:title, :topic_id, :category_id, tags: [])+ end++ new_topic = archive_params[:type] == "new_topic"+ raise Discourse::InvalidParameters if new_topic && archive_params[:title].blank?+ raise Discourse::InvalidParameters if !new_topic && archive_params[:topic_id].blank?++ if !guardian.can_change_channel_status?(channel_from_params, :read_only)+ raise Discourse::InvalidAccess.new(I18n.t("chat.errors.channel_cannot_be_archived"))+ end++ Chat::ChatChannelArchiveService.begin_archive_process(+ chat_channel: channel_from_params,+ acting_user: current_user,+ topic_params: {+ topic_id: archive_params[:topic_id],+ topic_title: archive_params[:title],+ category_id: archive_params[:category_id],+ tags: archive_params[:tags],+ },+ )+ end++ render json: success_json+ end+enddiff --git a/plugins/chat/app/controllers/api/chat_channels_controller.rb b/plugins/chat/app/controllers/api/chat_channels_controller.rbindex 6658b381eb7..9e70a95d015 100644--- a/plugins/chat/app/controllers/api/chat_channels_controller.rb+++ b/plugins/chat/app/controllers/api/chat_channels_controller.rb@@ -1,7 +1,7 @@# frozen_string_literal: true-CHAT_CHANNEL_EDITABLE_PARAMS = %i[name description]-CATEGORY_CHAT_CHANNEL_EDITABLE_PARAMS = %i[auto_join_users allow_channel_wide_mentions]+CHANNEL_EDITABLE_PARAMS = %i[name description]+CATEGORY_CHANNEL_EDITABLE_PARAMS = %i[auto_join_users allow_channel_wide_mentions]class Chat::Api::ChatChannelsController < Chat::Apidef index@@ -9,6 +9,9 @@ class Chat::Api::ChatChannelsController < Chat::Apiparams.permit(:filter, :limit, :offset),).symbolize_keys!+ options[:offset] = options[:offset].to_i+ options[:limit] = (options[:limit] || 25).to_i+memberships = Chat::ChatChannelMembershipManager.all_for_user(current_user)channels = Chat::ChatChannelFetcher.secured_public_channels(guardian, memberships, options)@@ -20,73 +23,166 @@ class Chat::Api::ChatChannelsController < Chat::Apimembership: memberships.find { |membership| membership.chat_channel_id == channel.id },)end- render json: serialized_channels, root: false++ pagination_options =+ options.slice(:offset, :limit, :filter).merge(offset: options[:offset] + options[:limit])+ pagination_params = pagination_options.map { |k, v| "#{k}=#{v}" }.join("&")+ render json: serialized_channels,+ root: "channels",+ meta: {+ load_more_url: "/chat/api/channels?#{pagination_params}",+ }+ end++ def destroy+ confirmation = params.require(:channel).require(:name_confirmation)&.downcase+ guardian.ensure_can_delete_chat_channel!++ if channel_from_params.title(current_user).downcase != confirmation+ raise Discourse::InvalidParameters.new(:name_confirmation)+ end++ begin+ ChatChannel.transaction do+ channel_from_params.trash!(current_user)+ StaffActionLogger.new(current_user).log_custom(+ "chat_channel_delete",+ {+ chat_channel_id: channel_from_params.id,+ chat_channel_name: channel_from_params.title(current_user),+ },+ )+ end+ rescue ActiveRecord::Rollback+ return render_json_error(I18n.t("chat.errors.delete_channel_failed"))+ end++ Jobs.enqueue(:chat_channel_delete, { chat_channel_id: channel_from_params.id })+ render json: success_json+ end++ def create+ channel_params =+ params.require(:channel).permit(:chatable_id, :name, :description, :auto_join_users)++ guardian.ensure_can_create_chat_channel!+ if channel_params[:name].length > SiteSetting.max_topic_title_length+ raise Discourse::InvalidParameters.new(:name)+ end++ if ChatChannel.exists?(+ chatable_type: "Category",+ chatable_id: channel_params[:chatable_id],+ name: channel_params[:name],+ )+ raise Discourse::InvalidParameters.new(I18n.t("chat.errors.channel_exists_for_category"))+ end++ chatable = Category.find_by(id: channel_params[:chatable_id])+ raise Discourse::NotFound unless chatable++ auto_join_users =+ ActiveRecord::Type::Boolean.new.deserialize(channel_params[:auto_join_users]) || false++ channel =+ chatable.create_chat_channel!(+ name: channel_params[:name],+ description: channel_params[:description],+ user_count: 1,+ auto_join_users: auto_join_users,+ )++ channel.user_chat_channel_memberships.create!(user: current_user, following: true)++ if channel.auto_join_users+ Chat::ChatChannelMembershipManager.new(channel).enforce_automatic_channel_memberships+ end++ render_serialized(+ channel,+ ChatChannelSerializer,+ membership: channel.membership_for(current_user),+ root: "channel",+ )+ end++ def show+ render_serialized(+ channel_from_params,+ ChatChannelSerializer,+ membership: channel_from_params.membership_for(current_user),+ root: "channel",+ )enddef updateguardian.ensure_can_edit_chat_channel!- chat_channel = find_chat_channel-- if chat_channel.direct_message_channel?+ if channel_from_params.direct_message_channel?raise Discourse::InvalidParameters.new(I18n.t("chat.errors.cant_update_direct_message_channel"),)end- params_to_edit = editable_params(params, chat_channel)+ params_to_edit = editable_params(params, channel_from_params)params_to_edit.each { |k, v| params_to_edit[k] = nil if params_to_edit[k].blank? }if ActiveRecord::Type::Boolean.new.deserialize(params_to_edit[:auto_join_users])- auto_join_limiter(chat_channel).performed!+ auto_join_limiter(channel_from_params).performed!end- chat_channel.update!(params_to_edit)+ channel_from_params.update!(params_to_edit)- ChatPublisher.publish_chat_channel_edit(chat_channel, current_user)+ ChatPublisher.publish_chat_channel_edit(channel_from_params, current_user)- if chat_channel.category_channel? && chat_channel.auto_join_users- Chat::ChatChannelMembershipManager.new(chat_channel).enforce_automatic_channel_memberships+ if channel_from_params.category_channel? && channel_from_params.auto_join_users+ Chat::ChatChannelMembershipManager.new(+ channel_from_params,+ ).enforce_automatic_channel_membershipsendrender_serialized(- chat_channel,+ channel_from_params,ChatChannelSerializer,- root: false,- membership: chat_channel.membership_for(current_user),+ root: "channel",+ membership: channel_from_params.membership_for(current_user),)endprivate- def find_chat_channel- chat_channel = ChatChannel.find(params.require(:chat_channel_id))- guardian.ensure_can_join_chat_channel!(chat_channel)- chat_channel+ def channel_from_params+ @channel ||=+ begin+ channel = ChatChannel.find(params.require(:channel_id))+ guardian.ensure_can_preview_chat_channel!(channel)+ channel+ endend- def find_membership- chat_channel = find_chat_channel- membership = Chat::ChatChannelMembershipManager.new(chat_channel).find_for_user(current_user)- raise Discourse::NotFound if membership.blank?- membership+ def membership_from_params+ @membership ||=+ begin+ membership =+ Chat::ChatChannelMembershipManager.new(channel_from_params).find_for_user(current_user)+ raise Discourse::NotFound if membership.blank?+ membership+ endend- def auto_join_limiter(chat_channel)+ def auto_join_limiter(channel)RateLimiter.new(current_user,- "auto_join_users_channel_#{chat_channel.id}",+ "auto_join_users_channel_#{channel.id}",1,3.minutes,apply_limit_to_staff: true,)end- def editable_params(params, chat_channel)- permitted_params = CHAT_CHANNEL_EDITABLE_PARAMS-- permitted_params += CATEGORY_CHAT_CHANNEL_EDITABLE_PARAMS if chat_channel.category_channel?-- params.permit(*permitted_params)+ def editable_params(params, channel)+ permitted_params = CHANNEL_EDITABLE_PARAMS+ permitted_params += CATEGORY_CHANNEL_EDITABLE_PARAMS if channel.category_channel?+ params.require(:channel).permit(*permitted_params)endenddiff --git a/plugins/chat/app/controllers/api/chat_channels_current_user_membership_controller.rb b/plugins/chat/app/controllers/api/chat_channels_current_user_membership_controller.rbnew file mode 100644index 00000000000..91422f9d673--- /dev/null+++ b/plugins/chat/app/controllers/api/chat_channels_current_user_membership_controller.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++class Chat::Api::ChatChannelsCurrentUserMembershipController < Chat::Api::ChatChannelsController+ def create+ guardian.ensure_can_join_chat_channel!(channel_from_params)++ render_serialized(+ channel_from_params.add(current_user),+ UserChatChannelMembershipSerializer,+ root: "membership",+ )+ end++ def destroy+ render_serialized(+ channel_from_params.remove(current_user),+ UserChatChannelMembershipSerializer,+ root: "membership",+ )+ end+enddiff --git a/plugins/chat/app/controllers/api/chat_channels_current_user_notifications_settings_controller.rb b/plugins/chat/app/controllers/api/chat_channels_current_user_notifications_settings_controller.rbnew file mode 100644index 00000000000..d9a8f4ac57e--- /dev/null+++ b/plugins/chat/app/controllers/api/chat_channels_current_user_notifications_settings_controller.rb@@ -0,0 +1,15 @@+# frozen_string_literal: true++MEMBERSHIP_EDITABLE_PARAMS = %i[muted desktop_notification_level mobile_notification_level]++class Chat::Api::ChatChannelsCurrentUserNotificationsSettingsController < Chat::Api::ChatChannelsController+ def update+ settings_params = params.require(:notifications_settings).permit(MEMBERSHIP_EDITABLE_PARAMS)+ membership_from_params.update!(settings_params.to_h)+ render_serialized(+ membership_from_params,+ UserChatChannelMembershipSerializer,+ root: "membership",+ )+ end+enddiff --git a/plugins/chat/app/controllers/api/chat_channels_memberships_controller.rb b/plugins/chat/app/controllers/api/chat_channels_memberships_controller.rbnew file mode 100644index 00000000000..c50a30735e7--- /dev/null+++ b/plugins/chat/app/controllers/api/chat_channels_memberships_controller.rb@@ -0,0 +1,29 @@+# frozen_string_literal: true++class Chat::Api::ChatChannelsMembershipsController < Chat::Api::ChatChannelsController+ def index+ params.permit(:username, :offset, :limit)++ offset = params[:offset].to_i+ limit = (params[:limit] || 50).to_i.clamp(1, 50)++ memberships =+ ChatChannelMembershipsQuery.call(+ channel_from_params,+ offset: offset,+ limit: limit,+ username: params[:username],+ )++ render_serialized(+ memberships,+ UserChatChannelMembershipSerializer,+ root: "memberships",+ meta: {+ total_rows: channel_from_params.user_count,+ load_more_url:+ "/chat/api/channels/#{channel_from_params.id}/memberships?offset=#{offset + limit}&limit=#{limit}&username=#{params[:username]}",+ },+ )+ end+enddiff --git a/plugins/chat/app/controllers/api/chat_channels_messages_moves_controller.rb b/plugins/chat/app/controllers/api/chat_channels_messages_moves_controller.rbnew file mode 100644index 00000000000..d0d3ff1777f--- /dev/null+++ b/plugins/chat/app/controllers/api/chat_channels_messages_moves_controller.rb@@ -0,0 +1,35 @@+# frozen_string_literal: true++class Chat::Api::ChatChannelsMessagesMovesController < Chat::Api::ChatChannelsController+ def create+ move_params = params.require(:move)+ move_params.require(:message_ids)+ move_params.require(:destination_channel_id)++ raise Discourse::InvalidAccess if !guardian.can_move_chat_messages?(channel_from_params)+ destination_channel =+ Chat::ChatChannelFetcher.find_with_access_check(+ move_params[:destination_channel_id],+ guardian,+ )++ begin+ message_ids = move_params[:message_ids].map(&:to_i)+ moved_messages =+ Chat::MessageMover.new(+ acting_user: current_user,+ source_channel: channel_from_params,+ message_ids: message_ids,+ ).move_to_channel(destination_channel)+ rescue Chat::MessageMover::NoMessagesFound, Chat::MessageMover::InvalidChannel => err+ return render_json_error(err.message)+ end++ render json:+ success_json.merge(+ destination_channel_id: destination_channel.id,+ destination_channel_title: destination_channel.title(current_user),+ first_moved_message_id: moved_messages.first.id,+ )+ end+enddiff --git a/plugins/chat/app/controllers/api/chat_channels_status_controller.rb b/plugins/chat/app/controllers/api/chat_channels_status_controller.rbnew file mode 100644index 00000000000..78b1ac3f2cb--- /dev/null+++ b/plugins/chat/app/controllers/api/chat_channels_status_controller.rb@@ -0,0 +1,18 @@+# frozen_string_literal: true++class Chat::Api::ChatChannelsStatusController < Chat::Api::ChatChannelsController+ def update+ status = params.require(:status)++ # we only want to use this endpoint for open/closed status changes,+ # the others are more "special" and are handled by the archive endpoint+ if !ChatChannel.statuses.keys.include?(status) || status == "read_only" || status == "archive"+ raise Discourse::InvalidParameters+ end++ guardian.ensure_can_change_channel_status!(channel_from_params, status.to_sym)+ channel_from_params.public_send("#{status}!", current_user)++ render_serialized(channel_from_params, ChatChannelSerializer, root: "channel")+ end+enddiff --git a/plugins/chat/app/controllers/api/chat_chatables_controller.rb b/plugins/chat/app/controllers/api/chat_chatables_controller.rbnew file mode 100644index 00000000000..9eaec32b89b--- /dev/null+++ b/plugins/chat/app/controllers/api/chat_chatables_controller.rb@@ -0,0 +1,82 @@+# frozen_string_literal: true++class Chat::Api::ChatChatablesController < Chat::Api+ def index+ params.require(:filter)+ filter = params[:filter].downcase++ memberships = Chat::ChatChannelMembershipManager.all_for_user(current_user)+ public_channels =+ Chat::ChatChannelFetcher.secured_public_channels(+ guardian,+ memberships,+ filter: filter,+ status: :open,+ )++ users = User.joins(:user_option).where.not(id: current_user.id)+ if !Chat.allowed_group_ids.include?(Group::AUTO_GROUPS[:everyone])+ users =+ users+ .joins(:groups)+ .where(groups: { id: Chat.allowed_group_ids })+ .or(users.joins(:groups).staff)+ end++ users = users.where(user_option: { chat_enabled: true })+ like_filter = "%#{filter}%"+ if SiteSetting.prioritize_username_in_ux || !SiteSetting.enable_names+ users = users.where("users.username_lower ILIKE ?", like_filter)+ else+ users =+ users.where(+ "LOWER(users.name) ILIKE ? OR users.username_lower ILIKE ?",+ like_filter,+ like_filter,+ )+ end++ users = users.limit(25).uniq++ direct_message_channels =+ if users.count > 0+ # FIXME: investigate the cost of this query+ ChatChannel+ .includes(chatable: :users)+ .joins(direct_message: :direct_message_users)+ .group(1)+ .having(+ "ARRAY[?] <@ ARRAY_AGG(user_id) AND ARRAY[?] && ARRAY_AGG(user_id)",+ [current_user.id],+ users.map(&:id),+ )+ else+ []+ end++ user_ids_with_channel = []+ direct_message_channels.each do |dm_channel|+ user_ids = dm_channel.chatable.users.map(&:id)+ user_ids_with_channel.concat(user_ids) if user_ids.count < 3+ end++ users_without_channel = users.filter { |u| !user_ids_with_channel.include?(u.id) }++ if current_user.username.downcase.start_with?(filter)+ # We filtered out the current user for the query earlier, but check to see+ # if they should be included, and add.+ users_without_channel << current_user+ end++ render_serialized(+ {+ public_channels: public_channels,+ direct_message_channels: direct_message_channels,+ users: users_without_channel,+ memberships: memberships,+ },+ ChatChannelSearchSerializer,+ root: false,+ )+ end+enddiff --git a/plugins/chat/app/controllers/api/chat_current_user_channels_controller.rb b/plugins/chat/app/controllers/api/chat_current_user_channels_controller.rbnew file mode 100644index 00000000000..ecc01163606--- /dev/null+++ b/plugins/chat/app/controllers/api/chat_current_user_channels_controller.rb@@ -0,0 +1,8 @@+# frozen_string_literal: true++class Chat::Api::ChatCurrentUserChannelsController < Chat::Api+ def index+ structured = Chat::ChatChannelFetcher.structured(guardian)+ render_serialized(structured, ChatChannelIndexSerializer, root: false)+ end+enddiff --git a/plugins/chat/app/controllers/chat_channels_controller.rb b/plugins/chat/app/controllers/chat_channels_controller.rbdeleted file mode 100644index cecc5b2f1fd..00000000000--- a/plugins/chat/app/controllers/chat_channels_controller.rb+++ /dev/null@@ -1,250 +0,0 @@-# frozen_string_literal: true--class Chat::ChatChannelsController < Chat::ChatBaseController- before_action :set_channel_and_chatable_with_access_check, except: %i[index create search]-- def index- structured = Chat::ChatChannelFetcher.structured(guardian)- render_serialized(structured, ChatChannelIndexSerializer, root: false)- end-- def show- render_serialized(- @chat_channel,- ChatChannelSerializer,- membership: @chat_channel.membership_for(current_user),- root: false,- )- end-- def follow- membership = @chat_channel.add(current_user)-- render_serialized(@chat_channel, ChatChannelSerializer, membership: membership, root: false)- end-- def unfollow- membership = @chat_channel.remove(current_user)-- render_serialized(@chat_channel, ChatChannelSerializer, membership: membership, root: false)- end-- def create- params.require(%i[id name])- guardian.ensure_can_create_chat_channel!- if params[:name].length > SiteSetting.max_topic_title_length- raise Discourse::InvalidParameters.new(:name)- end-- exists =- ChatChannel.exists?(chatable_type: "Category", chatable_id: params[:id], name: params[:name])- if exists- raise Discourse::InvalidParameters.new(I18n.t("chat.errors.channel_exists_for_category"))- end-- chatable = Category.find_by(id: params[:id])- raise Discourse::NotFound unless chatable-- auto_join_users = ActiveRecord::Type::Boolean.new.deserialize(params[:auto_join_users]) || false-- chat_channel =- chatable.create_chat_channel!(- name: params[:name],- description: params[:description],- user_count: 1,- auto_join_users: auto_join_users,- )- chat_channel.user_chat_channel_memberships.create!(user: current_user, following: true)-- if chat_channel.auto_join_users- Chat::ChatChannelMembershipManager.new(chat_channel).enforce_automatic_channel_memberships- end-- render_serialized(- chat_channel,- ChatChannelSerializer,- membership: chat_channel.membership_for(current_user),- )- end-- def edit- guardian.ensure_can_edit_chat_channel!- if (params[:name]&.length || 0) > SiteSetting.max_topic_title_length- raise Discourse::InvalidParameters.new(:name)- end-- chat_channel = ChatChannel.find_by(id: params[:chat_channel_id])- raise Discourse::NotFound unless chat_channel-- chat_channel.name = params[:name] if params[:name]- chat_channel.description = params[:description] if params[:description]- chat_channel.save!-- ChatPublisher.publish_chat_channel_edit(chat_channel, current_user)- render_serialized(- chat_channel,- ChatChannelSerializer,- membership: chat_channel.membership_for(current_user),- )- end-- def search- params.require(:filter)- filter = params[:filter]&.downcase- memberships = Chat::ChatChannelMembershipManager.all_for_user(current_user)- public_channels =- Chat::ChatChannelFetcher.secured_public_channels(- guardian,- memberships,- filter: filter,- status: :open,- )-- users = User.joins(:user_option).where.not(id: current_user.id)- if !Chat.allowed_group_ids.include?(Group::AUTO_GROUPS[:everyone])- users =- users- .joins(:groups)- .where(groups: { id: Chat.allowed_group_ids })- .or(users.joins(:groups).staff)- end-- users = users.where(user_option: { chat_enabled: true })- like_filter = "%#{filter}%"- if SiteSetting.prioritize_username_in_ux || !SiteSetting.enable_names- users = users.where("users.username_lower ILIKE ?", like_filter)- else- users =- users.where(- "LOWER(users.name) ILIKE ? OR users.username_lower ILIKE ?",- like_filter,- like_filter,- )- end-- users = users.limit(25).uniq-- direct_message_channels =- (- if users.count > 0- ChatChannel- .includes(chatable: :users)- .joins(direct_message: :direct_message_users)- .group(1)- .having(- "ARRAY[?] <@ ARRAY_AGG(user_id) AND ARRAY[?] && ARRAY_AGG(user_id)",- [current_user.id],- users.map(&:id),- )- else- []- end- )-- user_ids_with_channel = []- direct_message_channels.each do |dm_channel|- user_ids = dm_channel.chatable.users.map(&:id)- user_ids_with_channel.concat(user_ids) if user_ids.count < 3- end-- users_without_channel = users.filter { |u| !user_ids_with_channel.include?(u.id) }-- if current_user.username.downcase.start_with?(filter)- # We filtered out the current user for the query earlier, but check to see- # if they should be included, and add.- users_without_channel << current_user- end-- render_serialized(- {- public_channels: public_channels,- direct_message_channels: direct_message_channels,- users: users_without_channel,- memberships: memberships,- },- ChatChannelSearchSerializer,- root: false,- )- end-- def archive- params.require(:type)-- if params[:type] == "newTopic" ? params[:title].blank? : params[:topic_id].blank?- raise Discourse::InvalidParameters- end-- if !guardian.can_change_channel_status?(@chat_channel, :read_only)- raise Discourse::InvalidAccess.new(I18n.t("chat.errors.channel_cannot_be_archived"))- end-- Chat::ChatChannelArchiveService.begin_archive_process(- chat_channel: @chat_channel,- acting_user: current_user,- topic_params: {- topic_id: params[:topic_id],- topic_title: params[:title],- category_id: params[:category_id],- tags: params[:tags],- },- )-- render json: success_json- end-- def retry_archive- guardian.ensure_can_change_channel_status!(@chat_channel, :archived)-- archive = @chat_channel.chat_channel_archive- raise Discourse::NotFound if archive.blank?- raise Discourse::InvalidAccess if !archive.failed?-- Chat::ChatChannelArchiveService.retry_archive_process(chat_channel: @chat_channel)-- render json: success_json- end-- def change_status- params.require(:status)-- # we only want to use this endpoint for open/closed status changes,- # the others are more "special" and are handled by the archive endpoint- if !ChatChannel.statuses.keys.include?(params[:status]) || params[:status] == "read_only" ||- params[:status] == "archive"- raise Discourse::InvalidParameters- end-- guardian.ensure_can_change_channel_status!(@chat_channel, params[:status].to_sym)- @chat_channel.public_send("#{params[:status]}!", current_user)-- render json: success_json- end-- def destroy- params.require(:channel_name_confirmation)-- guardian.ensure_can_delete_chat_channel!-- if @chat_channel.title(current_user).downcase != params[:channel_name_confirmation].downcase- raise Discourse::InvalidParameters.new(:channel_name_confirmation)- end-- begin- ChatChannel.transaction do- @chat_channel.trash!(current_user)- StaffActionLogger.new(current_user).log_custom(- "chat_channel_delete",- {- chat_channel_id: @chat_channel.id,- chat_channel_name: @chat_channel.title(current_user),- },- )- end- rescue ActiveRecord::Rollback- return render_json_error(I18n.t("chat.errors.delete_channel_failed"))- end-- Jobs.enqueue(:chat_channel_delete, { chat_channel_id: @chat_channel.id })- render json: success_json- end-enddiff --git a/plugins/chat/app/controllers/chat_controller.rb b/plugins/chat/app/controllers/chat_controller.rbindex c4ad14e13dd..6b7d74d020b 100644--- a/plugins/chat/app/controllers/chat_controller.rb+++ b/plugins/chat/app/controllers/chat_controller.rb@@ -110,7 +110,9 @@ class Chat::ChatController < Chat::ChatBaseControllerreturn render_json_error(chat_message_creator.error) if chat_message_creator.failed?- @user_chat_channel_membership.update(last_read_message_id: chat_message_creator.chat_message.id)+ @user_chat_channel_membership.update!(+ last_read_message_id: chat_message_creator.chat_message.id,+ )if @chat_channel.direct_message_channel?# If any of the channel users is ignoring, muting, or preventing DMs from@@ -123,14 +125,15 @@ class Chat::ChatController < Chat::ChatBaseController).allowing_actor_communicationif user_ids_allowing_communication.any?- @chat_channel- .user_chat_channel_memberships- .where(user_id: user_ids_allowing_communication)- .update_all(following: true)ChatPublisher.publish_new_channel(@chat_channel,@chat_channel.chatable.users.where(id: user_ids_allowing_communication),)++ @chat_channel+ .user_chat_channel_memberships+ .where(user_id: user_ids_allowing_communication)+ .update_all(following: true)endend@@ -398,34 +401,6 @@ class Chat::ChatController < Chat::ChatBaseControllerrender json: success_json.merge(markdown: markdown)end- def move_messages_to_channel- params.require(:message_ids)- params.require(:destination_channel_id)-- raise Discourse::InvalidAccess if !guardian.can_move_chat_messages?(@chat_channel)- destination_channel =- Chat::ChatChannelFetcher.find_with_access_check(params[:destination_channel_id], guardian)-- begin- message_ids = params[:message_ids].map(&:to_i)- moved_messages =- Chat::MessageMover.new(- acting_user: current_user,- source_channel: @chat_channel,- message_ids: message_ids,- ).move_to_channel(destination_channel)- rescue Chat::MessageMover::NoMessagesFound, Chat::MessageMover::InvalidChannel => err- return render_json_error(err.message)- end-- render json:- success_json.merge(- destination_channel_id: destination_channel.id,- destination_channel_title: destination_channel.title(current_user),- first_moved_message_id: moved_messages.first.id,- )- end-def flagRateLimiter.new(current_user, "flag_chat_message", 4, 1.minutes).performed!diff --git a/plugins/chat/app/controllers/direct_messages_controller.rb b/plugins/chat/app/controllers/direct_messages_controller.rbindex fb07f66874b..b0100a95a89 100644--- a/plugins/chat/app/controllers/direct_messages_controller.rb+++ b/plugins/chat/app/controllers/direct_messages_controller.rb@@ -13,7 +13,7 @@ class Chat::DirectMessagesController < Chat::ChatBaseControllerrender_serialized(chat_channel,ChatChannelSerializer,- root: "chat_channel",+ root: "channel",membership: chat_channel.membership_for(current_user),)rescue Chat::DirectMessageChannelCreator::NotAllowed => err@@ -31,7 +31,7 @@ class Chat::DirectMessagesController < Chat::ChatBaseControllerrender_serialized(chat_channel,ChatChannelSerializer,- root: "chat_channel",+ root: "channel",membership: chat_channel.membership_for(current_user),)elsediff --git a/plugins/chat/app/jobs/regular/chat_channel_archive.rb b/plugins/chat/app/jobs/regular/chat_channel_archive.rbindex c5eb878d33b..33e270dd220 100644--- a/plugins/chat/app/jobs/regular/chat_channel_archive.rb+++ b/plugins/chat/app/jobs/regular/chat_channel_archive.rb@@ -15,7 +15,19 @@ module Jobsreturnend- return if channel_archive.complete?+ if channel_archive.complete?+ channel_archive.chat_channel.update!(status: :archived)++ ChatPublisher.publish_archive_status(+ channel_archive.chat_channel,+ archive_status: :success,+ archived_messages: channel_archive.archived_messages,+ archive_topic_id: channel_archive.destination_topic_id,+ total_messages: channel_archive.total_messages,+ )++ return+ endDistributedMutex.synchronize("archive_chat_channel_#{channel_archive.chat_channel_id}",diff --git a/plugins/chat/app/serializers/chat_channel_serializer.rb b/plugins/chat/app/serializers/chat_channel_serializer.rbindex fe321c7fa0e..9193334177d 100644--- a/plugins/chat/app/serializers/chat_channel_serializer.rb+++ b/plugins/chat/app/serializers/chat_channel_serializer.rb@@ -20,7 +20,7 @@ class ChatChannelSerializer < ApplicationSerializer:archive_topic_id,:memberships_count,:current_user_membership,- :message_bus_last_ids+ :metadef initialize(object, opts)super(object, opts)@@ -61,7 +61,7 @@ class ChatChannelSerializer < ApplicationSerializerenddef include_archive_status?- scope.is_staff? && object.archived? && archive.present?+ scope.is_staff? && (object.archived? || archive&.failed?) && archive.present?enddef archive_completed@@ -88,8 +88,11 @@ class ChatChannelSerializer < ApplicationSerializerscope.can_edit_chat_channel?end+ def include_current_user_membership?+ @current_user_membership.present?+ end+def current_user_membership- return if !@current_user_membership@current_user_membership.chat_channel = objectUserChatChannelMembershipSerializer.new(@current_user_membership,@@ -98,10 +101,17 @@ class ChatChannelSerializer < ApplicationSerializer).as_jsonend- def message_bus_last_ids+ def meta{- new_messages: @opts[:new_messages_message_bus_last_id] || MessageBus.last_id(ChatPublisher.new_messages_message_bus_channel(object.id)),- new_mentions: @opts[:new_mentions_message_bus_last_id] || MessageBus.last_id(ChatPublisher.new_mentions_message_bus_channel(object.id)),+ message_bus_last_ids: {+ new_messages:+ @opts[:new_messages_message_bus_last_id] ||+ MessageBus.last_id(ChatPublisher.new_messages_message_bus_channel(object.id)),+ new_mentions:+ @opts[:new_mentions_message_bus_last_id] ||+ MessageBus.last_id(ChatPublisher.new_mentions_message_bus_channel(object.id)),+ archive_status: MessageBus.last_id("/chat/channel-archive-status"),+ },}enddiff --git a/plugins/chat/app/serializers/structured_channel_serializer.rb b/plugins/chat/app/serializers/structured_channel_serializer.rbindex 8ecbc6103d8..a197c36c62e 100644--- a/plugins/chat/app/serializers/structured_channel_serializer.rb+++ b/plugins/chat/app/serializers/structured_channel_serializer.rb@@ -1,7 +1,7 @@# frozen_string_literal: trueclass StructuredChannelSerializer < ApplicationSerializer- attributes :public_channels, :direct_message_channels, :message_bus_last_ids+ attributes :public_channels, :direct_message_channels, :metadef public_channelsobject[:public_channels].map do |channel|@@ -10,8 +10,10 @@ class StructuredChannelSerializer < ApplicationSerializerroot: nil,scope: scope,membership: channel_membership(channel.id),- new_messages_message_bus_last_id: chat_message_bus_last_ids[ChatPublisher.new_messages_message_bus_channel(channel.id)],- new_mentions_message_bus_last_id: chat_message_bus_last_ids[ChatPublisher.new_mentions_message_bus_channel(channel.id)]+ new_messages_message_bus_last_id:+ chat_message_bus_last_ids[ChatPublisher.new_messages_message_bus_channel(channel.id)],+ new_mentions_message_bus_last_id:+ chat_message_bus_last_ids[ChatPublisher.new_mentions_message_bus_channel(channel.id)],)endend@@ -23,8 +25,10 @@ class StructuredChannelSerializer < ApplicationSerializerroot: nil,scope: scope,membership: channel_membership(channel.id),- new_messages_message_bus_last_id: chat_message_bus_last_ids[ChatPublisher.new_messages_message_bus_channel(channel.id)],- new_mentions_message_bus_last_id: chat_message_bus_last_ids[ChatPublisher.new_mentions_message_bus_channel(channel.id)]+ new_messages_message_bus_last_id:+ chat_message_bus_last_ids[ChatPublisher.new_messages_message_bus_channel(channel.id)],+ new_mentions_message_bus_last_id:+ chat_message_bus_last_ids[ChatPublisher.new_mentions_message_bus_channel(channel.id)],)endend@@ -34,47 +38,54 @@ class StructuredChannelSerializer < ApplicationSerializerobject[:memberships].find { |membership| membership.chat_channel_id == channel_id }end- def message_bus_last_ids- ids = {- channel_metadata: chat_message_bus_last_ids[ChatPublisher::CHANNEL_METADATA_MESSAGE_BUS_CHANNEL],+ def meta+ last_ids = {+ channel_metadata:+ chat_message_bus_last_ids[ChatPublisher::CHANNEL_METADATA_MESSAGE_BUS_CHANNEL],channel_edits: chat_message_bus_last_ids[ChatPublisher::CHANNEL_EDITS_MESSAGE_BUS_CHANNEL],channel_status: chat_message_bus_last_ids[ChatPublisher::CHANNEL_STATUS_MESSAGE_BUS_CHANNEL],- new_channel: chat_message_bus_last_ids[ChatPublisher::NEW_CHANNEL_MESSAGE_BUS_CHANNEL]+ new_channel: chat_message_bus_last_ids[ChatPublisher::NEW_CHANNEL_MESSAGE_BUS_CHANNEL],}- if id = chat_message_bus_last_ids[ChatPublisher.user_tracking_state_message_bus_channel(scope.user.id)]- ids[:user_tracking_state] = id+ if id =+ chat_message_bus_last_ids[+ ChatPublisher.user_tracking_state_message_bus_channel(scope.user.id)+ ]+ last_ids[:user_tracking_state] = idend- ids+ { message_bus_last_ids: last_ids }endprivatedef chat_message_bus_last_ids- @chat_message_bus_last_ids ||= begin- message_bus_channels = [- ChatPublisher::CHANNEL_METADATA_MESSAGE_BUS_CHANNEL,- ChatPublisher::CHANNEL_EDITS_MESSAGE_BUS_CHANNEL,- ChatPublisher::CHANNEL_STATUS_MESSAGE_BUS_CHANNEL,- ChatPublisher::NEW_CHANNEL_MESSAGE_BUS_CHANNEL,- ]+ @chat_message_bus_last_ids ||=+ begin+ message_bus_channels = [+ ChatPublisher::CHANNEL_METADATA_MESSAGE_BUS_CHANNEL,+ ChatPublisher::CHANNEL_EDITS_MESSAGE_BUS_CHANNEL,+ ChatPublisher::CHANNEL_STATUS_MESSAGE_BUS_CHANNEL,+ ChatPublisher::NEW_CHANNEL_MESSAGE_BUS_CHANNEL,+ ]- if !scope.anonymous?- message_bus_channels.push(ChatPublisher.user_tracking_state_message_bus_channel(scope.user.id))- end+ if !scope.anonymous?+ message_bus_channels.push(+ ChatPublisher.user_tracking_state_message_bus_channel(scope.user.id),+ )+ end- object[:public_channels].each do |channel|- message_bus_channels.push(ChatPublisher.new_messages_message_bus_channel(channel.id))- message_bus_channels.push(ChatPublisher.new_mentions_message_bus_channel(channel.id))- end+ object[:public_channels].each do |channel|+ message_bus_channels.push(ChatPublisher.new_messages_message_bus_channel(channel.id))+ message_bus_channels.push(ChatPublisher.new_mentions_message_bus_channel(channel.id))+ end- object[:direct_message_channels].each do |channel|- message_bus_channels.push(ChatPublisher.new_messages_message_bus_channel(channel.id))- message_bus_channels.push(ChatPublisher.new_mentions_message_bus_channel(channel.id))- end+ object[:direct_message_channels].each do |channel|+ message_bus_channels.push(ChatPublisher.new_messages_message_bus_channel(channel.id))+ message_bus_channels.push(ChatPublisher.new_mentions_message_bus_channel(channel.id))+ end- MessageBus.last_ids(*message_bus_channels)- end+ MessageBus.last_ids(*message_bus_channels)+ endendenddiff --git a/plugins/chat/app/services/chat_publisher.rb b/plugins/chat/app/services/chat_publisher.rbindex 5a1027d04d4..6dff51e6566 100644--- a/plugins/chat/app/services/chat_publisher.rb+++ b/plugins/chat/app/services/chat_publisher.rb@@ -20,6 +20,7 @@ module ChatPublisherMessageBus.publish(self.new_messages_message_bus_channel(chat_channel.id),{+ channel_id: chat_channel.id,message_id: chat_message.id,user_id: chat_message.user.id,username: chat_message.user.username,@@ -145,7 +146,7 @@ module ChatPublisherdef self.publish_new_mention(user_id, chat_channel_id, chat_message_id)MessageBus.publish(self.new_mentions_message_bus_channel(chat_channel_id),- { message_id: chat_message_id }.as_json,+ { message_id: chat_message_id, channel_id: chat_channel_id }.as_json,user_ids: [user_id],)end@@ -154,13 +155,20 @@ module ChatPublisherdef self.publish_new_channel(chat_channel, users)users.each do |user|+ # FIXME: This could generate a lot of queries depending on the amount of users+ membership = chat_channel.membership_for(user)++ # TODO: this event is problematic as some code will update the membership before calling it+ # and other code will update it after calling it+ # it means frontend must handle logic for both casesserialized_channel =ChatChannelSerializer.new(chat_channel,scope: Guardian.new(user), # We need a guardian here for direct messages- root: :chat_channel,- membership: chat_channel.membership_for(user),+ root: :channel,+ membership: membership,).as_json+MessageBus.publish(NEW_CHANNEL_MESSAGE_BUS_CHANNEL, serialized_channel, user_ids: [user.id])endend@@ -179,9 +187,10 @@ module ChatPublishertype: :mention_warning,chat_message_id: chat_message.id,cannot_see: cannot_chat_users.map { |u| { username: u.username, id: u.id } }.as_json,- without_membership: without_membership.map { |u| { username: u.username, id: u.id } }.as_json,+ without_membership:+ without_membership.map { |u| { username: u.username, id: u.id } }.as_json,groups_with_too_many_members: too_many_members.map(&:name).as_json,- group_mentions_disabled: mentions_disabled.map(&:name).as_json+ group_mentions_disabled: mentions_disabled.map(&:name).as_json,},user_ids: [user_id],)diff --git a/plugins/chat/assets/javascripts/discourse/adapters/chat-message.js b/plugins/chat/assets/javascripts/discourse/adapters/chat-message.jsindex 51f4b36f251..400f1d389be 100644--- a/plugins/chat/assets/javascripts/discourse/adapters/chat-message.js+++ b/plugins/chat/assets/javascripts/discourse/adapters/chat-message.js@@ -1,6 +1,8 @@import RESTAdapter from "discourse/adapters/rest";export default class ChatMessage extends RESTAdapter {+ jsonMode = true;+pathFor(store, type, findArgs) {if (findArgs.targetMessageId) {return `/chat/lookup/${findArgs.targetMessageId}.json?chat_channel_id=${findArgs.channelId}`;diff --git a/plugins/chat/assets/javascripts/discourse/components/channels-list.hbs b/plugins/chat/assets/javascripts/discourse/components/channels-list.hbsindex 4247db6e27d..a4100a897fa 100644--- a/plugins/chat/assets/javascripts/discourse/components/channels-list.hbs+++ b/plugins/chat/assets/javascripts/discourse/components/channels-list.hbs@@ -1,5 +1,11 @@-{{#if (and this.showMobileDirectMessageButton this.canCreateDirectMessageChannel)}}- <LinkTo @route="chat.draft-channel" class="btn-flat open-draft-channel-page-btn keep-mobile-sidebar-open btn-floating" title={{i18n this.createDirectMessageChannelLabel}}>+{{#if+ (and this.showMobileDirectMessageButton this.canCreateDirectMessageChannel)+}}+ <LinkTo+ @route="chat.draft-channel"+ class="btn-flat open-draft-channel-page-btn keep-mobile-sidebar-open btn-floating"+ title={{i18n this.createDirectMessageChannelLabel}}+ >{{d-icon "plus"}}</LinkTo>{{/if}}@@ -8,7 +14,10 @@role="region"aria-label={{i18n "chat.aria_roles.channels_list"}}class="channels-list"- {{on "scroll" (if this.chatStateManager.isFullPageActive this.storeScrollPosition (noop))}}+ {{on+ "scroll"+ (if this.chatStateManager.isFullPageActive this.storeScrollPosition (noop))+ }}>{{#if this.displayPublicChannels}}<div class="chat-channel-divider public-channels-section">@@ -26,7 +35,11 @@{{/if}}<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"}}>+ <LinkTo+ @route="chat.browse"+ class="btn no-text btn-flat open-browse-page-btn title-action"+ title={{i18n "chat.channels_list_popup.browse"}}+ >{{d-icon "pencil-alt"}}</LinkTo></div>@@ -40,7 +53,7 @@</LinkTo></div>{{else}}- {{#each this.publicChannels as |channel|}}+ {{#each this.chatChannelsManager.publicMessageChannels as |channel|}}<ChatChannelRow@channel={{channel}}@options={{hash settingsButton=true}}@@ -75,8 +88,17 @@{{/if}}<span class="channel-title">{{i18n "chat.direct_messages.title"}}</span>- {{#if (and this.canCreateDirectMessageChannel (not this.showMobileDirectMessageButton))}}- <LinkTo @route="chat.draft-channel" class="btn no-text btn-flat open-draft-channel-page-btn" title={{i18n this.createDirectMessageChannelLabel}}>+ {{#if+ (and+ this.canCreateDirectMessageChannel+ (not this.showMobileDirectMessageButton)+ )+ }}+ <LinkTo+ @route="chat.draft-channel"+ class="btn no-text btn-flat open-draft-channel-page-btn"+ title={{i18n this.createDirectMessageChannelLabel}}+ >{{d-icon "plus"}}</LinkTo>{{/if}}@@ -84,11 +106,8 @@{{/if}}<div id="direct-message-channels" class={{this.directMessageChannelClasses}}>- {{#each this.sortedDirectMessageChannels as |channel|}}- <ChatChannelRow- @channel={{channel}}- @options={{hash leaveButton=true}}- />+ {{#each this.chatChannelsManager.truncatedDirectMessageChannels as |channel|}}+ <ChatChannelRow @channel={{channel}} @options={{hash leaveButton=true}} />{{/each}}</div></div>diff --git a/plugins/chat/assets/javascripts/discourse/components/channels-list.js b/plugins/chat/assets/javascripts/discourse/components/channels-list.jsindex 796db2a1b94..9cac0ff735e 100644--- a/plugins/chat/assets/javascripts/discourse/components/channels-list.js+++ b/plugins/chat/assets/javascripts/discourse/components/channels-list.js@@ -3,18 +3,18 @@ import Component from "@ember/component";import { action, computed } from "@ember/object";import { schedule } from "@ember/runloop";import { inject as service } from "@ember/service";-import { and, empty, reads } from "@ember/object/computed";+import { and, empty } from "@ember/object/computed";export default class ChannelsList extends Component {@service chat;@service router;@service chatStateManager;+ @service chatChannelsManager;tagName = "";inSidebar = false;toggleSection = null;- @reads("chat.publicChannels.[]") publicChannels;- @reads("chat.directMessageChannels.[]") directMessageChannels;- @empty("publicChannels") publicChannelsEmpty;+ @empty("chatChannelsManager.publicMessageChannels")+ publicMessageChannelsEmpty;@and("site.mobileView", "showDirectMessageChannels")showMobileDirectMessageButton;@@ -27,11 +27,14 @@ export default class ChannelsList extends Component {return "chat.direct_messages.new";}- @computed("canCreateDirectMessageChannel", "directMessageChannels")+ @computed(+ "canCreateDirectMessageChannel",+ "chatChannelsManager.directMessageChannels"+ )get showDirectMessageChannels() {return (this.canCreateDirectMessageChannel ||- this.directMessageChannels?.length > 0+ this.chatChannelsManager.directMessageChannels?.length > 0);}@@ -39,17 +42,6 @@ export default class ChannelsList extends Component {return this.chat.userCanDirectMessage;}- @computed("[email protected]_message_sent_at")- get sortedDirectMessageChannels() {- if (!this.directMessageChannels?.length) {- return [];- }-- return this.chat.truncateDirectMessageChannels(- this.chat.sortDirectMessageChannels(this.directMessageChannels)- );- }-@computed("inSidebar")get publicChannelClasses() {return `channels-list-container public-channels ${@@ -58,11 +50,11 @@ export default class ChannelsList extends Component {}@computed(- "publicChannelsEmpty",+ "publicMessageChannelsEmpty","currentUser.{staff,has_joinable_public_channels}")get displayPublicChannels() {- if (this.publicChannelsEmpty) {+ if (this.publicMessageChannelsEmpty) {return (this.currentUser?.staff ||this.currentUser?.has_joinable_public_channelsdiff --git a/plugins/chat/assets/javascripts/discourse/components/chat-browse-view.hbs b/plugins/chat/assets/javascripts/discourse/components/chat-browse-view.hbsindex 04b7b31cf6c..5098f17b76e 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-browse-view.hbs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-browse-view.hbs@@ -1,12 +1,16 @@{{#if this.chatProgressBarContainer}}{{#in-element this.chatProgressBarContainer}}- <DProgressBar @key="browse-list" @isLoading={{this.isLoading}} />+ <DProgressBar @key="browse-list" @isLoading={{this.channelsCollection.loading}} />{{/in-element}}{{/if}}<div class="chat-browse-view__header chat-full-page-header">{{#if this.site.mobileView}}- <LinkTo @route="chat.index" class="chat-full-page-header__back-btn no-text btn-flat btn" title={{i18n "chat.browse.back"}}>+ <LinkTo+ @route="chat.index"+ class="chat-full-page-header__back-btn no-text btn-flat btn"+ title={{i18n "chat.browse.back"}}+ >{{d-icon "chevron-left"}}</LinkTo>{{/if}}@@ -17,7 +21,10 @@<DButton@action={{action "createChannel"}}@icon="plus"- @class={{concat-class "new-channel-btn" (if this.site.mobileView "btn-flat")}}+ @class={{concat-class+ "new-channel-btn"+ (if this.site.mobileView "btn-flat")+ }}@label={{if this.site.desktopView "chat.create_channel.title"}}/>{{/if}}@@ -49,7 +56,7 @@/></div>- {{#if (and (not this.channels.length) (not this.isLoading))}}+ {{#if (and (not this.channelsCollection.length) (not this.channelsCollection.loading))}}<div class="empty-state"><span class="empty-state-title">{{i18n "chat.empty_state.title"}}</span><div class="empty-state-body">@@ -60,16 +67,16 @@</LinkTo></div></div>- {{else if this.channels.length}}+ {{else if this.channelsCollection.length}}<div class="chat-browse-view__content_wrapper"><div class="chat-browse-view__content"><div class="chat-browse-view__cards">- {{#each this.channels as |channel|}}+ {{#each this.channelsCollection as |channel|}}<ChatChannelCard @channel={{channel}} />{{/each}}</div>- {{#unless this.isLoading}}+ {{#unless this.channelsCollection.loading}}<OnVisibilityAction @action={{action "onScroll"}} />{{/unless}}</div>diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-browse-view.js b/plugins/chat/assets/javascripts/discourse/components/chat-browse-view.jsindex a9d66616cdf..39ea226ef68 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-browse-view.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-browse-view.js@@ -1,62 +1,28 @@import { INPUT_DELAY } from "discourse-common/config/environment";import Component from "@ember/component";import { action, computed } from "@ember/object";-import { tracked } from "@glimmer/tracking";import { schedule } from "@ember/runloop";import { inject as service } from "@ember/service";-import ChatApi from "discourse/plugins/chat/discourse/lib/chat-api";import discourseDebounce from "discourse-common/lib/debounce";-import { bind } from "discourse-common/utils/decorators";import showModal from "discourse/lib/show-modal";const TABS = ["all", "open", "closed", "archived"];-const PER_PAGE = 20;export default class ChatBrowseView extends Component {- @service router;- @tracked isLoading = false;- @tracked channels = [];+ @service chatApi;tagName = "";- offset = 0;- canLoadMore = true;-didReceiveAttrs() {this._super(...arguments);- this.channels = [];- this.canLoadMore = true;- this.offset = 0;- this.fetchChannels();- }-- async fetchChannels(params) {- if (this.isLoading || !this.canLoadMore) {- return;+ if (!this.channelsCollection) {+ this.set("channelsCollection", this.chatApi.channels());}- this.isLoading = true;-- try {- const results = await ChatApi.chatChannels({- limit: PER_PAGE,- offset: this.offset,- status: this.status,- filter: this.filter,- ...params,- });-- if (results.length) {- this.channels.pushObjects(results);- }-- if (results.length < PER_PAGE) {- this.canLoadMore = false;- }- } finally {- this.offset = this.offset + PER_PAGE;- this.isLoading = false;- }+ this.channelsCollection.load({+ filter: this.filter,+ status: this.status,+ });}@computed("siteSettings.chat_allow_archiving_channels")@@ -74,19 +40,20 @@ export default class ChatBrowseView extends Component {@actiononScroll() {- if (this.isLoading) {- return;- }-- discourseDebounce(this, this.fetchChannels, INPUT_DELAY);+ discourseDebounce(+ this,+ this.channelsCollection.loadMore,+ { filter: this.filter, status: this.status },+ INPUT_DELAY+ );}@actiondebouncedFiltering(event) {discourseDebounce(this,- this.filterChannels,- event.target.value,+ this.channelsCollection.load,+ { filter: event.target.value, status: this.status },INPUT_DELAY);}@@ -100,14 +67,4 @@ export default class ChatBrowseView extends Component {focusFilterInput(input) {schedule("afterRender", () => input?.focus());}-- @bind- filterChannels(filter) {- this.canLoadMore = true;- this.filter = filter;- this.channels = [];- this.offset = 0;-- this.fetchChannels();- }}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-about-view.hbs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-about-view.hbsindex 323bc228731..889ec62b31f 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-about-view.hbs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-about-view.hbs@@ -59,7 +59,6 @@<div class="chat-form__section"><ToggleChannelMembershipButton@channel={{this.channel}}- @onToggle={{action "afterMembershipToggle"}}@options={{hash joinClass="btn-primary" leaveClass="btn-flat" joinIcon="sign-in-alt" leaveIcon="sign-out-alt"}}/></div>diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-about-view.js b/plugins/chat/assets/javascripts/discourse/components/chat-channel-about-view.jsindex 3b4d038645d..0537ff51bd2 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-about-view.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-about-view.js@@ -1,5 +1,4 @@import Component from "@ember/component";-import { action } from "@ember/object";import { inject as service } from "@ember/service";export default class ChatChannelAboutView extends Component {@@ -9,11 +8,4 @@ export default class ChatChannelAboutView extends Component {onEditChatChannelTitle = null;onEditChatChannelDescription = null;isLoading = false;-- @action- afterMembershipToggle() {- this.chat.forceRefreshChannels().then(() => {- this.chat.openChannel(this.channel);- });- }}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-archive-modal-inner.js b/plugins/chat/assets/javascripts/discourse/components/chat-channel-archive-modal-inner.jsindex 2569653fac3..57a800b4127 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-archive-modal-inner.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-archive-modal-inner.js@@ -5,7 +5,6 @@ import { isEmpty } from "@ember/utils";import discourseComputed from "discourse-common/utils/decorators";import { action } from "@ember/object";import { equal } from "@ember/object/computed";-import { ajax } from "discourse/lib/ajax";import { inject as service } from "@ember/service";import { popupAjaxError } from "discourse/lib/ajax-error";import {@@ -14,13 +13,15 @@ import {} from "discourse/plugins/chat/discourse/components/chat-to-topic-selector";import { CHANNEL_STATUSES } from "discourse/plugins/chat/discourse/models/chat-channel";import { htmlSafe } from "@ember/template";+import ModalFunctionality from "discourse/mixins/modal-functionality";-export default Component.extend({+export default Component.extend(ModalFunctionality, {chat: service(),+ chatApi: service(),tagName: "",chatChannel: null,- selection: "newTopic",+ selection: NEW_TOPIC_SELECTION,newTopic: equal("selection", NEW_TOPIC_SELECTION),existingTopic: equal("selection", EXISTING_TOPIC_SELECTION),@@ -34,18 +35,12 @@ export default Component.extend({@actionarchiveChannel() {this.set("saving", true);- return ajax({- url: `/chat/chat_channels/${this.chatChannel.id}/archive.json`,- type: "PUT",- data: this._data(),- })- .then(() => {- this.appEvents.trigger("modal-body:flash", {- text: I18n.t("chat.channel_archive.process_started"),- messageClass: "success",- });- this.chatChannel.set("status", CHANNEL_STATUSES.archived);+ return this.chatApi+ .createChannelArchive(this.chatChannel.id, this._data())+ .then((result) => {+ this.flash(I18n.t("chat.channel_archive.process_started"), "success");+ result.target.status = CHANNEL_STATUSES.archived;discourseLater(() => {this.closeModal();@@ -58,7 +53,6 @@ export default Component.extend({_data() {const data = {type: this.selection,- chat_channel_id: this.chatChannel.id,};if (this.newTopic) {data.title = this.topicTitle;diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-archive-status.js b/plugins/chat/assets/javascripts/discourse/components/chat-channel-archive-status.jsindex e8f20834527..7f76393cdcc 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-archive-status.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-archive-status.js@@ -2,14 +2,15 @@ import Component from "@ember/component";import { htmlSafe } from "@ember/template";import I18n from "I18n";import { popupAjaxError } from "discourse/lib/ajax-error";-import { ajax } from "discourse/lib/ajax";import getURL from "discourse-common/lib/get-url";import { action } from "@ember/object";import discourseComputed, { bind } from "discourse-common/utils/decorators";+import { inject as service } from "@ember/service";export default Component.extend({channel: null,tagName: "",+ chatApi: service(),@discourseComputed("channel.status",@@ -43,26 +44,32 @@ export default Component.extend({@actionretryArchive() {- return ajax({- url: `/chat/chat_channels/${this.channel.id}/retry_archive.json`,- type: "PUT",- })- .then(() => {- this.channel.set("archive_failed", false);- })+ return this.chatApi+ .createChannelArchive(this.channel.id).catch(popupAjaxError);},didInsertElement() {this._super(...arguments);+if (this.currentUser.admin) {- this.messageBus.subscribe("/chat/channel-archive-status", this.onMessage);+ this.messageBus.subscribe(+ "/chat/channel-archive-status",+ this.onMessage,+ this.channel.meta.message_bus_last_ids.archive_status+ );}},willDestroyElement() {this._super(...arguments);- this.messageBus.unsubscribe("/chat/channel-archive-status", this.onMessage);++ if (this.currentUser.admin) {+ this.messageBus.unsubscribe(+ "/chat/channel-archive-status",+ this.onMessage+ );+ }},_getTopicUrl() {diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-card.hbs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-card.hbsindex 411dc94ea38..beb29b614df 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-card.hbs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-card.hbs@@ -1,33 +1,34 @@-{{#if this.channel}}+{{#if @channel}}<divclass={{concat-class"chat-channel-card"- (if this.channel.isClosed "-closed")- (if this.channel.isArchived "-archived")+ (if @channel.isClosed "-closed")+ (if @channel.isArchived "-archived")}}- style={{border-color this.channel.chatable.color}}+ style={{border-color @channel.chatable.color}}+ data-channel-id={{@channel.id}}><div class="chat-channel-card__header"><LinkTo@route="chat.channel"- @models={{array this.channel.id (slugify-channel this.channel)}}+ @models={{array @channel.id (slugify-channel @channel)}}class="chat-channel-card__name-container"><span class="chat-channel-card__name">- {{replace-emoji this.channel.escapedTitle}}+ {{replace-emoji @channel.escapedTitle}}</span>- {{#if this.channel.chatable.read_restricted}}+ {{#if @channel.chatable.read_restricted}}{{d-icon "lock" class="chat-channel-card__read-restricted"}}{{/if}}</LinkTo><div class="chat-channel-card__header-actions">- {{#if this.channel.current_user_membership.muted}}+ {{#if @channel.currentUserMembership.muted}}<LinkTo@route="chat.channel.info.settings"@models={{array- this.channel.id- (slugify-channel this.channel)+ @channel.id+ (slugify-channel @channel)}}class="chat-channel-card__tag -muted"tabindex="-1"@@ -38,7 +39,7 @@<LinkTo@route="chat.channel.info.settings"- @models={{array this.channel.id (slugify-channel this.channel)}}+ @models={{array @channel.id (slugify-channel @channel)}}class="chat-channel-card__setting"tabindex="-1">@@ -47,32 +48,30 @@</div></div>- {{#if this.channel.description}}+ {{#if @channel.description}}<div class="chat-channel-card__description">- {{replace-emoji this.channel.escapedDescription}}+ {{replace-emoji @channel.escapedDescription}}</div>{{/if}}<div class="chat-channel-card__cta">- {{#if this.channel.isFollowing}}+ {{#if @channel.isFollowing}}<div class="chat-channel-card__tags"><span class="chat-channel-card__tag -joined">{{i18n "chat.joined"}}</span><ToggleChannelMembershipButton- @channel={{this.channel}}- @onToggle={{action "afterMembershipToggle"}}+ @channel={{@channel}}@options={{hashleaveClass="btn-link btn-small chat-channel-card__leave-btn"labelType="short"}}/></div>- {{else if this.channel.isJoinable}}+ {{else if @channel.isJoinable}}<ToggleChannelMembershipButton- @channel={{this.channel}}- @onToggle={{action "afterMembershipToggle"}}+ @channel={{@channel}}@options={{hashjoinClass="btn-primary btn-small chat-channel-card__join-btn"labelType="short"@@ -80,16 +79,16 @@/>{{/if}}- {{#if (gt this.channel.membershipsCount 0)}}+ {{#if (gt @channel.membershipsCount 0)}}<LinkTo@route="chat.channel.info.members"- @models={{array this.channel.id (slugify-channel this.channel)}}+ @models={{array @channel.id (slugify-channel @channel)}}class="chat-channel-card__members"tabindex="-1">{{i18n"chat.channel.memberships_count"- count=this.channel.membershipsCount}}</LinkTo>{{/if}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-card.js b/plugins/chat/assets/javascripts/discourse/components/chat-channel-card.jsindex 3392fe9f059..36a8f64e98b 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-card.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-card.js@@ -1,13 +1,6 @@-import Component from "@ember/component";-import { action } from "@ember/object";+import Component from "@glimmer/component";import { inject as service } from "@ember/service";export default class ChatChannelCard extends Component {@service chat;- tagName = "";-- @action- afterMembershipToggle() {- this.chat.forceRefreshChannels();- }}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-delete-modal-inner.js b/plugins/chat/assets/javascripts/discourse/components/chat-channel-delete-modal-inner.jsindex 3f38523f186..4943ae1e34b 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-delete-modal-inner.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-delete-modal-inner.js@@ -3,14 +3,15 @@ import { isEmpty } from "@ember/utils";import I18n from "I18n";import discourseComputed from "discourse-common/utils/decorators";import { action } from "@ember/object";-import { ajax } from "discourse/lib/ajax";import { inject as service } from "@ember/service";import { popupAjaxError } from "discourse/lib/ajax-error";import discourseLater from "discourse-common/lib/later";import { htmlSafe } from "@ember/template";+import ModalFunctionality from "discourse/mixins/modal-functionality";-export default Component.extend({+export default Component.extend(ModalFunctionality, {chat: service(),+ chatApi: service(),router: service(),tagName: "",chatChannel: null,@@ -37,16 +38,14 @@ export default Component.extend({@actiondeleteChannel() {this.set("deleting", true);- return ajax(`/chat/chat_channels/${this.chatChannel.id}.json`, {- method: "DELETE",- data: { channel_name_confirmation: this.channelNameConfirmation },- })++ return this.chatApi+ .destroyChannel(this.chatChannel.id, {+ name_confirmation: this.channelNameConfirmation,+ }).then(() => {this.set("confirmed", true);- this.appEvents.trigger("modal-body:flash", {- text: I18n.t("chat.channel_delete.process_started"),- messageClass: "success",- });+ this.flash(I18n.t("chat.channel_delete.process_started"), "success");discourseLater(() => {this.closeModal();diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-members-view.hbs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-members-view.hbsindex 90834e6051b..5acfc7a5267 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-members-view.hbs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-members-view.hbs@@ -1,6 +1,6 @@{{#if this.chatProgressBarContainer}}{{#in-element this.chatProgressBarContainer}}- <DProgressBar @key="members-view" @isLoading={{this.isFetchingMembers}} />+ <DProgressBar @key="members-view" @isLoading={{this.members.loading}} />{{/in-element}}{{/if}}@@ -22,15 +22,15 @@><div role="list" class="channel-members-view__list">- {{#each this.members as |member|}}+ {{#each this.members as |membership|}}<aclass="channel-members-view__list-item"- href={{member.user.userPath}}- data-user-card={{member.user.username}}+ href={{membership.user.userPath}}+ data-user-card={{membership.user.username}}tabindex="0">- <ChatUserAvatar @user={{member.user}} @avatarSize="medium" />- <ChatUserDisplayName @user={{member.user}} />+ <ChatUserAvatar @user={{membership.user}} @avatarSize="medium" />+ <ChatUserDisplayName @user={{membership.user}} /></a>{{else}}{{#unless this.isFetchingMembers}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-members-view.js b/plugins/chat/assets/javascripts/discourse/components/chat-channel-members-view.jsindex 49907dbd68c..dea4cad847d 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-members-view.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-members-view.js@@ -1,24 +1,20 @@-import { isEmpty } from "@ember/utils";import { INPUT_DELAY } from "discourse-common/config/environment";import Component from "@ember/component";import { action } from "@ember/object";import { schedule } from "@ember/runloop";-import ChatApi from "discourse/plugins/chat/discourse/lib/chat-api";import discourseDebounce from "discourse-common/lib/debounce";--const LIMIT = 50;+import { inject as service } from "@ember/service";export default class ChatChannelMembersView extends Component {+ @service chatApi;+tagName = "";channel = null;- members = null;isSearchFocused = false;- isFetchingMembers = false;onlineUsers = null;- offset = 0;filter = null;inputSelector = "channel-members-view__search-input";- canLoadMore = true;+ members = null;didInsertElement() {this._super(...arguments);@@ -28,14 +24,15 @@ export default class ChatChannelMembersView extends Component {}this._focusSearch();- this.set("members", []);- this.fetchMembers();+ this.set("members", this.chatApi.listChannelMemberships(this.channel.id));+ this.members.load();this.appEvents.on("chat:refresh-channel-members", this, "onFilterMembers");}willDestroyElement() {this._super(...arguments);+this.appEvents.off("chat:refresh-channel-members", this, "onFilterMembers");}@@ -46,59 +43,18 @@ export default class ChatChannelMembersView extends Component {@actiononFilterMembers(username) {this.set("filter", username);- this.set("offset", 0);- this.set("canLoadMore", true);discourseDebounce(this,- this.fetchMembers,- this.filter,- this.offset,+ this.members.load,+ { username: this.filter },INPUT_DELAY);}@actionloadMore() {- if (!this.canLoadMore) {- return;- }-- discourseDebounce(- this,- this.fetchMembers,- this.filter,- this.offset,- INPUT_DELAY- );- }-- fetchMembersHandler(id, params = {}) {- return ChatApi.chatChannelMemberships(id, params);- }-- fetchMembers(filter = null, offset = 0) {- this.set("isFetchingMembers", true);-- return this.fetchMembersHandler(this.channel.id, {- username: filter,- offset,- })- .then((response) => {- if (this.offset === 0) {- this.set("members", []);- }-- if (isEmpty(response)) {- this.set("canLoadMore", false);- } else {- this.set("offset", this.offset + LIMIT);- this.members.pushObjects(response);- }- })- .finally(() => {- this.set("isFetchingMembers", false);- });+ discourseDebounce(this, this.members.loadMore, INPUT_DELAY);}_focusSearch() {diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-preview-card.hbs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-preview-card.hbsindex 2e7f8f58005..eed8d6c84c2 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-preview-card.hbs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-preview-card.hbs@@ -13,7 +13,6 @@{{#if this.showJoinButton}}<ToggleChannelMembershipButton@channel={{this.channel}}- @onToggle={{this.afterMembershipToggle}}@options={{hash joinClass="btn-primary"}}/>{{/if}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-preview-card.js b/plugins/chat/assets/javascripts/discourse/components/chat-channel-preview-card.jsindex 23be8f9a672..954313febe9 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-preview-card.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-preview-card.js@@ -1,6 +1,6 @@import Component from "@ember/component";import { isEmpty } from "@ember/utils";-import { action, computed } from "@ember/object";+import { computed } from "@ember/object";import { readOnly } from "@ember/object/computed";import { inject as service } from "@ember/service";@@ -16,11 +16,4 @@ export default class ChatChannelPreviewCard extends Component {get hasDescription() {return !isEmpty(this.channel.description);}-- @action- afterMembershipToggle() {- this.chat.forceRefreshChannels().then(() => {- this.chat.openChannel(this.channel);- });- }}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-row.hbs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-row.hbsindex 83776ff9f77..e77ee34205f 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-row.hbs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-row.hbs@@ -4,7 +4,7 @@class={{concat-class"chat-channel-row"(if @channel.focused "focused")- (if @channel.current_user_membership.muted "muted")+ (if @channel.currentUserMembership.muted "muted")(if @options.leaveButton "can-leave")(if (eq this.chat.activeChannel.id @channel.id) "active")(if this.channelHasUnread "has-unread")diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-row.js b/plugins/chat/assets/javascripts/discourse/components/chat-channel-row.jsindex e703be69381..3fe267f6f63 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-row.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-row.js@@ -19,11 +19,7 @@ export default class ChatChannelRow extends Component {}get channelHasUnread() {- return (- this.currentUser.get(- `chat_channel_tracking_state.${this.args.channel?.id}.unread_count`- ) > 0- );+ return this.args.channel.currentUserMembership.unread_count > 0;}get #firstDirectMessageUser() {diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-selector-modal-inner.js b/plugins/chat/assets/javascripts/discourse/components/chat-channel-selector-modal-inner.jsindex bfd46d64c0e..1937ff6bdae 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-selector-modal-inner.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-selector-modal-inner.js@@ -17,24 +17,24 @@ export default Component.extend({channels: null,searchIndex: 0,loading: false,-- init() {- this._super(...arguments);- this.appEvents.on("chat-channel-selector-modal:close", this.close);- this.getInitialChannels();- },+ chatChannelsManager: service(),didInsertElement() {this._super(...arguments);++ this.appEvents.on("chat-channel-selector-modal:close", this.close);document.addEventListener("keyup", this.onKeyUp);document.getElementById("chat-channel-selector-modal-inner")?.addEventListener("mouseover", this.mouseover);document.getElementById("chat-channel-selector-input")?.focus();++ this.getInitialChannels();},willDestroyElement() {this._super(...arguments);+this.appEvents.off("chat-channel-selector-modal:close", this.close);document.removeEventListener("keyup", this.onKeyUp);document@@ -101,16 +101,17 @@ export default Component.extend({switchChannel(channel) {if (channel.user) {return this.fetchOrCreateChannelForUser(channel).then((response) => {- this.chat- .startTrackingChannel(ChatChannel.create(response.chat_channel))- .then((newlyTracked) => {- this.chat.openChannel(newlyTracked);- this.close();- });+ const newChannel = this.chatChannelsManager.store(response.channel);+ return this.chatChannelsManager.follow(newChannel).then((c) => {+ this.chat.openChannel(c);+ this.close();+ });});} else {- this.chat.openChannel(channel);- this.close();+ return this.chatChannelsManager.follow(channel).then((c) => {+ this.chat.openChannel(c);+ this.close();+ });}},@@ -135,7 +136,7 @@ export default Component.extend({searchIndex: this.searchIndex + 1,});const thisSearchIndex = this.searchIndex;- ajax("/chat/chat_channels/search", { data: { filter } })+ ajax("/chat/api/chatables", { data: { filter } }).then((searchModel) => {if (this.searchIndex === thisSearchIndex) {this.set("searchModel", searchModel);@@ -149,7 +150,11 @@ export default Component.extend({}});this.setProperties({- channels: channels.map((channel) => ChatChannel.create(channel)),+ channels: channels.map((channel) => {+ return channel.user+ ? ChatChannel.create(channel)+ : this.chatChannelsManager.store(channel);+ }),loading: false,});this.focusFirstChannel(this.channels);@@ -160,10 +165,9 @@ export default Component.extend({@actiongetInitialChannels() {- return this.chat.getChannelsWithFilter(this.filter).then((channels) => {- this.focusFirstChannel(channels);- this.set("channels", channels);- });+ const channels = this.getChannelsWithFilter(this.filter);+ this.set("channels", channels);+ this.focusFirstChannel(channels);},@action@@ -178,4 +182,44 @@ export default Component.extend({channels.forEach((c) => c.set("focused", false));channels[0]?.set("focused", true);},++ getChannelsWithFilter(filter, opts = { excludeActiveChannel: true }) {+ let sortedChannels = this.chatChannelsManager.channels.sort((a, b) => {+ return new Date(a.last_message_sent_at) > new Date(b.last_message_sent_at)+ ? -1+ : 1;+ });++ const trimmedFilter = filter.trim();+ const lowerCasedFilter = filter.toLowerCase();+ const { activeChannel } = this;++ return sortedChannels.filter((channel) => {+ if (+ opts.excludeActiveChannel &&+ activeChannel &&+ activeChannel.id === channel.id+ ) {+ return false;+ }+ if (!trimmedFilter.length) {+ return true;+ }++ if (channel.isDirectMessageChannel) {+ let userFound = false;+ channel.chatable.users.forEach((user) => {+ if (+ user.username.toLowerCase().includes(lowerCasedFilter) ||+ user.name?.toLowerCase().includes(lowerCasedFilter)+ ) {+ return (userFound = true);+ }+ });+ return userFound;+ } else {+ return channel.title.toLowerCase().includes(lowerCasedFilter);+ }+ });+ },});diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-settings-view.hbs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-settings-view.hbsindex 5597f74a5c9..9ea17a5e4ed 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-settings-view.hbs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-settings-view.hbs@@ -3,13 +3,13 @@<label class="chat-form__label"><span>{{i18n "chat.settings.mute"}}</span><ChatChannelSettingsSavedIndicator- @property={{this.channel.current_user_membership.muted}}+ @property={{this.channel.currentUserMembership.muted}}/></label><div class="chat-form__control"><ComboBox@content={{this.mutedOptions}}- @value={{this.channel.current_user_membership.muted}}+ @value={{this.channel.currentUserMembership.muted}}@valueProperty="value"@class="channel-settings-view__muted-selector"@onChange={{action (fn this.saveNotificationSettings "muted")}}@@ -17,18 +17,18 @@</div></div>- {{#unless this.channel.current_user_membership.muted}}+ {{#unless this.channel.currentUserMembership.muted}}<div class="chat-form__field"><label class="chat-form__label"><span>{{i18n "chat.settings.desktop_notification_level"}}</span><ChatChannelSettingsSavedIndicator- @property={{this.channel.current_user_membership.desktop_notification_level}}+ @property={{this.channel.currentUserMembership.desktop_notification_level}}/></label><div class="chat-form__control"><ComboBox@content={{this.notificationLevels}}- @value={{this.channel.current_user_membership.desktop_notification_level}}+ @value={{this.channel.currentUserMembership.desktop_notification_level}}@valueProperty="value"@class="channel-settings-view__desktop-notification-level-selector"@onChange={{action@@ -42,13 +42,13 @@<label class="chat-form__label"><span>{{i18n "chat.settings.mobile_notification_level"}}</span><ChatChannelSettingsSavedIndicator- @property={{this.channel.current_user_membership.mobile_notification_level}}+ @property={{this.channel.currentUserMembership.mobile_notification_level}}/></label><div class="chat-form__control"><ComboBox@content={{this.notificationLevels}}- @value={{this.channel.current_user_membership.mobile_notification_level}}+ @value={{this.channel.currentUserMembership.mobile_notification_level}}@valueProperty="value"@class="channel-settings-view__mobile-notification-level-selector"@onChange={{actiondiff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-settings-view.js b/plugins/chat/assets/javascripts/discourse/components/chat-channel-settings-view.jsindex 89a23c8575b..5367f4af96e 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-settings-view.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-settings-view.js@@ -1,7 +1,6 @@import Component from "@ember/component";import { action, computed } from "@ember/object";import { inject as service } from "@ember/service";-import ChatApi from "discourse/plugins/chat/discourse/lib/chat-api";import showModal from "discourse/lib/show-modal";import I18n from "I18n";import { Promise } from "rsvp";@@ -33,6 +32,7 @@ const CHANNEL_WIDE_MENTIONS_OPTIONS = [export default class ChatChannelSettingsView extends Component {@service chat;+ @service chatApi;@service chatGuardian;@service router;@service dialog;@@ -86,16 +86,26 @@ export default class ChatChannelSettingsView extends Component {const settings = {};settings[key] = value;- return ChatApi.updateChatChannelNotificationsSettings(- this.channel.id,- settings- ).then((membership) => {- this.channel.current_user_membership.setProperties({- muted: membership.muted,- desktop_notification_level: membership.desktop_notification_level,- mobile_notification_level: membership.mobile_notification_level,+ return this.chatApi+ .updateCurrentUserChatChannelNotificationsSettings(+ this.channel.id,+ settings+ )+ .then((result) => {+ [+ "muted",+ "desktop_notification_level",+ "mobile_notification_level",+ ].forEach((property) => {+ if (+ result.membership[property] !==+ this.channel.currentUserMembership[property]+ ) {+ this.channel.currentUserMembership[property] =+ result.membership[property];+ }+ });});- });}@action@@ -155,9 +165,10 @@ export default class ChatChannelSettingsView extends Component {const payload = {};payload[property] = value;- return ChatApi.modifyChatChannel(channel.id, payload)- .then((updatedChannel) => {- channel.set(property, updatedChannel[property]);+ return this.chatApi+ .updateChannel(channel.id, payload)+ .then((result) => {+ channel.set(property, result.channel[property]);}).catch((event) => {if (event.jqXHR?.responseJSON?.errors) {diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-toggle-view.js b/plugins/chat/assets/javascripts/discourse/components/chat-channel-toggle-view.jsindex 87c0cfd9b21..5ed0b2dbdf5 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-toggle-view.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-toggle-view.js@@ -3,12 +3,12 @@ import { htmlSafe } from "@ember/template";import { CHANNEL_STATUSES } from "discourse/plugins/chat/discourse/models/chat-channel";import I18n from "I18n";import { action, computed } from "@ember/object";-import { ajax } from "discourse/lib/ajax";import { inject as service } from "@ember/service";import { popupAjaxError } from "discourse/lib/ajax-error";export default class ChatChannelToggleView extends Component {@service chat;+ @service chatApi;@service router;tagName = "";channel = null;@@ -47,16 +47,11 @@ export default class ChatChannelToggleView extends Component {? CHANNEL_STATUSES.open: CHANNEL_STATUSES.closed;- return ajax(`/chat/chat_channels/${this.channel.id}/change_status.json`, {- method: "PUT",- data: { status },- })- .then(() => {- this.channel.set("status", status);- })- .catch(popupAjaxError)+ return this.chatApi+ .updateChannelStatus(this.channel.id, status).finally(() => {this.onStatusChange?.(this.channel);- });+ })+ .catch(popupAjaxError);}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-unread-indicator.hbs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-unread-indicator.hbsindex 4a53e0296a9..478d225337f 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-unread-indicator.hbs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-unread-indicator.hbs@@ -1,5 +1,16 @@-{{#if this.hasUnread}}- <div class="chat-channel-unread-indicator {{if this.isUrgent "urgent"}}">- <div class="number">{{this.unreadCount}}</div>+{{#if (gt @channel.currentUserMembership.unread_count 0)}}+ <div+ class={{concat-class+ "chat-channel-unread-indicator"+ (if+ (or+ @channel.isDirectMessageChannel+ (gt @channel.currentUserMembership.unread_mentions 0)+ )+ "urgent"+ )+ }}+ >+ <div class="number">{{@channel.currentUserMembership.unread_count}}</div></div>{{/if}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-unread-indicator.js b/plugins/chat/assets/javascripts/discourse/components/chat-channel-unread-indicator.jsdeleted file mode 100644index f24cd64a31b..00000000000--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-unread-indicator.js+++ /dev/null@@ -1,46 +0,0 @@-import discourseComputed from "discourse-common/utils/decorators";-import Component from "@ember/component";-import { equal, gt } from "@ember/object/computed";-import { CHATABLE_TYPES } from "discourse/plugins/chat/discourse/models/chat-channel";--export default Component.extend({- tagName: "",- channel: null,-- isDirectMessage: equal(- "channel.chatable_type",- CHATABLE_TYPES.directMessageChannel- ),-- hasUnread: gt("unreadCount", 0),-- @discourseComputed(- "currentUser.chat_channel_tracking_state.@each.{unread_count,unread_mentions}",- "channel.id"- )- channelTrackingState(state, channelId) {- return state?.[channelId];- },-- @discourseComputed(- "channelTrackingState.unread_mentions",- "channel",- "isDirectMessage"- )- isUrgent(unreadMentions, channel, isDirectMessage) {- if (!channel) {- return;- }-- return isDirectMessage || unreadMentions > 0;- },-- @discourseComputed("channelTrackingState.unread_count", "channel")- unreadCount(unreadCount, channel) {- if (!channel) {- return;- }-- return unreadCount || 0;- },-});diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-draft-channel-screen.js b/plugins/chat/assets/javascripts/discourse/components/chat-draft-channel-screen.jsindex e374564c35b..f8f00d3e920 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-draft-channel-screen.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-draft-channel-screen.js@@ -34,7 +34,7 @@ export default class ChatDraftChannelScreen extends Component {this.set("previewedChannel",ChatChannel.create(- Object.assign({}, response.chat_channel, { isDraft: true })+ Object.assign({}, response.channel, { isDraft: true })));})diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-drawer.js b/plugins/chat/assets/javascripts/discourse/components/chat-drawer.jsindex 3052f153983..35dab11417d 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-drawer.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-drawer.js@@ -17,6 +17,7 @@ export default Component.extend({draftChannelView: equal("view", DRAFT_CHANNEL_VIEW),chat: service(),router: service(),+ chatChannelsManager: service(),chatStateManager: service(),loading: false,showClose: true, // TODO - false when on same topic@@ -40,7 +41,6 @@ export default Component.extend({this,"openChannelAtMessage");- this.appEvents.on("chat:refresh-channels", this, "refreshChannels");this.appEvents.on("composer:closed", this, "_checkSize");this.appEvents.on("composer:opened", this, "_checkSize");this.appEvents.on("composer:resized", this, "_checkSize");@@ -68,7 +68,6 @@ export default Component.extend({this,"openChannelAtMessage");- this.appEvents.off("chat:refresh-channels", this, "refreshChannels");this.appEvents.off("composer:closed", this, "_checkSize");this.appEvents.off("composer:opened", this, "_checkSize");this.appEvents.off("composer:resized", this, "_checkSize");@@ -198,12 +197,9 @@ export default Component.extend({}},- @discourseComputed(- "chat.activeChannel",- "currentUser.chat_channel_tracking_state"- )- unreadCount(activeChannel, trackingState) {- return trackingState[activeChannel.id]?.unread_count || 0;+ @discourseComputed("chat.activeChannel.currentUserMembership.unread_count")+ unreadCount(count) {+ return count || 0;},@action@@ -218,7 +214,6 @@ export default Component.extend({switch (route.name) {case "chat":this.set("view", LIST_VIEW);- this.refreshChannels();this.appEvents.trigger("chat:float-toggled", false);return;case "chat.draft-channel":@@ -226,8 +221,8 @@ export default Component.extend({this.appEvents.trigger("chat:float-toggled", false);return;case "chat.channel":- return this.chat- .getChannelBy("id", route.params.channelId)+ return this.chatChannelsManager+ .find(route.params.channelId).then((channel) => {this.chat.set("messageId", route.queryParams.messageId);this.chat.setActiveChannel(channel);@@ -262,32 +257,6 @@ export default Component.extend({this.appEvents.trigger("chat:float-toggled", true);},- @action- refreshChannels() {- if (this.view === LIST_VIEW) {- this.fetchChannels();- }- },-- @action- fetchChannels() {- this.set("loading", true);-- this.chat.getChannels().then(() => {- if (this.isDestroying || this.isDestroyed) {- return;- }-- this.setProperties({- loading: false,- view: LIST_VIEW,- });-- this.chatStateManager.didExpandDrawer();- this.chat.setActiveChannel(null);- });- },-@actionswitchChannel(channel) {// we need next here to ensure we correctly let the time for routes transitionsdiff --git a/plugins/chat/assets/javascripts/discourse/components/chat-header-icon-unread-indicator.hbs b/plugins/chat/assets/javascripts/discourse/components/chat-header-icon-unread-indicator.hbsnew file mode 100644index 00000000000..c8af41c7876--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat-header-icon-unread-indicator.hbs@@ -0,0 +1,9 @@+{{#if (gt this.chatChannelsManager.unreadUrgentCount 0)}}+ <div class="chat-channel-unread-indicator urgent">+ <div class="number-wrap">+ <div class="number">{{this.chatChannelsManager.unreadUrgentCount}}</div>+ </div>+ </div>+{{else if (gt this.chatChannelsManager.unreadCount 0)}}+ <div class="chat-channel-unread-indicator"></div>+{{/if}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-header-icon-unread-indicator.js b/plugins/chat/assets/javascripts/discourse/components/chat-header-icon-unread-indicator.jsnew file mode 100644index 00000000000..df39429e489--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat-header-icon-unread-indicator.js@@ -0,0 +1,6 @@+import { inject as service } from "@ember/service";+import Component from "@glimmer/component";++export default class ChatHeaderIconUnreadIndicator extends Component {+ @service chatChannelsManager;+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-header-icon.hbs b/plugins/chat/assets/javascripts/discourse/components/chat-header-icon.hbsnew file mode 100644index 00000000000..4eb8b8ad9d8--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat-header-icon.hbs@@ -0,0 +1,21 @@+{{#if (and this.chatStateManager.isFullPageActive this.site.desktopView)}}+ <span class={{concat-class "icon" (if this.isActive "active")}}>+ {{d-icon "comment"}}++ {{#unless this.currentUserInDnD}}+ <ChatHeaderIconUnreadIndicator />+ {{/unless}}+ </span>+{{else}}+ <a+ href={{this.href}}+ tabindex="0"+ class={{concat-class "icon" (if this.isActive "active")}}+ >+ {{d-icon "comment"}}++ {{#unless this.currentUserInDnD}}+ <ChatHeaderIconUnreadIndicator />+ {{/unless}}+ </a>+{{/if}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-header-icon.js b/plugins/chat/assets/javascripts/discourse/components/chat-header-icon.jsnew file mode 100644index 00000000000..9753f8ab005--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/components/chat-header-icon.js@@ -0,0 +1,31 @@+import { inject as service } from "@ember/service";+import Component from "@glimmer/component";++export default class ChatHeaderIcon extends Component {+ @service currentUser;+ @service site;+ @service chatStateManager;++ get currentUserInDnD() {+ return this.currentUser.isInDoNotDisturb();+ }++ get href() {+ if (this.chatStateManager.isFullPageActive && this.site.mobileView) {+ return "/chat";+ }++ if (this.chatStateManager.isDrawerActive) {+ return "/chat";+ } else {+ return this.chatStateManager.lastKnownChatURL || "/chat";+ }+ }++ get isActive() {+ return (+ this.chatStateManager.isFullPageActive ||+ this.chatStateManager.isDrawerActive+ );+ }+}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-live-pane.hbs b/plugins/chat/assets/javascripts/discourse/components/chat-live-pane.hbsindex 2e1696714df..66d3a0e149c 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-live-pane.hbs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-live-pane.hbs@@ -21,6 +21,7 @@{{/if}}</div>+ <ChatChannelArchiveStatus @channel={{this.chatChannel}} /><ChatChannelStatus @channel={{this.chatChannel}} /></div>{{/if}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-live-pane.js b/plugins/chat/assets/javascripts/discourse/components/chat-live-pane.jsindex 4104ba0ba9f..320017945f5 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-live-pane.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-live-pane.js@@ -1,7 +1,5 @@import isElementInViewport from "discourse/lib/is-element-in-viewport";-import ChatApi from "discourse/plugins/chat/discourse/lib/chat-api";import { cloneJSON } from "discourse-common/lib/object";-import ChatChannel from "discourse/plugins/chat/discourse/models/chat-channel";import ChatMessage from "discourse/plugins/chat/discourse/models/chat-message";import Component from "@ember/component";import discourseComputed, {@@ -83,10 +81,12 @@ export default Component.extend({_mentionWarningsSeen: null, // Hashchat: service(),+ chatChannelsManager: service(),router: service(),chatEmojiPickerManager: service(),chatComposerPresenceManager: service(),chatStateManager: service(),+ chatApi: service(),getCachedChannelDetails: null,clearCachedChannelDetails: null,@@ -546,8 +546,7 @@ export default Component.extend({},_getLastReadId() {- return this.currentUser?.chat_channel_tracking_state?.[this.chatChannel.id]- ?.chat_message_id;+ return this.chatChannel.currentUserMembership.chat_message_id;},_markLastReadMessage(opts = { reRender: false }) {@@ -563,7 +562,6 @@ export default Component.extend({return;}- this.set("lastSendReadMessageId", lastReadId);const indexOfLastReadMessage =this.messages.findIndex((m) => m.id === lastReadId) || 0;let newestUnreadMessage = this.messages[indexOfLastReadMessage + 1];@@ -1009,7 +1007,8 @@ export default Component.extend({// Start ajax request but don't return here, we want to stage the message instantly when all messages are loaded.// Otherwise, we'll fetch latest and scroll to the one we just created.// Return a resolved promise below.- const msgCreationPromise = ChatApi.sendMessage(this.chatChannel.id, data)+ const msgCreationPromise = this.chatApi+ .sendMessage(this.chatChannel.id, data).catch((error) => {this._onSendError(data.staged_id, error);})@@ -1047,33 +1046,25 @@ export default Component.extend({},async _upsertChannelWithMessage(channel, message, uploads) {- let promise;+ let promise = Promise.resolve(channel);if (channel.isDirectMessageChannel || channel.isDraft) {promise = this.chat.upsertDmChannelForUsernames(channel.chatable.users.mapBy("username"));- } else {- promise = ChatApi.loading(channel.id).then(() => channel);}- return promise- .then((c) => {- c.current_user_membership.set("following", true);- return this.chat.startTrackingChannel(c);+ return promise.then((c) =>+ ajax(`/chat/${c.id}.json`, {+ type: "POST",+ data: {+ message,+ upload_ids: (uploads || []).mapBy("id"),+ },+ }).then(() => {+ this.onSwitchChannel(c);})- .then((c) =>- ajax(`/chat/${c.id}.json`, {- type: "POST",- data: {- message,- upload_ids: (uploads || []).mapBy("id"),- },- }).then(() => {- this.chat.forceRefreshChannels();- this.onSwitchChannel(ChatChannel.create(c));- })- );+ );},_onSendError(stagedId, error) {@@ -1103,7 +1094,8 @@ export default Component.extend({staged_id: stagedMessage.stagedId,};- ChatApi.sendMessage(this.chatChannel.id, data)+ this.chatApi+ .sendMessage(this.chatChannel.id, data).catch((error) => {this._onSendError(data.staged_id, error);})diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message-move-to-channel-modal-inner.hbs b/plugins/chat/assets/javascripts/discourse/components/chat-message-move-to-channel-modal-inner.hbsindex 2c7ba4de58e..48c9c87792d 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-message-move-to-channel-modal-inner.hbs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message-move-to-channel-modal-inner.hbs@@ -6,11 +6,23 @@<p>{{this.instructionsText}}</p></div>- <ChatChannelChooser @class="chat-move-message-channel-chooser" @content={{this.availableChannels}} @value={{this.destinationChannelId}} @nameProperty="title" />+ <ChatChannelChooser+ @class="chat-move-message-channel-chooser"+ @content={{this.availableChannels}}+ @value={{this.destinationChannelId}}+ @nameProperty="title"+ /></DModalBody><div class="modal-footer">- <DButton @class="btn-primary" @icon="sign-out-alt" @disabled={{this.disableMoveButton}} @action={{action "moveMessages"}} @label="chat.move_to_channel.confirm_move" @id="chat-confirm-move-messages-to-channel" />+ <DButton+ @class="btn-primary"+ @icon="sign-out-alt"+ @disabled={{this.disableMoveButton}}+ @action={{action "moveMessages"}}+ @label="chat.move_to_channel.confirm_move"+ @id="chat-confirm-move-messages-to-channel"+ /><DButton @label="cancel" @class="btn-flat" @action={{this.closeModal}} /></div>diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message-move-to-channel-modal-inner.js b/plugins/chat/assets/javascripts/discourse/components/chat-message-move-to-channel-modal-inner.jsindex 3045b7f4ed7..7d404060d25 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-message-move-to-channel-modal-inner.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message-move-to-channel-modal-inner.js@@ -3,14 +3,15 @@ import I18n from "I18n";import { reads } from "@ember/object/computed";import { isBlank } from "@ember/utils";import { action, computed } from "@ember/object";-import { ajax } from "discourse/lib/ajax";import { inject as service } from "@ember/service";import { popupAjaxError } from "discourse/lib/ajax-error";import { htmlSafe } from "@ember/template";export default class MoveToChannelModalInner extends Component {@service chat;+ @service chatApi;@service router;+ @service chatChannelsManager;tagName = "";sourceChannel = null;destinationChannelId = null;@@ -23,31 +24,25 @@ export default class MoveToChannelModalInner extends Component {return isBlank(this.destinationChannelId);}- @computed("chat.publicChannels.[]")+ @computed("chatChannelsManager.publicMessageChannels.[]")get availableChannels() {- return this.chat.publicChannels.rejectBy("id", this.sourceChannel.id);+ return this.chatChannelsManager.publicMessageChannels.rejectBy(+ "id",+ this.sourceChannel.id+ );}@actionmoveMessages() {- return ajax(- `/chat/${this.sourceChannel.id}/move_messages_to_channel.json`,- {- method: "PUT",- data: {- message_ids: this.selectedMessageIds,- destination_channel_id: this.destinationChannelId,- },- }- )+ return this.chatApi+ .moveChannelMessages(this.sourceChannel.id, {+ message_ids: this.selectedMessageIds,+ destination_channel_id: this.destinationChannelId,+ }).then((response) => {- this.router.transitionTo(- "chat.channel",+ return this.chat.openChannelAtMessage(response.destination_channel_id,- response.destination_channel_title,- {- queryParams: { messageId: response.first_moved_message_id },- }+ response.first_moved_message_id);}).catch(popupAjaxError);diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message.hbs b/plugins/chat/assets/javascripts/discourse/components/chat-message.hbsindex f93d4213caf..db545f463f6 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-message.hbs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message.hbs@@ -27,6 +27,7 @@(if this.selectingMessages "selecting-messages")}}data-id={{or this.message.id this.message.stagedId}}+ data-staged-id={{if this.message.staged this.message.stagedId}}>{{#if this.show}}{{#if this.selectingMessages}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-message.js b/plugins/chat/assets/javascripts/discourse/components/chat-message.jsindex 867610bdf31..8f82d105015 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-message.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-message.js@@ -43,6 +43,7 @@ export default Component.extend({onHoverMessage: null,chatEmojiReactionStore: service("chat-emoji-reaction-store"),chatEmojiPickerManager: service("chat-emoji-picker-manager"),+ chatChannelsManager: service("chat-channels-manager"),adminTools: optionalService(),_hasSubscribedToAppEvents: false,tagName: "",@@ -589,13 +590,11 @@ export default Component.extend({// so we will fully refresh if we were not members of the channel// alreadyif (!this.chatChannel.isFollowing || this.chatChannel.isDraft) {- this.chat.forceRefreshChannels().then(() => {- return this.chat- .getChannelBy("id", this.chatChannel.id)- .then((reactedChannel) => {- this.onSwitchChannel(reactedChannel);- });- });+ return this.chatChannelsManager+ .getChannel(this.chatChannel.id)+ .then((reactedChannel) => {+ this.onSwitchChannel(reactedChannel);+ });}});},diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-to-topic-selector.js b/plugins/chat/assets/javascripts/discourse/components/chat-to-topic-selector.jsindex e7ae0190ffc..eb44133b1f8 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-to-topic-selector.js+++ b/plugins/chat/assets/javascripts/discourse/components/chat-to-topic-selector.js@@ -3,9 +3,9 @@ import { htmlSafe } from "@ember/template";import discourseComputed from "discourse-common/utils/decorators";import { alias, equal } from "@ember/object/computed";-export const NEW_TOPIC_SELECTION = "newTopic";-export const EXISTING_TOPIC_SELECTION = "existingTopic";-export const NEW_MESSAGE_SELECTION = "newMessage";+export const NEW_TOPIC_SELECTION = "new_topic";+export const EXISTING_TOPIC_SELECTION = "existing_topic";+export const NEW_MESSAGE_SELECTION = "new_message";export default Component.extend({newTopicSelection: NEW_TOPIC_SELECTION,diff --git a/plugins/chat/assets/javascripts/discourse/components/full-page-chat.js b/plugins/chat/assets/javascripts/discourse/components/full-page-chat.jsindex 76edf0f21ee..a736c4e9011 100644--- a/plugins/chat/assets/javascripts/discourse/components/full-page-chat.js+++ b/plugins/chat/assets/javascripts/discourse/components/full-page-chat.js@@ -10,9 +10,6 @@ export default Component.extend({init() {this._super(...arguments);-- this.appEvents.on("chat:refresh-channels", this, "refreshModel");- this.appEvents.on("chat:refresh-channel", this, "_refreshChannel");},didInsertElement() {@@ -25,8 +22,6 @@ export default Component.extend({willDestroyElement() {this._super(...arguments);- this.appEvents.off("chat:refresh-channels", this, "refreshModel");- this.appEvents.off("chat:refresh-channel", this, "_refreshChannel");document.removeEventListener("keydown", this._autoFocusChatComposer);},@@ -77,12 +72,6 @@ export default Component.extend({}},- _refreshChannel(channelId) {- if (this.chat.activeChannel?.id === channelId) {- this.refreshModel(true);- }- },-@actionnavigateToIndex() {this.router.transitionTo("chat.index");diff --git a/plugins/chat/assets/javascripts/discourse/components/toggle-channel-membership-button.hbs b/plugins/chat/assets/javascripts/discourse/components/toggle-channel-membership-button.hbsindex a8b2d2c538c..00751d14915 100644--- a/plugins/chat/assets/javascripts/discourse/components/toggle-channel-membership-button.hbs+++ b/plugins/chat/assets/javascripts/discourse/components/toggle-channel-membership-button.hbs@@ -1,4 +1,4 @@-{{#if this.channel.isFollowing}}+{{#if @channel.currentUserMembership.following}}<DButton@action={{action "onLeaveChannel"}}@translatedLabel={{this.label}}diff --git a/plugins/chat/assets/javascripts/discourse/components/toggle-channel-membership-button.js b/plugins/chat/assets/javascripts/discourse/components/toggle-channel-membership-button.jsindex 866e85c26b4..b6cceec6324 100644--- a/plugins/chat/assets/javascripts/discourse/components/toggle-channel-membership-button.js+++ b/plugins/chat/assets/javascripts/discourse/components/toggle-channel-membership-button.js@@ -1,53 +1,44 @@-import Component from "@ember/component";+import Component from "@glimmer/component";import I18n from "I18n";import { inject as service } from "@ember/service";import { popupAjaxError } from "discourse/lib/ajax-error";-import { action, computed } from "@ember/object";-+import { action } from "@ember/object";+import { tracked } from "@glimmer/tracking";export default class ToggleChannelMembershipButton extends Component {@service chat;-- tagName = "";- channel = null;+ @tracked isLoading = false;onToggle = null;- options = null;- isLoading = false;+ options = {};- init() {- super.init(...arguments);+ constructor() {+ super(...arguments);- this.set(- "options",- Object.assign(- {- labelType: "normal",- joinTitle: I18n.t("chat.channel_settings.join_channel"),- joinIcon: "",- joinClass: "",- leaveTitle: I18n.t("chat.channel_settings.leave_channel"),- leaveIcon: "",- leaveClass: "",- },- this.options || {}- )- );+ this.options = {+ labelType: "normal",+ joinTitle: I18n.t("chat.channel_settings.join_channel"),+ joinIcon: "",+ joinClass: "",+ leaveTitle: I18n.t("chat.channel_settings.leave_channel"),+ leaveIcon: "",+ leaveClass: "",+ ...this.args.options,+ };}- @computed("channel.current_user_membership.following")get label() {if (this.options.labelType === "none") {return "";}if (this.options.labelType === "short") {- if (this.channel.isFollowing) {+ if (this.args.channel.currentUserMembership.following) {return I18n.t("chat.channel_settings.leave");} else {return I18n.t("chat.channel_settings.join");}}- if (this.channel.isFollowing) {+ if (this.args.channel.currentUserMembership.following) {return I18n.t("chat.channel_settings.leave_channel");} else {return I18n.t("chat.channel_settings.join_channel");@@ -56,10 +47,10 @@ export default class ToggleChannelMembershipButton extends Component {@actiononJoinChannel() {- this.set("isLoading", true);+ this.isLoading = true;return this.chat- .followChannel(this.channel)+ .followChannel(this.args.channel).then(() => {this.onToggle?.();})@@ -69,16 +60,16 @@ export default class ToggleChannelMembershipButton extends Component {return;}- this.set("isLoading", false);+ this.isLoading = false;});}@actiononLeaveChannel() {- this.set("isLoading", true);+ this.isLoading = true;return this.chat- .unfollowChannel(this.channel)+ .unfollowChannel(this.args.channel).then(() => {this.onToggle?.();})@@ -88,7 +79,7 @@ export default class ToggleChannelMembershipButton extends Component {return;}- this.set("isLoading", false);+ this.isLoading = false;});}}diff --git a/plugins/chat/assets/javascripts/discourse/controllers/chat-channel-edit-description.js b/plugins/chat/assets/javascripts/discourse/controllers/chat-channel-edit-description.jsindex 0efdb70bbf1..85e834963ae 100644--- a/plugins/chat/assets/javascripts/discourse/controllers/chat-channel-edit-description.js+++ b/plugins/chat/assets/javascripts/discourse/controllers/chat-channel-edit-description.js@@ -1,11 +1,12 @@import Controller from "@ember/controller";import { action, computed } from "@ember/object";import ModalFunctionality from "discourse/mixins/modal-functionality";-import ChatApi from "discourse/plugins/chat/discourse/lib/chat-api";+import { inject as service } from "@ember/service";export default class ChatChannelEditDescriptionController extends Controller.extend(ModalFunctionality) {+ @service chatApi;editedDescription = "";@computed("model.description", "editedDescription")@@ -27,11 +28,12 @@ export default class ChatChannelEditDescriptionController extends Controller.ext@actiononSaveChatChannelDescription() {- return ChatApi.modifyChatChannel(this.model.id, {- description: this.editedDescription,- })- .then((chatChannel) => {- this.model.set("description", chatChannel.description);+ return this.chatApi+ .updateChannel(this.model.id, {+ description: this.editedDescription,+ })+ .then((result) => {+ this.model.set("description", result.channel.description);this.send("closeModal");}).catch((event) => {diff --git a/plugins/chat/assets/javascripts/discourse/controllers/chat-channel-edit-title.js b/plugins/chat/assets/javascripts/discourse/controllers/chat-channel-edit-title.jsindex 9eb3dbde1f5..d57ad3f6ce6 100644--- a/plugins/chat/assets/javascripts/discourse/controllers/chat-channel-edit-title.js+++ b/plugins/chat/assets/javascripts/discourse/controllers/chat-channel-edit-title.js@@ -1,11 +1,11 @@import Controller from "@ember/controller";import { action, computed } from "@ember/object";import ModalFunctionality from "discourse/mixins/modal-functionality";-import ChatApi from "discourse/plugins/chat/discourse/lib/chat-api";-+import { inject as service } from "@ember/service";export default class ChatChannelEditTitleController extends Controller.extend(ModalFunctionality) {+ @service chatApi;editedTitle = "";@computed("model.title", "editedTitle")@@ -27,11 +27,12 @@ export default class ChatChannelEditTitleController extends Controller.extend(@actiononSaveChatChannelTitle() {- return ChatApi.modifyChatChannel(this.model.id, {- name: this.editedTitle,- })- .then((chatChannel) => {- this.model.set("title", chatChannel.title);+ return this.chatApi+ .updateChannel(this.model.id, {+ name: this.editedTitle,+ })+ .then((result) => {+ this.model.set("title", result.channel.title);this.send("closeModal");}).catch((event) => {diff --git a/plugins/chat/assets/javascripts/discourse/controllers/chat-channel-info-about.js b/plugins/chat/assets/javascripts/discourse/controllers/chat-channel-info-about.jsindex c7976a24ff7..d33ec8fd222 100644--- a/plugins/chat/assets/javascripts/discourse/controllers/chat-channel-info-about.js+++ b/plugins/chat/assets/javascripts/discourse/controllers/chat-channel-info-about.js@@ -8,13 +8,13 @@ export default class ChatChannelInfoAboutController extends Controller.extend() {@actiononEditChatChannelTitle() {- showModal("chat-channel-edit-title", { model: this.model?.chatChannel });+ showModal("chat-channel-edit-title", { model: this.model });}@actiononEditChatChannelDescription() {showModal("chat-channel-edit-description", {- model: this.model?.chatChannel,+ model: this.model,});}}diff --git a/plugins/chat/assets/javascripts/discourse/controllers/chat-channel-info.js b/plugins/chat/assets/javascripts/discourse/controllers/chat-channel-info.jsindex 720e6f635f3..65c132080d9 100644--- a/plugins/chat/assets/javascripts/discourse/controllers/chat-channel-info.js+++ b/plugins/chat/assets/javascripts/discourse/controllers/chat-channel-info.js@@ -1,7 +1,7 @@import Controller from "@ember/controller";-import { action, computed } from "@ember/object";import { inject as service } from "@ember/service";import { reads } from "@ember/object/computed";+import { computed } from "@ember/object";export default class ChatChannelInfoIndexController extends Controller {@service router;@@ -10,28 +10,25 @@ export default class ChatChannelInfoIndexController extends Controller {@reads("router.currentRoute.localName") tab;- @computed("model.chatChannel.{membershipsCount,status}")+ @computed("model.{membershipsCount,status,currentUserMembership.following}")get tabs() {const tabs = [];- if (!this.model.chatChannel.isDirectMessageChannel) {+ if (!this.model.isDirectMessageChannel) {tabs.push("about");}- if (- this.model.chatChannel.isOpen &&- this.model.chatChannel.membershipsCount >= 1- ) {+ if (this.model.isOpen && this.model.membershipsCount >= 1) {tabs.push("members");}- tabs.push("settings");+ if (+ this.currentUser?.staff ||+ this.model.currentUserMembership?.following+ ) {+ tabs.push("settings");+ }return tabs;}-- @action- switchChannel(channel) {- return this.chat.openChannel(channel);- }}diff --git a/plugins/chat/assets/javascripts/discourse/controllers/create-channel.js b/plugins/chat/assets/javascripts/discourse/controllers/create-channel.jsindex 00b9b8e0aef..ae2ed12f483 100644--- a/plugins/chat/assets/javascripts/discourse/controllers/create-channel.js+++ b/plugins/chat/assets/javascripts/discourse/controllers/create-channel.js@@ -1,10 +1,7 @@import { escapeExpression } from "discourse/lib/utilities";import Controller from "@ember/controller";-import ChatApi from "discourse/plugins/chat/discourse/lib/chat-api";-import ChatChannel from "discourse/plugins/chat/discourse/models/chat-channel";import I18n from "I18n";import ModalFunctionality from "discourse/mixins/modal-functionality";-import { ajax } from "discourse/lib/ajax";import { action, computed } from "@ember/object";import { gt, notEmpty } from "@ember/object/computed";import { inject as service } from "@ember/service";@@ -23,6 +20,8 @@ export default class CreateChannelController extends Controller.extend() {@service chat;@service dialog;+ @service chatChannelsManager;+ @service chatApi;category = null;categoryId = null;@@ -57,20 +56,18 @@ export default class CreateChannelController extends Controller.extend(_createChannel() {const data = {- id: this.categoryId,+ chatable_id: this.categoryId,name: this.name,description: this.description,auto_join_users: this.autoJoinUsers,};- return ajax("/chat/chat_channels", { method: "PUT", data })- .then((response) => {- const chatChannel = ChatChannel.create(response.chat_channel);-- return this.chat.startTrackingChannel(chatChannel).then(() => {- this.send("closeModal");- this.chat.openChannel(chatChannel);- });+ return this.chatApi+ .createChannel(data)+ .then((channel) => {+ this.send("closeModal");+ this.chatChannelsManager.follow(channel);+ this.chat.openChannel(channel);}).catch((e) => {this.flash(e.jqXHR.responseJSON.errors[0], "error");@@ -117,24 +114,26 @@ export default class CreateChannelController extends Controller.extend(if (category) {const fullSlug = this._buildCategorySlug(category);- return ChatApi.categoryPermissions(category.id).then((catPermissions) => {- this._updateAutoJoinConfirmWarning(category, catPermissions);- const allowedGroups = catPermissions.allowed_groups;- const translationKey =- allowedGroups.length < 3 ? "hint_groups" : "hint_multiple_groups";-- this.set(- "categoryPermissionsHint",- htmlSafe(- I18n.t(`chat.create_channel.choose_category.${translationKey}`, {- link: `/c/${escapeExpression(fullSlug)}/edit/security`,- hint: escapeExpression(allowedGroups[0]),- hint_2: escapeExpression(allowedGroups[1]),- count: allowedGroups.length,- })- )- );- });+ return this.chatApi+ .categoryPermissions(category.id)+ .then((catPermissions) => {+ this._updateAutoJoinConfirmWarning(category, catPermissions);+ const allowedGroups = catPermissions.allowed_groups;+ const translationKey =+ allowedGroups.length < 3 ? "hint_groups" : "hint_multiple_groups";++ this.set(+ "categoryPermissionsHint",+ htmlSafe(+ I18n.t(`chat.create_channel.choose_category.${translationKey}`, {+ link: `/c/${escapeExpression(fullSlug)}/edit/security`,+ hint: escapeExpression(allowedGroups[0]),+ hint_2: escapeExpression(allowedGroups[1]),+ count: allowedGroups.length,+ })+ )+ );+ });} else {this.set("categoryPermissionsHint", DEFAULT_HINT);this.set("autoJoinWarning", "");diff --git a/plugins/chat/assets/javascripts/discourse/initializers/chat-setup.js b/plugins/chat/assets/javascripts/discourse/initializers/chat-setup.jsindex ee754a1e75e..c892853691c 100644--- a/plugins/chat/assets/javascripts/discourse/initializers/chat-setup.js+++ b/plugins/chat/assets/javascripts/discourse/initializers/chat-setup.js@@ -12,15 +12,13 @@ export default {name: "chat-setup",initialize(container) {this.chatService = container.lookup("service:chat");-- if (!this.chatService.userCanChat) {- return;- }-this.siteSettings = container.lookup("service:site-settings");this.appEvents = container.lookup("service:appEvents");this.appEvents.on("discourse:focus-changed", this, "_handleFocusChanged");+ if (!this.chatService.userCanChat) {+ return;+ }withPluginApi("0.12.1", (api) => {api.registerChatComposerButton({id: "chat-upload-btn",@@ -99,8 +97,6 @@ export default {const currentUser = api.getCurrentUser();if (currentUser?.chat_channels) {this.chatService.setupWithPreloadedChannels(currentUser.chat_channels);- } else {- this.chatService.setupWithoutPreloadedChannels();}const chatNotificationManager = container.lookup(@@ -115,19 +111,7 @@ export default {api.addCardClickListenerSelector(".chat-drawer-outlet");- api.dispatchWidgetAppEvent(- "site-header",- "header-chat-link",- "chat:rerender-header"- );-- api.dispatchWidgetAppEvent(- "sidebar-header",- "header-chat-link",- "chat:rerender-header"- );-- api.addToHeaderIcons("header-chat-link");+ api.addToHeaderIcons("chat-header-icon");api.decorateChatMessage(function (chatMessage, chatChannel) {if (!this.currentUser) {@@ -155,17 +139,22 @@ export default {},teardown() {+ this.appEvents.off("discourse:focus-changed", this, "_handleFocusChanged");+if (!this.chatService.userCanChat) {return;}- this.appEvents.off("discourse:focus-changed", this, "_handleFocusChanged");_lastForcedRefreshAt = null;clearChatComposerButtons();},@bind_handleFocusChanged(hasFocus) {+ if (!this.chatService.userCanChat) {+ return;+ }+if (!hasFocus) {_lastForcedRefreshAt = Date.now();return;@@ -179,6 +168,5 @@ export default {}_lastForcedRefreshAt = Date.now();- this.chatService.refreshTrackingState();},};diff --git a/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js b/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.jsindex e7c417e8e1e..547632c6c77 100644--- a/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js+++ b/plugins/chat/assets/javascripts/discourse/initializers/chat-sidebar.js@@ -25,41 +25,12 @@ export default {api.addSidebarSection((BaseCustomSidebarSection, BaseCustomSidebarSectionLink) => {const SidebarChatChannelsSectionLink = class extends BaseCustomSidebarSectionLink {- @tracked chatChannelTrackingState =- this.chatService.currentUser.chat_channel_tracking_state[- this.channel.id- ];-constructor({ channel, chatService }) {super(...arguments);this.channel = channel;this.chatService = chatService;}- @bind- willDestroy() {- this.chatService.appEvents.off(- "chat:user-tracking-state-changed",- this._refreshTrackingState- );- }-- @bind- didInsert() {- this.chatService.appEvents.on(- "chat:user-tracking-state-changed",- this._refreshTrackingState- );- }-- @bind- _refreshTrackingState() {- this.chatChannelTrackingState =- this.chatService.currentUser.chat_channel_tracking_state[- this.channel.id- ];- }-get name() {return dasherize(slugifyChannel(this.channel));}@@ -68,7 +39,7 @@ export default {get classNames() {const classes = [];- if (this.channel.current_user_membership.muted) {+ if (this.channel.currentUserMembership.muted) {classes.push("sidebar-section-link--muted");}@@ -76,6 +47,8 @@ export default {classes.push("sidebar-section-link--active");}+ classes.push(`channel-${this.channel.id}`);+return classes.join(" ");}@@ -118,26 +91,19 @@ export default {}get suffixValue() {- return this.chatChannelTrackingState?.unread_count > 0+ return this.channel.currentUserMembership.unread_count > 0? "circle": "";}get suffixCSSClass() {- return this.chatChannelTrackingState?.unread_mentions > 0+ return this.channel.currentUserMembership.unread_mentions > 0? "urgent": "unread";}};const SidebarChatChannelsSection = class extends BaseCustomSidebarSection {- @tracked sectionLinks = [];-- @tracked sectionIndicator =- this.chatService.publicChannels &&- this.chatService.publicChannels[0].current_user_membership- .unread_count;-@tracked currentUserCanJoinPublicChannels =this.sidebar.currentUser &&(this.sidebar.currentUser.staff ||@@ -150,39 +116,22 @@ export default {return;}this.chatService = container.lookup("service:chat");+ this.chatChannelsManager = container.lookup(+ "service:chat-channels-manager"+ );this.router = container.lookup("service:router");- this.appEvents = container.lookup("service:app-events");- this.appEvents.on("chat:refresh-channels", this._refreshChannels);- this._refreshChannels();}- @bind- willDestroy() {- if (!this.appEvents) {- return;- }- this.appEvents.off(- "chat:refresh-channels",- this._refreshChannels+ get sectionLinks() {+ return this.chatChannelsManager.publicMessageChannels.map(+ (channel) =>+ new SidebarChatChannelsSectionLink({+ channel,+ chatService: this.chatService,+ }));}- @bind- _refreshChannels() {- const newSectionLinks = [];- this.chatService.getChannels().then((channels) => {- channels.publicChannels.forEach((channel) => {- newSectionLinks.push(- new SidebarChatChannelsSectionLink({- channel,- chatService: this.chatService,- })- );- });- this.sectionLinks = newSectionLinks;- });- }-get name() {return "chat-channels";}@@ -228,11 +177,6 @@ export default {api.addSidebarSection((BaseCustomSidebarSection, BaseCustomSidebarSectionLink) => {const SidebarChatDirectMessagesSectionLink = class extends BaseCustomSidebarSectionLink {- @tracked chatChannelTrackingState =- this.chatService.currentUser.chat_channel_tracking_state[- this.channel.id- ];-constructor({ channel, chatService }) {super(...arguments);this.channel = channel;@@ -258,7 +202,7 @@ export default {get classNames() {const classes = [];- if (this.channel.current_user_membership.muted) {+ if (this.channel.currentUserMembership.muted) {classes.push("sidebar-section-link--muted");}@@ -266,6 +210,8 @@ export default {classes.push("sidebar-section-link--active");}+ classes.push(`channel-${this.channel.id}`);+return classes.join(" ");}@@ -340,7 +286,7 @@ export default {}get suffixValue() {- return this.chatChannelTrackingState?.unread_count > 0+ return this.channel.currentUserMembership.unread_count > 0? "circle": "";}@@ -396,7 +342,6 @@ export default {const SidebarChatDirectMessagesSection = class extends BaseCustomSidebarSection {@service site;@service router;- @tracked sectionLinks = [];@tracked userCanDirectMessage =this.chatService.userCanDirectMessage;@@ -407,42 +352,21 @@ export default {return;}this.chatService = container.lookup("service:chat");- this.chatService.appEvents.on(- "chat:user-tracking-state-changed",- this._refreshDirectMessageChannels+ this.chatChannelsManager = container.lookup(+ "service:chat-channels-manager");- this._refreshDirectMessageChannels();}- @bind- willDestroy() {- if (container.isDestroyed) {- return;- }- this.chatService.appEvents.off(- "chat:user-tracking-state-changed",- this._refreshDirectMessageChannels+ get sectionLinks() {+ return this.chatChannelsManager.truncatedDirectMessageChannels.map(+ (channel) =>+ new SidebarChatDirectMessagesSectionLink({+ channel,+ chatService: this.chatService,+ }));}- @bind- _refreshDirectMessageChannels() {- const newSectionLinks = [];- this.chatService.getChannels().then((channels) => {- this.chatService- .truncateDirectMessageChannels(channels.directMessageChannels)- .forEach((channel) => {- newSectionLinks.push(- new SidebarChatDirectMessagesSectionLink({- channel,- chatService: this.chatService,- })- );- });- this.sectionLinks = newSectionLinks;- });- }-get name() {return "chat-dms";}diff --git a/plugins/chat/assets/javascripts/discourse/lib/chat-api.js b/plugins/chat/assets/javascripts/discourse/lib/chat-api.jsdeleted file mode 100644index 3b373570a72..00000000000--- a/plugins/chat/assets/javascripts/discourse/lib/chat-api.js+++ /dev/null@@ -1,95 +0,0 @@-import { ajax } from "discourse/lib/ajax";-import { popupAjaxError } from "discourse/lib/ajax-error";-import ChatChannel from "discourse/plugins/chat/discourse/models/chat-channel";-export default class ChatApi {- static async chatChannelMemberships(channelId, data) {- return await ajax(`/chat/api/chat_channels/${channelId}/memberships.json`, {- data,- }).catch(popupAjaxError);- }-- static async updateChatChannelNotificationsSettings(channelId, data = {}) {- return await ajax(- `/chat/api/chat_channels/${channelId}/notifications_settings.json`,- {- method: "PUT",- data,- }- ).catch(popupAjaxError);- }-- static async sendMessage(channelId, data = {}) {- return ajax(`/chat/${channelId}.json`, {- ignoreUnsent: false,- method: "POST",- data,- });- }-- static async chatChannels(data = {}) {- if (data?.status === "all") {- delete data.status;- }-- return await ajax(`/chat/api/chat_channels.json`, {- method: "GET",- data,- })- .then((channels) =>- channels.map((channel) => ChatChannel.create(channel))- )- .catch(popupAjaxError);- }-- static async modifyChatChannel(channelId, data) {- return await this._performRequest(- `/chat/api/chat_channels/${channelId}.json`,- {- method: "PUT",- data,- }- );- }-- static async unfollowChatChannel(channel) {- return await this._performRequest(- `/chat/chat_channels/${channel.id}/unfollow.json`,- {- method: "POST",- }- ).then((updatedChannel) => {- channel.updateMembership(updatedChannel.current_user_membership);-- // doesn't matter if this is inaccurate, it will be eventually consistent- // via the channel-metadata MessageBus channel- channel.set("memberships_count", channel.memberships_count - 1);- return channel;- });- }-- static async followChatChannel(channel) {- return await this._performRequest(- `/chat/chat_channels/${channel.id}/follow.json`,- {- method: "POST",- }- ).then((updatedChannel) => {- channel.updateMembership(updatedChannel.current_user_membership);-- // doesn't matter if this is inaccurate, it will be eventually consistent- // via the channel-metadata MessageBus channel- channel.set("memberships_count", channel.memberships_count + 1);- return channel;- });- }-- static async categoryPermissions(categoryId) {- return await this._performRequest(- `/chat/api/category-chatables/${categoryId}/permissions.json`- );- }-- static async _performRequest(...args) {- return await ajax(...args).catch(popupAjaxError);- }-}diff --git a/plugins/chat/assets/javascripts/discourse/models/chat-channel.js b/plugins/chat/assets/javascripts/discourse/models/chat-channel.jsindex 7dca63e974b..182b01a1ec3 100644--- a/plugins/chat/assets/javascripts/discourse/models/chat-channel.js+++ b/plugins/chat/assets/javascripts/discourse/models/chat-channel.js@@ -1,15 +1,16 @@import RestModel from "discourse/models/rest";import I18n from "I18n";-import { computed } from "@ember/object";import User from "discourse/models/user";import UserChatChannelMembership from "discourse/plugins/chat/discourse/models/user-chat-channel-membership";import { ajax } from "discourse/lib/ajax";import { escapeExpression } from "discourse/lib/utilities";+import { tracked } from "@glimmer/tracking";export const CHATABLE_TYPES = {directMessageChannel: "DirectMessage",categoryChannel: "Category",};+export const CHANNEL_STATUSES = {open: "open",readOnly: "read_only",@@ -38,13 +39,10 @@ export function channelStatusIcon(channelStatus) {switch (channelStatus) {case CHANNEL_STATUSES.closed:return "lock";- break;case CHANNEL_STATUSES.readOnly:return "comment-slash";- break;case CHANNEL_STATUSES.archived:return "archive";- break;}}@@ -60,62 +58,51 @@ const READONLY_STATUSES = [];export default class ChatChannel extends RestModel {- isDraft = false;- lastSendReadMessageId = null;+ @tracked currentUserMembership = null;+ @tracked isDraft = false;+ @tracked title;+ @tracked description;+ @tracked chatableType;+ @tracked status;- @computed("title")get escapedTitle() {return escapeExpression(this.title);}- @computed("description")get escapedDescription() {return escapeExpression(this.description);}- @computed("chatable_type")get isDirectMessageChannel() {return this.chatable_type === CHATABLE_TYPES.directMessageChannel;}- @computed("chatable_type")get isCategoryChannel() {return this.chatable_type === CHATABLE_TYPES.categoryChannel;}- @computed("status")get isOpen() {return !this.status || this.status === CHANNEL_STATUSES.open;}- @computed("status")get isReadOnly() {return this.status === CHANNEL_STATUSES.readOnly;}- @computed("status")get isClosed() {return this.status === CHANNEL_STATUSES.closed;}- @computed("status")get isArchived() {return this.status === CHANNEL_STATUSES.archived;}- @computed("isArchived", "isOpen")get isJoinable() {return this.isOpen && !this.isArchived;}- @computed("memberships_count")- get membershipsCount() {- return this.memberships_count;- }-- @computed("current_user_membership.following")get isFollowing() {- return this.current_user_membership.following;+ return this.currentUserMembership.following;}canModifyMessages(user) {@@ -127,12 +114,12 @@ export default class ChatChannel extends RestModel {}updateMembership(membership) {- this.current_user_membership.setProperties({- following: membership.following,- muted: membership.muted,- desktop_notification_level: membership.desktop_notification_level,- mobile_notification_level: membership.mobile_notification_level,- });+ this.currentUserMembership.following = membership.following;+ this.currentUserMembership.muted = membership.muted;+ this.currentUserMembership.desktop_notification_level =+ membership.desktop_notification_level;+ this.currentUserMembership.mobile_notification_level =+ membership.mobile_notification_level;}updateLastReadMessage(messageId) {@@ -143,7 +130,7 @@ export default class ChatChannel extends RestModel {return ajax(`/chat/${this.id}/read/${messageId}.json`, {method: "PUT",}).then(() => {- this.set("lastSendReadMessageId", messageId);+ this.currentUserMembership.last_read_message_id = messageId;});}}@@ -151,11 +138,12 @@ export default class ChatChannel extends RestModel {ChatChannel.reopenClass({create(args) {args = args || {};+this._initUserModels(args);this._initUserMembership(args);- args.lastSendReadMessageId =- args.current_user_membership?.last_read_message_id;+ args.chatableType = args.chatable_type;+ args.membershipsCount = args.memberships_count;return this._super(args);},@@ -170,11 +158,11 @@ ChatChannel.reopenClass({},_initUserMembership(args) {- if (args.current_user_membership instanceof UserChatChannelMembership) {+ if (args.currentUserMembership instanceof UserChatChannelMembership) {return;}- args.current_user_membership = UserChatChannelMembership.create(+ args.currentUserMembership = UserChatChannelMembership.create(args.current_user_membership || {following: false,muted: false,@@ -182,6 +170,8 @@ ChatChannel.reopenClass({unread_mentions: 0,});++ delete args.current_user_membership;},});diff --git a/plugins/chat/assets/javascripts/discourse/models/user-chat-channel-membership.js b/plugins/chat/assets/javascripts/discourse/models/user-chat-channel-membership.jsindex 8e97e26bfe2..9d732e82fc4 100644--- a/plugins/chat/assets/javascripts/discourse/models/user-chat-channel-membership.js+++ b/plugins/chat/assets/javascripts/discourse/models/user-chat-channel-membership.js@@ -1,3 +1,30 @@import RestModel from "discourse/models/rest";+import { tracked } from "@glimmer/tracking";+import User from "discourse/models/user";+export default class UserChatChannelMembership extends RestModel {+ @tracked following = false;+ @tracked muted = false;+ @tracked unread_count = 0;+ @tracked unread_mentions = 0;+ @tracked chat_message_id = null;+ @tracked chat_channel_id = null;+ @tracked desktop_notification_level = null;+ @tracked mobile_notification_level = null;+ @tracked last_read_message_id = null;+}-export default class UserChatChannelMembership extends RestModel {}+UserChatChannelMembership.reopenClass({+ create(args) {+ args = args || {};+ this._initUser(args);+ return this._super(args);+ },++ _initUser(args) {+ if (args.user instanceof User) {+ return;+ }++ args.user = User.create(args.user);+ },+});diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat-browse-archived.js b/plugins/chat/assets/javascripts/discourse/routes/chat-browse-archived.jsnew file mode 100644index 00000000000..7fc075e2cee--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/routes/chat-browse-archived.js@@ -0,0 +1,9 @@+import DiscourseRoute from "discourse/routes/discourse";++export default class ChatBrowseIndexRoute extends DiscourseRoute {+ afterModel() {+ if (!this.siteSettings.chat_allow_archiving_channels) {+ this.replaceWith("chat.browse");+ }+ }+}diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat-channel-by-name.js b/plugins/chat/assets/javascripts/discourse/routes/chat-channel-by-name.jsindex 7516fe58bb1..ba6c91c245e 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat-channel-by-name.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat-channel-by-name.js@@ -13,8 +13,8 @@ export default class ChatChannelByNameRoute extends DiscourseRoute {.then((response) => {this.transitionTo("chat.channel",- response.chat_channel.id,- response.chat_channel.title+ response.channel.id,+ response.channel.title);}).catch(() => this.replaceWith("/404"));diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-about.js b/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-about.jsindex 181c9ffb690..a92d5e882f0 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-about.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-about.js@@ -2,7 +2,7 @@ import DiscourseRoute from "discourse/routes/discourse";export default class ChatChannelInfoAboutRoute extends DiscourseRoute {afterModel(model) {- if (model.chatChannel.isDirectMessageChannel) {+ if (model.isDirectMessageChannel) {this.replaceWith("chat.channel.info.index");}}diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-index.js b/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-index.jsindex ffc3bc589b4..c7bfd1c0905 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-index.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-index.js@@ -2,8 +2,8 @@ import DiscourseRoute from "discourse/routes/discourse";export default class ChatChannelInfoIndexRoute extends DiscourseRoute {afterModel(model) {- if (model.chatChannel.isDirectMessageChannel) {- if (model.chatChannel.isOpen && model.chatChannel.membershipsCount >= 1) {+ if (model.isDirectMessageChannel) {+ if (model.isOpen && model.membershipsCount >= 1) {this.replaceWith("chat.channel.info.members");} else {this.replaceWith("chat.channel.info.settings");diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-members.js b/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-members.jsindex 25d2e4eb93a..d3fba6f97de 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-members.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-members.js@@ -2,8 +2,12 @@ import DiscourseRoute from "discourse/routes/discourse";export default class ChatChannelInfoMembersRoute extends DiscourseRoute {afterModel(model) {- if (!model.chatChannel.isOpen) {- this.replaceWith("chat.channel.info.settings");+ if (!model.isOpen) {+ return this.replaceWith("chat.channel.info.settings");+ }++ if (model.membershipsCount < 1) {+ return this.replaceWith("chat.channel.info");}}}diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-settings.js b/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-settings.jsnew file mode 100644index 00000000000..61635238534--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/routes/chat-channel-info-settings.js@@ -0,0 +1,9 @@+import DiscourseRoute from "discourse/routes/discourse";++export default class ChatChannelInfoSettingsRoute extends DiscourseRoute {+ afterModel(model) {+ if (!this.currentUser?.staff && !model.currentUserMembership?.following) {+ this.replaceWith("chat.channel.info");+ }+ }+}diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat-channel.js b/plugins/chat/assets/javascripts/discourse/routes/chat-channel.jsindex 17e6a2f7456..7e49d1f764e 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat-channel.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat-channel.js@@ -1,48 +1,23 @@import DiscourseRoute from "discourse/routes/discourse";-import Promise from "rsvp";-import EmberObject, { action } from "@ember/object";-import { ajax } from "discourse/lib/ajax";import { inject as service } from "@ember/service";-import ChatChannel from "discourse/plugins/chat/discourse/models/chat-channel";import slugifyChannel from "discourse/plugins/chat/discourse/lib/slugify-channel";export default class ChatChannelRoute extends DiscourseRoute {@service chat;@service router;+ @service chatChannelsManager;async model(params) {- let [chatChannel, channels] = await Promise.all([- this.getChannel(params.channelId),- this.chat.getChannels(),- ]);-- return EmberObject.create({- chatChannel,- channels,- });- }-- async getChannel(id) {- let channel = await this.chat.getChannelBy("id", id);- if (!channel || this.forceRefetchChannel) {- channel = await this.getChannelFromServer(id);- }- return channel;- }-- async getChannelFromServer(id) {- return ajax(`/chat/chat_channels/${id}`)- .then((response) => ChatChannel.create(response))- .catch(() => this.replaceWith("/404"));+ return this.chatChannelsManager.find(params.channelId);}afterModel(model) {- this.chat.setActiveChannel(model?.chatChannel);+ this.chat.setActiveChannel(model);const queryParams = this.paramsFor(this.routeName);- const slug = slugifyChannel(model.chatChannel);+ const slug = slugifyChannel(model);if (queryParams?.channelTitle !== slug) {- this.router.replaceWith("chat.channel.index", model.chatChannel.id, slug);+ this.router.replaceWith("chat.channel.index", model.id, slug);}}@@ -54,10 +29,4 @@ export default class ChatChannelRoute extends DiscourseRoute {this.controller.set("messageId", null);}}-- @action- refreshModel(forceRefetchChannel = false) {- this.forceRefetchChannel = forceRefetchChannel;- this.refresh();- }}diff --git a/plugins/chat/assets/javascripts/discourse/routes/chat-index.js b/plugins/chat/assets/javascripts/discourse/routes/chat-index.jsindex fbf8cd0a3cb..027f21b4672 100644--- a/plugins/chat/assets/javascripts/discourse/routes/chat-index.js+++ b/plugins/chat/assets/javascripts/discourse/routes/chat-index.js@@ -3,36 +3,29 @@ import { inject as service } from "@ember/service";export default class ChatIndexRoute extends DiscourseRoute {@service chat;+ @service chatChannelsManager;@service router;redirect() {+ // Always want the channel index on mobile.if (this.site.mobileView) {- return; // Always want the channel index on mobile.+ return;}- // We are on desktop. Check for a channel to enter and transition if so.- // Otherwise, `setupController` will fetch all available- return this.chat.getIdealFirstChannelIdAndTitle().then((channelInfo) => {- if (channelInfo) {- return this.chat.getChannelBy("id", channelInfo.id).then((c) => {- return this.chat.openChannel(c);- });- } else {- return this.router.transitionTo("chat.browse");- }- });+ // We are on desktop. Check for a channel to enter and transition if so+ const id = this.chat.getIdealFirstChannelId();+ if (id) {+ return this.chatChannelsManager.find(id).then((c) => {+ return this.chat.openChannel(c);+ });+ } else {+ return this.router.transitionTo("chat.browse");+ }}model() {if (this.site.mobileView) {- return this.chat.getChannels().then((channels) => {- if (- channels.publicChannels.length ||- channels.directMessageChannels.length- ) {- return channels;- }- });+ return this.chatChannelsManager.channels;}}}diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-api.js b/plugins/chat/assets/javascripts/discourse/services/chat-api.jsnew file mode 100644index 00000000000..4a24d8a9b6e--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/services/chat-api.js@@ -0,0 +1,242 @@+import Service, { inject as service } from "@ember/service";+import { ajax } from "discourse/lib/ajax";+import UserChatChannelMembership from "discourse/plugins/chat/discourse/models/user-chat-channel-membership";+import { tracked } from "@glimmer/tracking";+import { bind } from "discourse-common/utils/decorators";+import { Promise } from "rsvp";++class Collection {+ @tracked items = [];+ @tracked meta = {};+ @tracked loading = false;++ constructor(resourceURL, handler) {+ this._resourceURL = resourceURL;+ this._handler = handler;+ this._fetchedAll = false;+ }++ get loadMoreURL() {+ return this.meta.load_more_url;+ }++ get totalRows() {+ return this.meta.total_rows;+ }++ get length() {+ return this.items.length;+ }++ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols+ [Symbol.iterator]() {+ let index = 0;++ return {+ next: () => {+ if (index < this.items.length) {+ return { value: this.items[index++], done: false };+ } else {+ return { done: true };+ }+ },+ };+ }++ @bind+ load(params = {}) {+ this._fetchedAll = false;++ if (this.loading) {+ return;+ }++ this.loading = true;++ const filteredQueryParams = Object.entries(params).filter(+ ([, v]) => v !== undefined+ );+ const queryString = new URLSearchParams(filteredQueryParams).toString();++ const endpoint = this._resourceURL + (queryString ? `?${queryString}` : "");+ return this.#fetch(endpoint)+ .then((result) => {+ this.items = this._handler(result);+ this.meta = result.meta;+ })+ .finally(() => {+ this.loading = false;+ });+ }++ @bind+ loadMore() {+ if (this.loading) {+ return;+ }++ if (+ this._fetchedAll ||+ (this.totalRows && this.items.length >= this.totalRows)+ ) {+ return;+ }++ let promise;++ this.loading = true;++ if (this.loadMoreURL) {+ promise = this.#fetch(this.loadMoreURL).then((result) => {+ const newItems = this._handler(result);++ if (newItems.length) {+ this.items = this.items.concat(newItems);+ } else {+ this._fetchedAll = true;+ }+ this.meta = result.meta;+ });+ } else {+ promise = Promise.resolve();+ }++ return promise.finally(() => {+ this.loading = false;+ });+ }++ #fetch(url) {+ return ajax(url, { type: "GET" });+ }+}++export default class ChatApi extends Service {+ @service chatChannelsManager;++ getChannel(channelId) {+ return this.#getRequest(`/channels/${channelId}`).then((result) =>+ this.chatChannelsManager.store(result.channel)+ );+ }++ channels() {+ return new Collection(`${this.#basePath}/channels`, (response) => {+ return response.channels.map((channel) =>+ this.chatChannelsManager.store(channel)+ );+ });+ }++ moveChannelMessages(channelId, data = {}) {+ return this.#postRequest(`/channels/${channelId}/messages/moves`, {+ move: data,+ });+ }++ destroyChannel(channelId, data = {}) {+ return this.#deleteRequest(`/channels/${channelId}`, { channel: data });+ }++ createChannel(data = {}) {+ return this.#postRequest("/channels", { channel: data }).then((response) =>+ this.chatChannelsManager.store(response.channel)+ );+ }++ categoryPermissions(categoryId) {+ return ajax(`/chat/api/category-chatables/${categoryId}/permissions`);+ }++ sendMessage(channelId, data = {}) {+ return ajax(`/chat/${channelId}`, {+ ignoreUnsent: false,+ type: "POST",+ data,+ });+ }++ createChannelArchive(channelId, data = {}) {+ return this.#postRequest(`/channels/${channelId}/archives`, {+ archive: data,+ });+ }++ updateChannel(channelId, data = {}) {+ return this.#putRequest(`/channels/${channelId}`, { channel: data });+ }++ updateChannelStatus(channelId, status) {+ return this.#putRequest(`/channels/${channelId}/status`, { status });+ }++ listChannelMemberships(channelId) {+ return new Collection(+ `${this.#basePath}/channels/${channelId}/memberships`,+ (response) => {+ return response.memberships.map((membership) =>+ UserChatChannelMembership.create(membership)+ );+ }+ );+ }++ listCurrentUserChannels() {+ return this.#getRequest(`/channels/me`).then((result) => {+ return (result?.channels || []).map((channel) =>+ this.chatChannelsManager.store(channel)+ );+ });+ }++ followChannel(channelId) {+ return this.#postRequest(`/channels/${channelId}/memberships/me`).then(+ (result) => UserChatChannelMembership.create(result.membership)+ );+ }++ unfollowChannel(channelId) {+ return this.#deleteRequest(`/channels/${channelId}/memberships/me`).then(+ (result) => UserChatChannelMembership.create(result.membership)+ );+ }++ updateCurrentUserChatChannelNotificationsSettings(channelId, data = {}) {+ return this.#putRequest(+ `/channels/${channelId}/notifications-settings/me`,+ { notifications_settings: data }+ );+ }++ get #basePath() {+ return "/chat/api";+ }++ #getRequest(endpoint, data = {}) {+ return ajax(`${this.#basePath}/${endpoint}`, {+ type: "GET",+ data,+ });+ }++ #putRequest(endpoint, data = {}) {+ return ajax(`${this.#basePath}/${endpoint}`, {+ type: "PUT",+ data,+ });+ }++ #postRequest(endpoint, data = {}) {+ return ajax(`${this.#basePath}/${endpoint}`, {+ type: "POST",+ data,+ });+ }++ #deleteRequest(endpoint, data = {}) {+ return ajax(`${this.#basePath}/${endpoint}`, {+ type: "DELETE",+ data,+ });+ }+}diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-channels-manager.js b/plugins/chat/assets/javascripts/discourse/services/chat-channels-manager.jsnew file mode 100644index 00000000000..4ba6ab2365b--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/services/chat-channels-manager.js@@ -0,0 +1,136 @@+import Service, { inject as service } from "@ember/service";+import Promise from "rsvp";+import ChatChannel from "discourse/plugins/chat/discourse/models/chat-channel";+import { tracked } from "@glimmer/tracking";+import { TrackedObject } from "@ember-compat/tracked-built-ins";++const DIRECT_MESSAGE_CHANNELS_LIMIT = 20;++export default class ChatChannelsManager extends Service {+ @service chatSubscriptionsManager;+ @service chatApi;+ @service currentUser;+ @tracked _cached = new TrackedObject();++ get channels() {+ return Object.values(this._cached);+ }++ async find(id) {+ const existingChannel = this.#findStale(id);+ if (existingChannel) {+ return Promise.resolve(existingChannel);+ } else {+ return this.#find(id);+ }+ }++ store(channelObject) {+ let model = this.#findStale(channelObject.id);++ if (!model) {+ model = ChatChannel.create(channelObject);+ this.#cache(model);+ }++ return model;+ }++ async follow(model) {+ this.chatSubscriptionsManager.startChannelSubscription(model);++ if (!model.currentUserMembership.following) {+ return this.chatApi.followChannel(model.id).then((membership) => {+ model.currentUserMembership.following = membership.following;+ model.currentUserMembership.muted = membership.muted;+ model.currentUserMembership.desktop_notification_level =+ membership.desktop_notification_level;+ model.currentUserMembership.mobile_notification_level =+ membership.mobile_notification_level;++ return model;+ });+ } else {+ return Promise.resolve(model);+ }+ }++ async unfollow(model) {+ this.chatSubscriptionsManager.stopChannelSubscription(model);++ return this.chatApi.unfollowChannel(model.id).then((membership) => {+ model.currentUserMembership = membership;++ return model;+ });+ }++ get unreadCount() {+ let count = 0;+ this.publicMessageChannels.forEach((channel) => {+ count += channel.currentUserMembership.unread_count || 0;+ });+ return count;+ }++ get unreadUrgentCount() {+ let count = 0;+ this.channels.forEach((channel) => {+ if (channel.isDirectMessageChannel) {+ count += channel.currentUserMembership.unread_count || 0;+ }+ count += channel.currentUserMembership.unread_mentions || 0;+ });+ return count;+ }++ get publicMessageChannels() {+ return this.channels.filter(+ (channel) =>+ channel.isCategoryChannel && channel.currentUserMembership.following+ );+ }++ get directMessageChannels() {+ return this.#sortDirectMessageChannels(+ this.channels.filter((channel) => {+ const membership = channel.currentUserMembership;+ return channel.isDirectMessageChannel && membership.following;+ })+ );+ }++ get truncatedDirectMessageChannels() {+ return this.directMessageChannels.slice(0, DIRECT_MESSAGE_CHANNELS_LIMIT);+ }++ async #find(id) {+ return this.chatApi.getChannel(id).then((channel) => {+ this.#cache(channel);+ return channel;+ });+ }++ #cache(channel) {+ this._cached[channel.id] = channel;+ }++ #findStale(id) {+ return this._cached[id];+ }++ #sortDirectMessageChannels(channels) {+ return channels.sort((a, b) => {+ const unreadCountA = a.currentUserMembership.unread_count || 0;+ const unreadCountB = b.currentUserMembership.unread_count || 0;+ if (unreadCountA === unreadCountB) {+ return new Date(a.get("last_message_sent_at")) >+ new Date(b.get("last_message_sent_at"))+ ? -1+ : 1;+ } else {+ return unreadCountA > unreadCountB ? -1 : 1;+ }+ });+ }+}diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-message-visibility-observer.js b/plugins/chat/assets/javascripts/discourse/services/chat-message-visibility-observer.jsindex b76f8420e44..bc51a26394e 100644--- a/plugins/chat/assets/javascripts/discourse/services/chat-message-visibility-observer.js+++ b/plugins/chat/assets/javascripts/discourse/services/chat-message-visibility-observer.js@@ -19,7 +19,11 @@ export default class ChatMessageVisibilityObserver extends Service {entries.forEach((entry) => {entry.target.dataset.visible = entry.isIntersecting;- if (entry.isIntersecting && !isTesting()) {+ if (+ !entry.target.dataset.stagedId &&+ entry.isIntersecting &&+ !isTesting()+ ) {this.chat.updateLastReadMessage();}});diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-state-manager.js b/plugins/chat/assets/javascripts/discourse/services/chat-state-manager.jsindex 12df7f6382e..ee79bb20bb3 100644--- a/plugins/chat/assets/javascripts/discourse/services/chat-state-manager.js+++ b/plugins/chat/assets/javascripts/discourse/services/chat-state-manager.js@@ -86,6 +86,10 @@ export default class ChatStateManager extends Service {return this.router.currentRouteName?.startsWith("chat");}+ get isActive() {+ return this.isFullPageActive || this.isDrawerActive;+ }+storeAppURL(URL = null) {this._appURL = URL || this.router.currentURL;}diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-subscriptions-manager.js b/plugins/chat/assets/javascripts/discourse/services/chat-subscriptions-manager.jsnew file mode 100644index 00000000000..cf627de4d57--- /dev/null+++ b/plugins/chat/assets/javascripts/discourse/services/chat-subscriptions-manager.js@@ -0,0 +1,265 @@+import Service, { inject as service } from "@ember/service";+import { bind } from "discourse-common/utils/decorators";+import { CHANNEL_STATUSES } from "discourse/plugins/chat/discourse/models/chat-channel";++export default class ChatSubscriptionsManager extends Service {+ @service store;+ @service chatChannelsManager;+ @service currentUser;+ @service appEvents;++ _channelSubscriptions = new Set();++ startChannelSubscription(channel) {+ if (+ channel.currentUserMembership.muted ||+ this._channelSubscriptions.has(channel.id)+ ) {+ return;+ }++ this._channelSubscriptions.add(channel.id);++ if (!channel.isDirectMessageChannel) {+ this._startChannelMentionsSubscription(channel);+ }++ this._startChannelNewMessagesSubscription(channel);+ }++ stopChannelSubscription(channel) {+ this.messageBus.unsubscribe(+ `/chat/${channel.id}/new-messages`,+ this._onNewMessages+ );+ if (!channel.isDirectMessageChannel) {+ this.messageBus.unsubscribe(+ `/chat/${channel.id}/new-mentions`,+ this._onNewMentions+ );+ }++ this._channelSubscriptions.delete(channel.id);+ }++ startChannelsSubscriptions(messageBusIds) {+ this._startNewChannelSubscription(messageBusIds.new_channel);+ this._startUserTrackingStateSubscription(messageBusIds.user_tracking_state);+ this._startChannelsEditsSubscription(messageBusIds.channel_edits);+ this._startChannelsStatusChangesSubscription(messageBusIds.channel_status);+ this._startChannelsMetadataChangesSubscription(+ messageBusIds.channel_metadata+ );+ }++ stopChannelsSubscriptions() {+ this._stopNewChannelSubscription();+ this._stopUserTrackingStateSubscription();+ this._stopChannelsEditsSubscription();+ this._stopChannelsStatusChangesSubscription();+ this._stopChannelsMetadataChangesSubscription();++ (this.chatChannelsManager.channels || []).forEach((channel) => {+ this.stopChannelSubscription(channel);+ });+ }++ _startChannelMentionsSubscription(channel) {+ this.messageBus.subscribe(+ `/chat/${channel.id}/new-mentions`,+ this._onNewMentions,+ channel.meta.message_bus_last_ids.new_mentions+ );+ }++ @bind+ _onNewMentions(busData) {+ this.chatChannelsManager.find(busData.channel_id).then((channel) => {+ const membership = channel.currentUserMembership;+ if (membership) {+ membership.unread_mentions = (membership.unread_mentions || 0) + 1;+ }+ });+ }++ _startChannelNewMessagesSubscription(channel) {+ this.messageBus.subscribe(+ `/chat/${channel.id}/new-messages`,+ this._onNewMessages,+ channel.meta.message_bus_last_ids.new_messages+ );+ }++ @bind+ _onNewMessages(busData) {+ this.chatChannelsManager.find(busData.channel_id).then((channel) => {+ if (busData.user_id === this.currentUser.id) {+ // User sent message, update tracking state to no unread+ channel.currentUserMembership.chat_message_id = busData.message_id;+ } else {+ // Ignored user sent message, update tracking state to no unread+ if (this.currentUser.ignored_users.includes(busData.username)) {+ channel.currentUserMembership.chat_message_id = busData.message_id;+ } else {+ // Message from other user. Increment trackings state+ if (+ busData.message_id >+ (channel.currentUserMembership.chat_message_id || 0)+ ) {+ channel.currentUserMembership.unread_count =+ channel.currentUserMembership.unread_count + 1;+ }+ }+ }++ channel.set("last_message_sent_at", new Date());+ });+ }++ _startUserTrackingStateSubscription(lastId) {+ if (!this.currentUser) {+ return;+ }++ this.messageBus.subscribe(+ `/chat/user-tracking-state/${this.currentUser.id}`,+ this._onUserTrackingStateUpdate,+ lastId+ );+ }++ _stopUserTrackingStateSubscription() {+ if (!this.currentUser) {+ return;+ }++ this.messageBus.unsubscribe(+ `/chat/user-tracking-state/${this.currentUser.id}`,+ this._onUserTrackingStateUpdate+ );+ }++ @bind+ _onUserTrackingStateUpdate(data) {+ this.chatChannelsManager.find(data.chat_channel_id).then((channel) => {+ if (+ channel?.currentUserMembership?.chat_message_id < data.chat_message_id+ ) {+ channel.currentUserMembership.chat_message_id = data.chat_message_id;+ channel.currentUserMembership.unread_count = 0;+ channel.currentUserMembership.unread_mentions = 0;+ }+ });+ }++ _startNewChannelSubscription(lastId) {+ this.messageBus.subscribe(+ "/chat/new-channel",+ this._onNewChannelSubscription,+ lastId+ );+ }++ _stopNewChannelSubscription() {+ this.messageBus.unsubscribe(+ "/chat/new-channel",+ this._onNewChannelSubscription+ );+ }++ @bind+ _onNewChannelSubscription(data) {+ this.chatChannelsManager.find(data.channel.id).then((channel) => {+ // we need to refrehs here to have correct last message ids+ channel.meta = data.channel.meta;++ if (+ channel.isDirectMessageChannel &&+ !channel.currentUserMembership.following+ ) {+ channel.currentUserMembership.unread_count = 1;+ }++ this.chatChannelsManager.follow(channel);+ });+ }++ _startChannelsMetadataChangesSubscription(lastId) {+ this.messageBus.subscribe(+ "/chat/channel-metadata",+ this._onChannelMetadata,+ lastId+ );+ }++ _startChannelsEditsSubscription(lastId) {+ this.messageBus.subscribe(+ "/chat/channel-edits",+ this._onChannelEdits,+ lastId+ );+ }++ _startChannelsStatusChangesSubscription(lastId) {+ this.messageBus.subscribe(+ "/chat/channel-status",+ this._onChannelStatus,+ lastId+ );+ }++ _stopChannelsStatusChangesSubscription() {+ this.messageBus.unsubscribe("/chat/channel-status", this._onChannelStatus);+ }++ _stopChannelsEditsSubscription() {+ this.messageBus.unsubscribe("/chat/channel-edits", this._onChannelEdits);+ }++ _stopChannelsMetadataChangesSubscription() {+ this.messageBus.unsubscribe(+ "/chat/channel-metadata",+ this._onChannelMetadata+ );+ }++ @bind+ _onChannelMetadata(busData) {+ this.chatChannelsManager.find(busData.chat_channel_id).then((channel) => {+ if (channel) {+ channel.setProperties({+ memberships_count: busData.memberships_count,+ });+ this.appEvents.trigger("chat:refresh-channel-members");+ }+ });+ }++ @bind+ _onChannelEdits(busData) {+ this.chatChannelsManager.find(busData.chat_channel_id).then((channel) => {+ if (channel) {+ channel.setProperties({+ title: busData.name,+ description: busData.description,+ });+ }+ });+ }++ @bind+ _onChannelStatus(busData) {+ this.chatChannelsManager.find(busData.chat_channel_id).then((channel) => {+ channel.set("status", busData.status);++ // it is not possible for the user to set their last read message id+ // if the channel has been archived, because all the messages have+ // been deleted. we don't want them seeing the blue dot anymore so+ // just completely reset the unreads+ if (busData.status === CHANNEL_STATUSES.archived) {+ channel.currentUserMembership.unread_count = 0;+ channel.currentUserMembership.unread_mentions = 0;+ }+ });+ }+}diff --git a/plugins/chat/assets/javascripts/discourse/services/chat.js b/plugins/chat/assets/javascripts/discourse/services/chat.jsindex 26feb212750..03b9164a058 100644--- a/plugins/chat/assets/javascripts/discourse/services/chat.js+++ b/plugins/chat/assets/javascripts/discourse/services/chat.js@@ -5,22 +5,15 @@ import { popupAjaxError } from "discourse/lib/ajax-error";import Service, { inject as service } from "@ember/service";import Site from "discourse/models/site";import { ajax } from "discourse/lib/ajax";-import { A } from "@ember/array";import { generateCookFunction } from "discourse/lib/text";import { cancel, next } from "@ember/runloop";import { and } from "@ember/object/computed";+import { computed } from "@ember/object";import { Promise } from "rsvp";-import ChatChannel, {- CHANNEL_STATUSES,- CHATABLE_TYPES,-} from "discourse/plugins/chat/discourse/models/chat-channel";import simpleCategoryHashMentionTransform from "discourse/plugins/chat/discourse/lib/simple-category-hash-mention-transform";import discourseDebounce from "discourse-common/lib/debounce";-import EmberObject, { computed } from "@ember/object";-import ChatApi from "discourse/plugins/chat/discourse/lib/chat-api";import discourseLater from "discourse-common/lib/later";import userPresent from "discourse/lib/user-presence";-import { bind } from "discourse-common/utils/decorators";export const LIST_VIEW = "list_view";export const CHAT_VIEW = "chat_view";@@ -36,30 +29,21 @@ const READ_INTERVAL = 1000;export default class Chat extends Service {@service appEvents;@service chatNotificationManager;+ @service chatSubscriptionsManager;@service chatStateManager;@service presence;@service router;@service site;+ @service chatChannelsManager;activeChannel = null;- allChannels = null;cook = null;- directMessageChannels = null;- hasFetchedChannels = false;- hasUnreadMessages = false;- idToTitleMap = null;- lastUserTrackingMessageId = null;+messageId = null;presenceChannel = null;- publicChannels = null;sidebarActive = false;- unreadUrgentCount = null;- directMessagesLimit = 20;isNetworkUnreliable = false;@and("currentUser.has_chat_enabled", "siteSettings.chat_enabled") userCanChat;- _fetchingChannels = null;- _onNewMentionsCallbacks = new Map();- _onNewMessagesCallbacks = new Map();@computed("currentUser.staff", "currentUser.groups.[]")get userCanDirectMessage() {@@ -81,7 +65,6 @@ export default class Chat extends Service {super.init(...arguments);if (this.userCanChat) {- this.set("allChannels", []);this.presenceChannel = this.presence.getChannel("/chat/online");this.draftStore = {};@@ -114,38 +97,24 @@ export default class Chat extends Service {}setupWithPreloadedChannels(channels) {- this.currentUser.set("chat_channel_tracking_state", {});- this._processChannels(channels || {});- this.subscribeToChannelMessageBus();- this.userChatChannelTrackingStateChanged();- this.appEvents.trigger("chat:refresh-channels");- }-- setupWithoutPreloadedChannels() {- this.getChannels().then(() => {- this.subscribeToChannelMessageBus();- });- }+ this.chatSubscriptionsManager.startChannelsSubscriptions(+ channels.meta.message_bus_last_ids+ );+ this.presenceChannel.subscribe(channels.global_presence_channel_state);- subscribeToChannelMessageBus() {- this._subscribeToNewChannelUpdates();- this._subscribeToUserTrackingChannel();- this._subscribeToChannelEdits();- this._subscribeToChannelMetadata();- this._subscribeToChannelStatusChange();+ [...channels.public_channels, ...channels.direct_message_channels].forEach(+ (channelObject) => {+ const channel = this.chatChannelsManager.store(channelObject);+ return this.chatChannelsManager.follow(channel);+ }+ );}willDestroy() {super.willDestroy(...arguments);if (this.userCanChat) {- this.set("allChannels", null);- this._unsubscribeFromNewDmChannelUpdates();- this._unsubscribeFromUserTrackingChannel();- this._unsubscribeFromChannelEdits();- this._unsubscribeFromChannelMetadata();- this._unsubscribeFromChannelStatusChange();- this._unsubscribeFromAllChatChannels();+ this.chatSubscriptionsManager.stopChannelsSubscriptions();}}@@ -186,10 +155,7 @@ export default class Chat extends Service {return;}- if (- this.chatStateManager.isFullPageActive ||- this.chatStateManager.isDrawerActive- ) {+ if (this.chatStateManager.isActive) {this.presenceChannel.enter({ activeOptions: CHAT_ONLINE_OPTIONS });} else {this.presenceChannel.leave();@@ -199,61 +165,10 @@ export default class Chat extends Service {getDocumentTitleCount() {return this.chatNotificationManager.shouldCountChatInDocTitle()- ? this.unreadUrgentCount+ ? this.chatChannelsManager.unreadUrgentCount: 0;}- _channelObject() {- return {- publicChannels: this.publicChannels,- directMessageChannels: this.directMessageChannels,- };- }-- truncateDirectMessageChannels(channels) {- return channels.slice(0, this.directMessagesLimit);- }-- async getChannelsWithFilter(filter, opts = { excludeActiveChannel: true }) {- let sortedChannels = this.allChannels.sort((a, b) => {- return new Date(a.last_message_sent_at) > new Date(b.last_message_sent_at)- ? -1- : 1;- });-- const trimmedFilter = filter.trim();- const lowerCasedFilter = filter.toLowerCase();- const { activeChannel } = this;-- return sortedChannels.filter((channel) => {- if (- opts.excludeActiveChannel &&- activeChannel &&- activeChannel.id === channel.id- ) {- return false;- }- if (!trimmedFilter.length) {- return true;- }-- if (channel.isDirectMessageChannel) {- let userFound = false;- channel.chatable.users.forEach((user) => {- if (- user.username.toLowerCase().includes(lowerCasedFilter) ||- user.name?.toLowerCase().includes(lowerCasedFilter)- ) {- return (userFound = true);- }- });- return userFound;- } else {- return channel.title.toLowerCase().includes(lowerCasedFilter);- }- });- }-switchChannelUpOrDown(direction) {const { activeChannel } = this;if (!activeChannel) {@@ -262,15 +177,11 @@ export default class Chat extends Service {let currentList, otherList;if (activeChannel.isDirectMessageChannel) {- currentList = this.truncateDirectMessageChannels(- this.directMessageChannels- );- otherList = this.publicChannels;+ currentList = this.chatChannelsManager.truncatedDirectMessageChannels;+ otherList = this.chatChannelsManager.publicMessageChannels;} else {- currentList = this.publicChannels;- otherList = this.truncateDirectMessageChannels(- this.directMessageChannels- );+ currentList = this.chatChannelsManager.publicMessageChannels;+ otherList = this.chatChannelsManager.truncatedDirectMessageChannels;}const directionUp = direction === "up";@@ -296,109 +207,6 @@ export default class Chat extends Service {}}- getChannels() {- return new Promise((resolve) => {- if (this.hasFetchedChannels) {- return resolve(this._channelObject());- }-- if (!this._fetchingChannels) {- this._fetchingChannels = this._refreshChannels();- }-- this._fetchingChannels- .then(() => resolve(this._channelObject()))- .finally(() => (this._fetchingChannels = null));- });- }-- forceRefreshChannels() {- this.set("hasFetchedChannels", false);- this._unsubscribeFromAllChatChannels();- return this.getChannels();- }-- refreshTrackingState() {- if (!this.currentUser) {- return;- }-- return ajax("/chat/chat_channels.json")- .then((response) => {- this.currentUser.set("chat_channel_tracking_state", {});- (response.direct_message_channels || []).forEach((channel) => {- this._updateUserTrackingState(channel);- });- (response.public_channels || []).forEach((channel) => {- this._updateUserTrackingState(channel);- });- })- .finally(() => {- this.userChatChannelTrackingStateChanged();- });- }-- _refreshChannels() {- return new Promise((resolve) => {- this.setProperties({- loading: true,- allChannels: [],- });- this.currentUser.set("chat_channel_tracking_state", {});- ajax("/chat/chat_channels.json").then((channels) => {- this._processChannels(channels);- this.userChatChannelTrackingStateChanged();- this.appEvents.trigger("chat:refresh-channels");- resolve(this._channelObject());- });- });- }-- _processChannels(channels) {- // Must be set first because `processChannels` relies on this data.- this.set("messageBusLastIds", channels.message_bus_last_ids);- this.setProperties({- publicChannels: A(- this.sortPublicChannels(- (channels.public_channels || []).map((channel) =>- this.processChannel(channel)- )- )- ),- directMessageChannels: A(- this.sortDirectMessageChannels(- (channels.direct_message_channels || []).map((channel) =>- this.processChannel(channel)- )- )- ),- hasFetchedChannels: true,- loading: false,- });- const idToTitleMap = {};- this.allChannels.forEach((c) => {- idToTitleMap[c.id] = c.title;- });- this.set("idToTitleMap", idToTitleMap);- this.presenceChannel.subscribe(channels.global_presence_channel_state);- }-- reSortDirectMessageChannels() {- this.set(- "directMessageChannels",- this.sortDirectMessageChannels(this.directMessageChannels)- );- }-- async getChannelBy(key, value) {- return this.getChannels().then(() => {- if (!isNaN(value)) {- value = parseInt(value, 10);- }- return (this.allChannels || []).findBy(key, value);- });- }-searchPossibleDirectMessageUsers(options) {// TODO: implement a chat specific user search functionreturn userSearch(options);@@ -414,99 +222,54 @@ export default class Chat extends Service {// if that is present and in the list of channels the user can access.// If none of these options exist, then we get the first public channel,// or failing that the first DM channel.- return this.getChannels().then(() => {- // Defined in order of significance.- let publicChannelWithMention,- dmChannelWithUnread,- publicChannelWithUnread,- publicChannel,- dmChannel,- defaultChannel;-- for (const [channel, state] of Object.entries(- this.currentUser.chat_channel_tracking_state- )) {- if (state.chatable_type === CHATABLE_TYPES.directMessageChannel) {- if (!dmChannelWithUnread && state.unread_count > 0) {- dmChannelWithUnread = channel;- } else if (!dmChannel) {- dmChannel = channel;- }- } else {- if (state.unread_mentions > 0) {- publicChannelWithMention = channel;- break; // <- We have a public channel with a mention. Break and return this.- } else if (!publicChannelWithUnread && state.unread_count > 0) {- publicChannelWithUnread = channel;- } else if (- !defaultChannel &&- parseInt(this.siteSettings.chat_default_channel_id || 0, 10) ===- parseInt(channel, 10)- ) {- defaultChannel = channel;- } else if (!publicChannel) {- publicChannel = channel;- }- }- }- return (- publicChannelWithMention ||- dmChannelWithUnread ||- publicChannelWithUnread ||- defaultChannel ||- publicChannel ||- dmChannel- );- });- }+ // Defined in order of significance.+ let publicChannelWithMention,+ dmChannelWithUnread,+ publicChannelWithUnread,+ publicChannel,+ dmChannel,+ defaultChannel;- sortPublicChannels(channels) {- return channels.sort((a, b) => a.title.localeCompare(b.title));- }+ this.chatChannelsManager.channels.forEach((channel) => {+ const membership = channel.currentUserMembership;- sortDirectMessageChannels(channels) {- return channels.sort((a, b) => {- const unreadCountA =- this.currentUser.chat_channel_tracking_state[a.id]?.unread_count || 0;- const unreadCountB =- this.currentUser.chat_channel_tracking_state[b.id]?.unread_count || 0;- if (unreadCountA === unreadCountB) {- return new Date(a.last_message_sent_at) >- new Date(b.last_message_sent_at)- ? -1- : 1;+ if (channel.isDirectMessageChannel) {+ if (!dmChannelWithUnread && membership.unread_count > 0) {+ dmChannelWithUnread = channel.id;+ } else if (!dmChannel) {+ dmChannel = channel.id;+ }} else {- return unreadCountA > unreadCountB ? -1 : 1;+ if (membership.unread_mentions > 0) {+ publicChannelWithMention = channel.id;+ return; // <- We have a public channel with a mention. Break and return this.+ } else if (!publicChannelWithUnread && membership.unread_count > 0) {+ publicChannelWithUnread = channel.id;+ } else if (+ !defaultChannel &&+ parseInt(this.siteSettings.chat_default_channel_id || 0, 10) ===+ channel.id+ ) {+ defaultChannel = channel.id;+ } else if (!publicChannel) {+ publicChannel = channel.id;+ }}});- }- getIdealFirstChannelIdAndTitle() {- return this.getIdealFirstChannelId().then((channelId) => {- if (!channelId) {- return;- }- return {- id: channelId,- title: this.idToTitleMap[channelId],- };- });+ return (+ publicChannelWithMention ||+ dmChannelWithUnread ||+ publicChannelWithUnread ||+ defaultChannel ||+ publicChannel ||+ dmChannel+ );}async openChannelAtMessage(channelId, messageId = null) {- let channel = await this.getChannelBy("id", channelId);- if (channel) {+ return this.chatChannelsManager.find(channelId).then((channel) => {return this._openFoundChannelAtMessage(channel, messageId);- }-- return ajax(`/chat/chat_channels/${channelId}`).then((response) => {- const queryParams = messageId ? { messageId } : {};- return this.router.transitionTo(- "chat.channel",- response.id,- slugifyChannel(response),- { queryParams }- );});}@@ -559,380 +322,18 @@ export default class Chat extends Service {this.appEvents.trigger("chat-live-pane:highlight-message", messageId);}- async startTrackingChannel(channel) {- if (!channel.current_user_membership.following) {- return;- }-- let existingChannel = await this.getChannelBy("id", channel.id);- if (existingChannel) {- return existingChannel; // User is already tracking this channel. return!- }-- const existingChannels = channel.isDirectMessageChannel- ? this.directMessageChannels- : this.publicChannels;-- // this check shouldn't be needed given the previous check to existingChannel- // this is a safety net, to ensure we never track duplicated channels- existingChannel = existingChannels.findBy("id", channel.id);- if (existingChannel) {- return existingChannel;- }-- const newChannel = this.processChannel(channel);- existingChannels.pushObject(newChannel);- this.currentUser.chat_channel_tracking_state[channel.id] =- EmberObject.create({- unread_count: 1,- unread_mentions: 0,- chatable_type: channel.chatable_type,- });- this.userChatChannelTrackingStateChanged();- if (channel.isDirectMessageChannel) {- this.reSortDirectMessageChannels();- }- if (channel.isPublicChannel) {- this.set("publicChannels", this.sortPublicChannels(this.publicChannels));- }- this.appEvents.trigger("chat:refresh-channels");- return newChannel;- }-- async stopTrackingChannel(channel) {- return this.getChannelBy("id", channel.id).then((existingChannel) => {- if (existingChannel) {- return this.forceRefreshChannels();- }- });- }-- _subscribeToChannelMetadata() {- this.messageBus.subscribe(- "/chat/channel-metadata",- this._onChannelMetadata,- this.messageBusLastIds.channel_metadata- );- }-- _subscribeToChannelEdits() {- this.messageBus.subscribe(- "/chat/channel-edits",- this._onChannelEdits,- this.messageBusLastIds.channel_edits- );- }-- _subscribeToChannelStatusChange() {- this.messageBus.subscribe("/chat/channel-status", this._onChannelStatus);- }-- _unsubscribeFromChannelStatusChange() {- this.messageBus.unsubscribe("/chat/channel-status", this._onChannelStatus);- }-- _unsubscribeFromChannelEdits() {- this.messageBus.unsubscribe("/chat/channel-edits", this._onChannelEdits);- }-- _unsubscribeFromChannelMetadata() {- this.messageBus.unsubscribe(- "/chat/channel-metadata",- this._onChannelMetadata- );- }-- _subscribeToNewChannelUpdates() {- this.messageBus.subscribe(- "/chat/new-channel",- this._onNewChannel,- this.messageBusLastIds.new_channel- );- }-- _unsubscribeFromNewDmChannelUpdates() {- this.messageBus.unsubscribe("/chat/new-channel", this._onNewChannel);- }-- _subscribeToSingleUpdateChannel(channel) {- if (channel.current_user_membership.muted) {- return;- }-- // We do this first so we don't multi-subscribe to mention + messages- // messageBus channels for this chat channel, since _subscribeToSingleUpdateChannel- // is called from multiple places.- this._unsubscribeFromChatChannel(channel);-- if (!channel.isDirectMessageChannel) {- this._subscribeToMentionChannel(channel);- }-- this._subscribeToNewMessagesChannel(channel);- }-- _subscribeToMentionChannel(channel) {- const onNewMentions = () => {- const trackingState =- this.currentUser.chat_channel_tracking_state[channel.id];-- if (trackingState) {- const count = (trackingState.unread_mentions || 0) + 1;- trackingState.set("unread_mentions", count);- this.userChatChannelTrackingStateChanged();- }- };-- this._onNewMentionsCallbacks.set(channel.id, onNewMentions);-- this.messageBus.subscribe(- `/chat/${channel.id}/new-mentions`,- onNewMentions,- channel.message_bus_last_ids.new_mentions- );- }-- _subscribeToNewMessagesChannel(channel) {- const onNewMessages = (busData) => {- const trackingState =- this.currentUser.chat_channel_tracking_state[channel.id];-- if (busData.user_id === this.currentUser.id) {- // User sent message, update tracking state to no unread- trackingState.set("chat_message_id", busData.message_id);- } else {- // Ignored user sent message, update tracking state to no unread- if (this.currentUser.ignored_users.includes(busData.username)) {- trackingState.set("chat_message_id", busData.message_id);- } else {- // Message from other user. Increment trackings state- if (busData.message_id > (trackingState.chat_message_id || 0)) {- trackingState.set("unread_count", trackingState.unread_count + 1);- }- }- }-- this.userChatChannelTrackingStateChanged();- channel.set("last_message_sent_at", new Date());-- const directMessageChannel = (this.directMessageChannels || []).findBy(- "id",- parseInt(channel.id, 10)- );-- if (directMessageChannel) {- this.reSortDirectMessageChannels();- }- };-- this._onNewMessagesCallbacks.set(channel.id, onNewMessages);-- this.messageBus.subscribe(- `/chat/${channel.id}/new-messages`,- onNewMessages,- channel.message_bus_last_ids.new_messages- );- }-- @bind- _onChannelMetadata(busData) {- this.getChannelBy("id", busData.chat_channel_id).then((channel) => {- if (channel) {- channel.setProperties({- memberships_count: busData.memberships_count,- });- this.appEvents.trigger("chat:refresh-channel-members");- }- });- }-- @bind- _onChannelEdits(busData) {- this.getChannelBy("id", busData.chat_channel_id).then((channel) => {- if (channel) {- channel.setProperties({- title: busData.name,- description: busData.description,- });- }- });- }-- @bind- _onChannelStatus(busData) {- this.getChannelBy("id", busData.chat_channel_id).then((channel) => {- if (!channel) {- return;- }-- channel.set("status", busData.status);-- // it is not possible for the user to set their last read message id- // if the channel has been archived, because all the messages have- // been deleted. we don't want them seeing the blue dot anymore so- // just completely reset the unreads- if (busData.status === CHANNEL_STATUSES.archived) {- this.currentUser.chat_channel_tracking_state[channel.id] = {- unread_count: 0,- unread_mentions: 0,- chatable_type: channel.chatable_type,- };- this.userChatChannelTrackingStateChanged();- }-- this.appEvents.trigger("chat:refresh-channel", channel.id);- }, this.messageBusLastIds.channel_status);- }-- @bind- _onNewChannel(busData) {- this.startTrackingChannel(ChatChannel.create(busData.chat_channel));- }-async followChannel(channel) {- return ChatApi.followChatChannel(channel).then(() => {- this.startTrackingChannel(channel);- this._subscribeToSingleUpdateChannel(channel);- });+ return this.chatChannelsManager.follow(channel);}async unfollowChannel(channel) {- return ChatApi.unfollowChatChannel(channel).then(() => {- this._unsubscribeFromChatChannel(channel);- this.stopTrackingChannel(channel);-+ return this.chatChannelsManager.unfollow(channel).then(() => {if (channel === this.activeChannel && channel.isDirectMessageChannel) {this.router.transitionTo("chat");}});}- _unsubscribeFromAllChatChannels() {- (this.allChannels || []).forEach((channel) => {- this._unsubscribeFromChatChannel(channel);- });- }-- _unsubscribeFromChatChannel(channel) {- this.messageBus.unsubscribe("/chat/*", this._onNewMessagesCallbacks);- if (!channel.isDirectMessageChannel) {- this.messageBus.unsubscribe("/chat/*", this._onNewMentionsCallbacks);- }- }-- _subscribeToUserTrackingChannel() {- this.messageBus.subscribe(- `/chat/user-tracking-state/${this.currentUser.id}`,- this._onUserTrackingState,- this.messageBusLastIds.user_tracking_state- );- }-- _unsubscribeFromUserTrackingChannel() {- this.messageBus.unsubscribe(- `/chat/user-tracking-state/${this.currentUser.id}`,- this._onUserTrackingState- );- }-- @bind- _onUserTrackingState(busData, _, messageId) {- const lastId = this.lastUserTrackingMessageId;-- // we don't want this state to go backwards, only catch- // up if messages from messagebus were missed- if (!lastId || messageId > lastId) {- this.lastUserTrackingMessageId = messageId;- }-- // we are too far out of sync, we should resync everything.- // this will trigger a route transition and blur the chat input- if (lastId && messageId > lastId + 1) {- return this.forceRefreshChannels();- }-- const trackingState =- this.currentUser.chat_channel_tracking_state[busData.chat_channel_id];-- if (trackingState) {- trackingState.set("chat_message_id", busData.chat_message_id);- trackingState.set("unread_count", 0);- trackingState.set("unread_mentions", 0);- this.userChatChannelTrackingStateChanged();- }- }-- resetTrackingStateForChannel(channelId) {- const trackingState =- this.currentUser.chat_channel_tracking_state[channelId];- if (trackingState) {- trackingState.set("unread_count", 0);- this.userChatChannelTrackingStateChanged();- }- }-- userChatChannelTrackingStateChanged() {- this._recalculateUnreadMessages();- this.appEvents.trigger("chat:user-tracking-state-changed");- }-- _recalculateUnreadMessages() {- let unreadPublicCount = 0;- let unreadUrgentCount = 0;- let headerNeedsRerender = false;-- Object.values(this.currentUser.chat_channel_tracking_state).forEach(- (state) => {- if (state.muted) {- return;- }-- if (state.chatable_type === CHATABLE_TYPES.directMessageChannel) {- unreadUrgentCount += state.unread_count || 0;- } else {- unreadUrgentCount += state.unread_mentions || 0;- unreadPublicCount += state.unread_count || 0;- }- }- );-- let hasUnreadPublic = unreadPublicCount > 0;- if (hasUnreadPublic !== this.hasUnreadMessages) {- headerNeedsRerender = true;- this.set("hasUnreadMessages", hasUnreadPublic);- }-- if (unreadUrgentCount !== this.unreadUrgentCount) {- headerNeedsRerender = true;- this.set("unreadUrgentCount", unreadUrgentCount);- }-- this.currentUser.notifyPropertyChange("chat_channel_tracking_state");- if (headerNeedsRerender) {- this.appEvents.trigger("chat:rerender-header");- this.appEvents.trigger("notifications:changed");- }- }-- processChannel(channel) {- channel = ChatChannel.create(channel);- this._subscribeToSingleUpdateChannel(channel);- this._updateUserTrackingState(channel);- this.allChannels.push(channel);- return channel;- }-- _updateUserTrackingState(channel) {- this.currentUser.chat_channel_tracking_state[channel.id] =- EmberObject.create({- chatable_type: channel.chatable_type,- muted: channel.current_user_membership.muted,- unread_count: channel.current_user_membership.unread_count,- unread_mentions: channel.current_user_membership.unread_mentions,- chat_message_id: channel.current_user_membership.last_read_message_id,- });- }-upsertDmChannelForUser(channel, user) {const usernames = (channel.chatable.users || []).mapBy("username")@@ -951,9 +352,9 @@ export default class Chat extends Service {data: { usernames: usernames.uniq() },}).then((response) => {- const chatChannel = ChatChannel.create(response.chat_channel);- this.startTrackingChannel(chatChannel);- return chatChannel;+ const channel = this.chatChannelsManager.store(response.channel);+ this.chatChannelsManager.follow(channel);+ return channel;}).catch(popupAjaxError);}@@ -1031,17 +432,8 @@ export default class Chat extends Service {10);- const hasUnreadMessages = latestUnreadMsgId > channel.lastSendReadMessageId;-- if (- !hasUnreadMessages &&- this.currentUser.chat_channel_tracking_state[this.activeChannel.id]- ?.unread_count > 0- ) {- // Weird state here where the chat_channel_tracking_state is wrong. Need to reset it.- this.resetTrackingStateForChannel(this.activeChannel.id);- }-+ const hasUnreadMessages =+ latestUnreadMsgId > channel.currentUserMembership.last_read_message_id;if (hasUnreadMessages) {channel.updateLastReadMessage(latestUnreadMsgId);}diff --git a/plugins/chat/assets/javascripts/discourse/templates/chat-channel-index.hbs b/plugins/chat/assets/javascripts/discourse/templates/chat-channel-index.hbsindex dc261f00413..89a38629ad6 100644--- a/plugins/chat/assets/javascripts/discourse/templates/chat-channel-index.hbs+++ b/plugins/chat/assets/javascripts/discourse/templates/chat-channel-index.hbs@@ -1 +1 @@-<FullPageChat @refreshModel={{route-action "refreshModel"}} />+<FullPageChat />diff --git a/plugins/chat/assets/javascripts/discourse/templates/chat-channel-info-about.hbs b/plugins/chat/assets/javascripts/discourse/templates/chat-channel-info-about.hbsindex 5211ae3ff72..a9cb4f67d41 100644--- a/plugins/chat/assets/javascripts/discourse/templates/chat-channel-info-about.hbs+++ b/plugins/chat/assets/javascripts/discourse/templates/chat-channel-info-about.hbs@@ -1 +1,5 @@-<ChatChannelAboutView @channel={{this.model.chatChannel}} @onEditChatChannelTitle={{action "onEditChatChannelTitle"}} @onEditChatChannelDescription={{action "onEditChatChannelDescription"}} />+<ChatChannelAboutView+ @channel={{this.model}}+ @onEditChatChannelTitle={{action "onEditChatChannelTitle"}}+ @onEditChatChannelDescription={{action "onEditChatChannelDescription"}}+/>diff --git a/plugins/chat/assets/javascripts/discourse/templates/chat-channel-info-members.hbs b/plugins/chat/assets/javascripts/discourse/templates/chat-channel-info-members.hbsindex b6e654e73d6..e80afabd3ba 100644--- a/plugins/chat/assets/javascripts/discourse/templates/chat-channel-info-members.hbs+++ b/plugins/chat/assets/javascripts/discourse/templates/chat-channel-info-members.hbs@@ -1 +1 @@-<ChatChannelMembersView @channel={{this.model.chatChannel}} />+<ChatChannelMembersView @channel={{this.model}} />diff --git a/plugins/chat/assets/javascripts/discourse/templates/chat-channel-info-settings.hbs b/plugins/chat/assets/javascripts/discourse/templates/chat-channel-info-settings.hbsindex d267701835a..a30950bc79e 100644--- a/plugins/chat/assets/javascripts/discourse/templates/chat-channel-info-settings.hbs+++ b/plugins/chat/assets/javascripts/discourse/templates/chat-channel-info-settings.hbs@@ -1 +1 @@-<ChatChannelSettingsView @channel={{this.model.chatChannel}} />+<ChatChannelSettingsView @channel={{this.model}} />diff --git a/plugins/chat/assets/javascripts/discourse/templates/chat-channel-info.hbs b/plugins/chat/assets/javascripts/discourse/templates/chat-channel-info.hbsindex e7e0ba3aacb..fdb757c23c3 100644--- a/plugins/chat/assets/javascripts/discourse/templates/chat-channel-info.hbs+++ b/plugins/chat/assets/javascripts/discourse/templates/chat-channel-info.hbs@@ -3,16 +3,17 @@<div class="chat-channel-header-details"><div class="chat-full-page-header__left-actions">{{#if this.chatChannelInfoRouteOriginManager.isBrowse}}- <LinkTo @route="chat.browse" class="chat-full-page-header__back-btn no-text btn-flat btn" title={{i18n "chat.channel_info.back_to_all_channel"}}>+ <LinkTo+ @route="chat.browse"+ class="chat-full-page-header__back-btn no-text btn-flat btn"+ title={{i18n "chat.channel_info.back_to_all_channel"}}+ >{{d-icon "chevron-left"}}</LinkTo>{{else}}<LinkTo@route="chat.channel"- @models={{array- this.model.chatChannel.id- (slugify-channel this.model.chatChannel)- }}+ @models={{array this.model.id (slugify-channel this.model)}}class="chat-full-page-header__back-btn no-text btn-flat btn"title={{i18n "chat.channel_info.back_to_channel"}}>@@ -21,7 +22,7 @@{{/if}}</div>- <ChatChannelTitle @channel={{this.model.chatChannel}} />+ <ChatChannelTitle @channel={{this.model}} /></div></div>@@ -35,16 +36,13 @@><LinkTo@route={{concat "chat.channel.info." tab}}- @models={{array- this.model.chatChannel.id- (slugify-channel this.model.chatChannel)- }}+ @models={{array this.model.id (slugify-channel this.model)}}class="chat-tabs-list__link"><span>{{i18n (concat "chat.channel_info.tabs." tab)}}</span>{{#if (eq tab "members")}}<span class="chat-tabs__memberships-count">- ({{this.model.chatChannel.membershipsCount}})+ ({{this.model.membershipsCount}})</span>{{/if}}</LinkTo>diff --git a/plugins/chat/assets/javascripts/discourse/templates/modal/create-channel.hbs b/plugins/chat/assets/javascripts/discourse/templates/modal/create-channel.hbsindex e39cc9a9d59..14199193dec 100644--- a/plugins/chat/assets/javascripts/discourse/templates/modal/create-channel.hbs+++ b/plugins/chat/assets/javascripts/discourse/templates/modal/create-channel.hbs@@ -17,15 +17,15 @@</label>{{/if}}- <label class="create-channel-label">+ <label for="channel-name" class="create-channel-label">{{i18n "chat.create_channel.name"}}</label>- <Input class="create-channel-name-input" @type="text" @value={{this.name}} />+ <Input name="channel-name" class="create-channel-name-input" @type="text" @value={{this.name}} />- <label class="create-channel-label">+ <label for="channel-description" class="create-channel-label">{{i18n "chat.create_channel.description"}}</label>- <Input class="create-channel-description-input" @type="textarea" @value={{this.description}} />+ <Input name="channel-description" class="create-channel-description-input" @type="textarea" @value={{this.description}} /></DModalBody><div class="modal-footer">diff --git a/plugins/chat/assets/javascripts/discourse/widgets/chat-header-icon.js b/plugins/chat/assets/javascripts/discourse/widgets/chat-header-icon.jsindex 50985147a84..84220e86afd 100644--- a/plugins/chat/assets/javascripts/discourse/widgets/chat-header-icon.js+++ b/plugins/chat/assets/javascripts/discourse/widgets/chat-header-icon.js@@ -1,87 +1,24 @@-import getURL from "discourse-common/lib/get-url";import { createWidget } from "discourse/widgets/widget";-import { h } from "virtual-dom";-import { iconNode } from "discourse-common/lib/icon-library";+import RenderGlimmer from "discourse/widgets/render-glimmer";+import { hbs } from "ember-cli-htmlbars";-export default createWidget("header-chat-link", {- buildKey: () => "header-chat-link",- chat: null,- tagName: "li.header-dropdown-toggle.open-chat",- title: "chat.title",- services: ["chat", "router", "chatStateManager"],+export default createWidget("chat-header-icon", {+ tagName: "li.header-dropdown-toggle.chat-header-icon",+ title: "chat.title_capitalized",++ services: ["chat"],html() {if (!this.chat.userCanChat) {return;}- if (this.currentUser.isInDoNotDisturb()) {- return this.chatLinkHtml();- }-- let indicator;- if (this.chat.unreadUrgentCount) {- indicator = h(- "div.chat-channel-unread-indicator.urgent",- {},- h(- "div.number-wrap",- {},- h("div.number", {}, this.chat.unreadUrgentCount)- )- );- } else if (this.chat.hasUnreadMessages) {- indicator = h("div.chat-channel-unread-indicator");- }-- return this.chatLinkHtml(indicator);- },-- chatLinkHtml(indicatorNode) {- return h(- `a.icon${- this.chatStateManager.isFullPageActive ||- this.chatStateManager.isDrawerActive- ? ".active"- : ""- }`,- { attributes: { tabindex: 0 } },- [iconNode("comment"), indicatorNode].filter(Boolean)- );- },-- mouseUp(e) {- if (e.which === 2) {- // Middle mouse click- window.open(getURL("/chat"), "_blank").focus();- }- },-- keyUp(e) {- if (e.code === "Enter") {- return this.click();- }- },-- click() {- if (this.chatStateManager.isFullPageActive && this.site.desktopView) {- return;- }-- if (this.chatStateManager.isFullPageActive && this.site.mobileView) {- return this.router.transitionTo("chat");- }-- if (this.chatStateManager.isDrawerActive) {- return this.router.transitionTo("chat");- } else {- return this.router.transitionTo(- this.chatStateManager.lastKnownChatURL || "chat"- );- }- },-- chatRerenderHeader() {- this.scheduleRerender();+ return [+ new RenderGlimmer(+ this,+ "div.widget-component-connector",+ hbs`<ChatHeaderIcon />`+ ),+ ];},});diff --git a/plugins/chat/assets/stylesheets/common/common.scss b/plugins/chat/assets/stylesheets/common/common.scssindex 5fc95c56df1..894e3676470 100644--- a/plugins/chat/assets/stylesheets/common/common.scss+++ b/plugins/chat/assets/stylesheets/common/common.scss@@ -103,8 +103,30 @@ $float-height: 530px;}}-.header-dropdown-toggle.open-chat {+.header-dropdown-toggle.chat-header-icon {.icon {+ .chat-channel-unread-indicator {+ border: 2px solid var(--header_background);+ position: absolute;+ right: 2px;+ bottom: 2px;+ transition: border-color linear 0.15s;+ }+ }++ span.icon {+ cursor: auto;++ &:hover {+ .d-icon {+ color: var(--header_primary-low-mid);+ }++ background: none;+ }+ }++ a.icon {&.active {.d-icon-comment {color: var(--primary-medium);@@ -116,14 +138,6 @@ $float-height: 530px;border-color: var(--primary-low);}}-- .chat-channel-unread-indicator {- border: 2px solid var(--header_background);- position: absolute;- right: 2px;- bottom: 2px;- transition: border-color linear 0.15s;- }}}diff --git a/plugins/chat/assets/stylesheets/mobile/mobile.scss b/plugins/chat/assets/stylesheets/mobile/mobile.scssindex d60171796dd..98224a6849f 100644--- a/plugins/chat/assets/stylesheets/mobile/mobile.scss+++ b/plugins/chat/assets/stylesheets/mobile/mobile.scss@@ -114,7 +114,7 @@ html.has-full-page-chat body {margin-left: 0;}-.header-dropdown-toggle.open-chat {+.header-dropdown-toggle.chat-header-icon {.icon {&.active {border: 1px solid var(--primary-low);diff --git a/plugins/chat/assets/stylesheets/sidebar-extensions.scss b/plugins/chat/assets/stylesheets/sidebar-extensions.scssindex ea504c0f18e..bc817db6dd0 100644--- a/plugins/chat/assets/stylesheets/sidebar-extensions.scss+++ b/plugins/chat/assets/stylesheets/sidebar-extensions.scss@@ -15,7 +15,7 @@}}}- .header-dropdown-toggle.open-chat {+ .header-dropdown-toggle.chat-header-icon {.chat-channel-unread-indicator {border-color: var(--primary-very-low);}diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.ymlindex d18182eea7e..b5562dbb645 100644--- a/plugins/chat/config/locales/client.en.yml+++ b/plugins/chat/config/locales/client.en.yml@@ -116,10 +116,10 @@ en:without_membership:one: "%{username} has not joined this channel."other: "%{username} and %{others} have not joined this channel."- group_mentions_disabled:+ group_mentions_disabled:one: "%{group_name} doesn't allow mentions"other: "%{group_name} and %{others} doesn't allow mentions"- too_many_members:+ too_many_members:one: "%{group_name} has too many members. No one was notified"other: "%{group_name} and %{others} have too many members. No one was notified"warning_multiple:diff --git a/plugins/chat/lib/chat_channel_archive_service.rb b/plugins/chat/lib/chat_channel_archive_service.rbindex 8d1e0e65e02..45196c1f937 100644--- a/plugins/chat/lib/chat_channel_archive_service.rb+++ b/plugins/chat/lib/chat_channel_archive_service.rb@@ -45,6 +45,7 @@ class Chat::ChatChannelArchiveService:chat_channel_archive,chat_channel_archive_id: chat_channel.chat_channel_archive.id,)+ chat_channel.chat_channel_archiveendattr_reader :chat_channel_archive, :chat_channel, :chat_channel_titlediff --git a/plugins/chat/lib/chat_message_reactor.rb b/plugins/chat/lib/chat_message_reactor.rbindex 444c60e0ae1..9e7260f7979 100644--- a/plugins/chat/lib/chat_message_reactor.rb+++ b/plugins/chat/lib/chat_message_reactor.rb@@ -19,14 +19,15 @@ class Chat::ChatMessageReactormessage = ensure_chat_message!(message_id)validate_max_reactions!(message, react_action, emoji)+ reaction = nilActiveRecord::Base.transaction doenforce_channel_membership!- create_reaction(message, react_action, emoji)+ reaction = create_reaction(message, react_action, emoji)endpublish_reaction(message, react_action, emoji)- message+ reactionendprivatediff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rbindex 88204cf734a..2e9b6b4fa6d 100644--- a/plugins/chat/plugin.rb+++ b/plugins/chat/plugin.rb@@ -120,7 +120,6 @@ after_initialize do)load File.expand_path("../app/controllers/chat_base_controller.rb", __FILE__)load File.expand_path("../app/controllers/chat_controller.rb", __FILE__)- load File.expand_path("../app/controllers/chat_channels_controller.rb", __FILE__)load File.expand_path("../app/controllers/emojis_controller.rb", __FILE__)load File.expand_path("../app/controllers/direct_messages_controller.rb", __FILE__)load File.expand_path("../app/controllers/incoming_chat_webhooks_controller.rb", __FILE__)@@ -207,13 +206,25 @@ after_initialize doload File.expand_path("../app/services/chat_message_destroyer.rb", __FILE__)load File.expand_path("../app/controllers/api_controller.rb", __FILE__)load File.expand_path("../app/controllers/api/chat_channels_controller.rb", __FILE__)- load File.expand_path("../app/controllers/api/chat_channel_memberships_controller.rb", __FILE__)+ load File.expand_path("../app/controllers/api/chat_current_user_channels_controller.rb", __FILE__)load File.expand_path(- "../app/controllers/api/chat_channel_notifications_settings_controller.rb",+ "../app/controllers/api/chat_channels_current_user_membership_controller.rb",+ __FILE__,+ )+ load File.expand_path("../app/controllers/api/chat_channels_memberships_controller.rb", __FILE__)+ load File.expand_path(+ "../app/controllers/api/chat_channels_messages_moves_controller.rb",+ __FILE__,+ )+ load File.expand_path("../app/controllers/api/chat_channels_archives_controller.rb", __FILE__)+ load File.expand_path("../app/controllers/api/chat_channels_status_controller.rb", __FILE__)+ load File.expand_path(+ "../app/controllers/api/chat_channels_current_user_notifications_settings_controller.rb",__FILE__,)load File.expand_path("../app/controllers/api/category_chatables_controller.rb", __FILE__)load File.expand_path("../app/controllers/api/hints_controller.rb", __FILE__)+ load File.expand_path("../app/controllers/api/chat_chatables_controller.rb", __FILE__)load File.expand_path("../app/queries/chat_channel_memberships_query.rb", __FILE__)if Discourse.allow_dev_populate?@@ -245,7 +256,6 @@ after_initialize doCategory.prepend Chat::CategoryExtensionUser.prepend Chat::UserExtensionJobs::UserEmail.prepend Chat::UserEmailExtension-Bookmark.register_bookmarkable(ChatMessageBookmarkable)end@@ -579,12 +589,23 @@ after_initialize doendChat::Engine.routes.draw do- namespace :api do- get "/chat_channels" => "chat_channels#index"- get "/chat_channels/:chat_channel_id/memberships" => "chat_channel_memberships#index"- put "/chat_channels/:chat_channel_id" => "chat_channels#update"- put "/chat_channels/:chat_channel_id/notifications_settings" =>- "chat_channel_notifications_settings#update"+ namespace :api, defaults: { format: :json } do+ get "/chatables" => "chat_chatables#index"+ get "/channels" => "chat_channels#index"+ get "/channels/me" => "chat_current_user_channels#index"+ post "/channels" => "chat_channels#create"+ delete "/channels/:channel_id" => "chat_channels#destroy"+ put "/channels/:channel_id" => "chat_channels#update"+ get "/channels/:channel_id" => "chat_channels#show"+ put "/channels/:channel_id/status" => "chat_channels_status#update"+ post "/channels/:channel_id/messages/moves" => "chat_channels_messages_moves#create"+ post "/channels/:channel_id/archives" => "chat_channels_archives#create"+ get "/channels/:channel_id/memberships" => "chat_channels_memberships#index"+ delete "/channels/:channel_id/memberships/me" =>+ "chat_channels_current_user_membership#destroy"+ post "/channels/:channel_id/memberships/me" => "chat_channels_current_user_membership#create"+ put "/channels/:channel_id/notifications-settings/me" =>+ "chat_channels_current_user_notifications_settings#update"# Category chatables controller hints. Only used by staff members, we don't want to leak category permissions.get "/category-chatables/:id/permissions" => "category_chatables#permissions",@@ -607,18 +628,9 @@ after_initialize do# chat_channel_controller routesget "/chat_channels" => "chat_channels#index"- put "/chat_channels" => "chat_channels#create"- get "/chat_channels/search" => "chat_channels#search"- post "/chat_channels/:chat_channel_id" => "chat_channels#edit"post "/chat_channels/:chat_channel_id/notification_settings" =>"chat_channels#notification_settings"- post "/chat_channels/:chat_channel_id/follow" => "chat_channels#follow"- post "/chat_channels/:chat_channel_id/unfollow" => "chat_channels#unfollow"get "/chat_channels/:chat_channel_id" => "chat_channels#show"- put "/chat_channels/:chat_channel_id/archive" => "chat_channels#archive"- put "/chat_channels/:chat_channel_id/retry_archive" => "chat_channels#retry_archive"- put "/chat_channels/:chat_channel_id/change_status" => "chat_channels#change_status"- delete "/chat_channels/:chat_channel_id" => "chat_channels#destroy"# chat_controller routesget "/" => "chat#respond"@@ -645,7 +657,6 @@ after_initialize doput "/:chat_channel_id/:message_id/rebake" => "chat#rebake"post "/:chat_channel_id/:message_id/flag" => "chat#flag"post "/:chat_channel_id/quote" => "chat#quote_messages"- put "/:chat_channel_id/move_messages_to_channel" => "chat#move_messages_to_channel"put "/:chat_channel_id/restore/:message_id" => "chat#restore"get "/lookup/:message_id" => "chat#lookup_message"put "/:chat_channel_id/read/:message_id" => "chat#update_user_last_read"@@ -742,7 +753,7 @@ after_initialize do}register_user_destroyer_on_content_deletion_callback(- Proc.new { |user| Jobs.enqueue(:delete_user_messages, user_id: user.id) }+ Proc.new { |user| Jobs.enqueue(:delete_user_messages, user_id: user.id) },)enddiff --git a/plugins/chat/spec/fabricators/chat_fabricator.rb b/plugins/chat/spec/fabricators/chat_fabricator.rbindex ee07f45022a..58752279971 100644--- a/plugins/chat/spec/fabricators/chat_fabricator.rb+++ b/plugins/chat/spec/fabricators/chat_fabricator.rb@@ -16,19 +16,37 @@ Fabricator(:chat_channel) doendchatable { Fabricate(:category) }type do |attrs|- attrs[:chatable_type] == "Category" || attrs[:chatable]&.is_a?(Category) ? "CategoryChannel" : "DirectMessageChannel"+ if attrs[:chatable_type] == "Category" || attrs[:chatable]&.is_a?(Category)+ "CategoryChannel"+ else+ "DirectMessageChannel"+ endendstatus { :open }endFabricator(:category_channel, from: :chat_channel, class_name: :category_channel) {}+Fabricator(:private_category_channel, from: :category_channel, class_name: :category_channel) do+ transient :group+ chatable { |attrs| Fabricate(:private_category, group: attrs[:group] || Group[:staff]) }+end+Fabricator(:direct_message_channel, from: :chat_channel, class_name: :direct_message_channel) do- transient :users+ transient :users, following: true, with_membership: truechatable do |attrs|Fabricate(:direct_message, users: attrs[:users] || [Fabricate(:user), Fabricate(:user)])endstatus { :open }+ name nil+ after_create do |channel, attrs|+ if attrs[:with_membership]+ channel.chatable.users.each do |user|+ membership = channel.add(user)+ membership.update!(following: false) if attrs[:following] == false+ end+ end+ endendFabricator(:chat_message) do@@ -37,6 +55,7 @@ Fabricator(:chat_message) domessage "Beep boop"cooked { |attrs| ChatMessage.cook(attrs[:message]) }cooked_version ChatMessage::BAKED_VERSION+ in_reply_to nilendFabricator(:chat_mention) do@@ -49,6 +68,9 @@ Fabricator(:chat_message_reaction) dochat_message { Fabricate(:chat_message) }user { Fabricate(:user) }emoji { %w[+1 tada heart joffrey_facepalm].sample }+ after_build do |chat_message_reaction|+ chat_message_reaction.chat_message.chat_channel.add(chat_message_reaction.user)+ endendFabricator(:chat_upload) dodiff --git a/plugins/chat/spec/jobs/regular/auto_join_channel_batch_spec.rb b/plugins/chat/spec/jobs/regular/auto_join_channel_batch_spec.rbindex 568b94e8dad..e97776b10fe 100644--- a/plugins/chat/spec/jobs/regular/auto_join_channel_batch_spec.rb+++ b/plugins/chat/spec/jobs/regular/auto_join_channel_batch_spec.rb@@ -138,7 +138,7 @@ describe Jobs::AutoJoinChannelBatch doendexpect(messages.size).to eq(1)- expect(messages.first.data.dig(:chat_channel, :id)).to eq(channel.id)+ expect(messages.first.data.dig(:channel, :id)).to eq(channel.id)enddescribe "context when the channel's category is read restricted" dodiff --git a/plugins/chat/spec/jobs/regular/chat_notify_watching_spec.rb b/plugins/chat/spec/jobs/regular/chat_notify_watching_spec.rbindex 1690c3b0184..72a09d58bf8 100644--- a/plugins/chat/spec/jobs/regular/chat_notify_watching_spec.rb+++ b/plugins/chat/spec/jobs/regular/chat_notify_watching_spec.rb@@ -163,7 +163,9 @@ RSpec.describe Jobs::ChatNotifyWatching doendcontext "for a direct message channel" do- fab!(:channel) { Fabricate(:direct_message_channel, users: [user1, user2, user3]) }+ fab!(:channel) do+ Fabricate(:direct_message_channel, users: [user1, user2, user3], with_membership: false)+ endfab!(:membership1) doFabricate(:user_chat_channel_membership, user: user1, chat_channel: channel)enddiff --git a/plugins/chat/spec/lib/chat_channel_fetcher_spec.rb b/plugins/chat/spec/lib/chat_channel_fetcher_spec.rbindex 5d0a3a05864..354a6b15996 100644--- a/plugins/chat/spec/lib/chat_channel_fetcher_spec.rb+++ b/plugins/chat/spec/lib/chat_channel_fetcher_spec.rb@@ -139,11 +139,18 @@ describe Chat::ChatChannelFetcher docontext "when restricted category" dofab!(:group) { Fabricate(:group) }- fab!(:category_group) { Fabricate(:category_group, category: private_category, group: group, permission_type: CategoryGroup.permission_types[:readonly]) }- fab!(:group_user) { Fabricate(:group_user, group: private_category.groups.last, user: user1) }- before do- category_channel.update!(chatable: private_category)+ fab!(:category_group) do+ Fabricate(+ :category_group,+ category: private_category,+ group: group,+ permission_type: CategoryGroup.permission_types[:readonly],+ )+ end+ fab!(:group_user) do+ Fabricate(:group_user, group: private_category.groups.last, user: user1)end+ before { category_channel.update!(chatable: private_category) }it "does not include the category channel for member of group with readonly access" doexpect(subject.all_secured_channel_ids(guardian)).to be_empty@@ -195,22 +202,12 @@ describe Chat::ChatChannelFetcher doit "can filter by an array of slugs" doexpect(- subject.secured_public_channels(- guardian,- memberships,- slugs: ["support"],- ).map(&:id),+ subject.secured_public_channels(guardian, memberships, slugs: ["support"]).map(&:id),).to match_array([category_channel.id])endit "returns nothing if the array of slugs is empty" do- expect(- subject.secured_public_channels(- guardian,- memberships,- slugs: [],- ).map(&:id),- ).to eq([])+ expect(subject.secured_public_channels(guardian, memberships, slugs: []).map(&:id)).to eq([])endit "can filter by status" dodiff --git a/plugins/chat/spec/lib/direct_message_channel_creator_spec.rb b/plugins/chat/spec/lib/direct_message_channel_creator_spec.rbindex 1b88cce7983..ff3863ca3a7 100644--- a/plugins/chat/spec/lib/direct_message_channel_creator_spec.rb+++ b/plugins/chat/spec/lib/direct_message_channel_creator_spec.rb@@ -10,8 +10,12 @@ describe Chat::DirectMessageChannelCreator dobefore { Group.refresh_automatic_groups! }context "with an existing direct message channel" do- fab!(:dm_chat_channel) { Fabricate(:direct_message_channel, users: [user_1, user_2, user_3]) }- fab!(:own_chat_channel) { Fabricate(:direct_message_channel, users: [user_1]) }+ fab!(:dm_chat_channel) do+ Fabricate(:direct_message_channel, users: [user_1, user_2, user_3], with_membership: false)+ end+ fab!(:own_chat_channel) do+ Fabricate(:direct_message_channel, users: [user_1], with_membership: false)+ endit "doesn't create a new chat channel" doexisting_channel = nil@@ -71,7 +75,7 @@ describe Chat::DirectMessageChannelCreator doexpect(user_3_membership.following).to eq(false)end- it "publishes the new DM channel message bus message for each user" do+ it "publishes the new DM channel message bus message for each user not following yet" domessages =MessageBus.track_publish do@@ -81,7 +85,7 @@ describe Chat::DirectMessageChannelCreator doexpect(messages.count).to eq(3)expect(messages.first[:data]).to be_kind_of(Hash)- expect(messages.map { |m| m.dig(:data, :chat_channel, :id) }).to eq(+ expect(messages.map { |m| m.dig(:data, :channel, :id) }).to eq([dm_chat_channel.id, dm_chat_channel.id, dm_chat_channel.id],)end@@ -161,7 +165,7 @@ describe Chat::DirectMessageChannelCreator dochat_channel = ChatChannel.lastexpect(messages.count).to eq(2)expect(messages.first[:data]).to be_kind_of(Hash)- expect(messages.map { |m| m.dig(:data, :chat_channel, :id) }).to eq(+ expect(messages.map { |m| m.dig(:data, :channel, :id) }).to eq([chat_channel.id, chat_channel.id],)enddiff --git a/plugins/chat/spec/plugin_helper.rb b/plugins/chat/spec/plugin_helper.rbindex 09c4fbe37e8..33657da1fc5 100644--- a/plugins/chat/spec/plugin_helper.rb+++ b/plugins/chat/spec/plugin_helper.rb@@ -1,7 +1,7 @@# frozen_string_literal: truemodule ChatSystemHelpers- def chat_system_bootstrap(user, channels_for_membership = [])+ def chat_system_bootstrap(user = Fabricate(:admin), channels_for_membership = [])# ensures we have one valid registered admin/useruser.activate@@ -16,9 +16,10 @@ module ChatSystemHelpersendGroup.refresh_automatic_groups!++ # this is reset after each test+ Bookmark.register_bookmarkable(ChatMessageBookmarkable)endend-RSpec.configure do |config|- config.include ChatSystemHelpers, type: :system-end+RSpec.configure { |config| config.include ChatSystemHelpers, type: :system }diff --git a/plugins/chat/spec/plugin_spec.rb b/plugins/chat/spec/plugin_spec.rbindex 64bbde077bb..f31c4c1ec92 100644--- a/plugins/chat/spec/plugin_spec.rb+++ b/plugins/chat/spec/plugin_spec.rb@@ -349,11 +349,6 @@ describe Chat dofab!(:user_2) { Fabricate(:user) }fab!(:channel) { Fabricate(:direct_message_channel, users: [user, user_2]) }- before do- Fabricate(:user_chat_channel_membership, user: user, chat_channel: channel, following: true)- Fabricate(:direct_message_channel, users: [user, user_2])- end-it "returns them" doexpect(serializer.chat_channels[:public_channels]).to eq([])expect(serializer.chat_channels[:direct_message_channels].count).to eq(1)diff --git a/plugins/chat/spec/queries/chat_channel_memberships_query_spec.rb b/plugins/chat/spec/queries/chat_channel_memberships_query_spec.rbindex 73cfa74ce9f..409349c0ef9 100644--- a/plugins/chat/spec/queries/chat_channel_memberships_query_spec.rb+++ b/plugins/chat/spec/queries/chat_channel_memberships_query_spec.rb@@ -108,31 +108,18 @@ describe ChatChannelMembershipsQuery doendcontext "when chatable is direct channel" do- fab!(:channel_1) { Fabricate(:direct_message_channel, users: [user_1, user_2]) }-context "when no memberships exists" do+ fab!(:channel_1) do+ Fabricate(:direct_message_channel, users: [user_1, user_2], with_membership: false)+ end+it "returns an empty array" doexpect(described_class.call(channel_1)).to eq([])endendcontext "when memberships exist" do- before do- UserChatChannelMembership.create!(- user: user_1,- chat_channel: channel_1,- following: true,- desktop_notification_level: UserChatChannelMembership::NOTIFICATION_LEVELS[:always],- mobile_notification_level: UserChatChannelMembership::NOTIFICATION_LEVELS[:always],- )- UserChatChannelMembership.create!(- user: user_2,- chat_channel: channel_1,- following: true,- desktop_notification_level: UserChatChannelMembership::NOTIFICATION_LEVELS[:always],- mobile_notification_level: UserChatChannelMembership::NOTIFICATION_LEVELS[:always],- )- end+ fab!(:channel_1) { Fabricate(:direct_message_channel, users: [user_1, user_2]) }it "returns the memberships" domemberships = described_class.call(channel_1)diff --git a/plugins/chat/spec/requests/api/category_chatables_controller_spec.rb b/plugins/chat/spec/requests/api/category_chatables_controller_spec.rbindex cfea49060d0..cf4d2047856 100644--- a/plugins/chat/spec/requests/api/category_chatables_controller_spec.rb+++ b/plugins/chat/spec/requests/api/category_chatables_controller_spec.rb@@ -14,12 +14,26 @@ describe Chat::Api::CategoryChatablesController doit "returns a list with the group names that could access a chat channel" doreadonly_group = Fabricate(:group)- Fabricate(:category_group, category: private_category, group: readonly_group, permission_type: CategoryGroup.permission_types[:readonly])+ Fabricate(+ :category_group,+ category: private_category,+ group: readonly_group,+ permission_type: CategoryGroup.permission_types[:readonly],+ )create_post_group = Fabricate(:group)- create_post_category_group = Fabricate(:category_group, category: private_category, group: create_post_group, permission_type: CategoryGroup.permission_types[:create_post])- get "/chat/api/category-chatables/#{private_category.id}/permissions.json"-- expect(response.parsed_body["allowed_groups"]).to contain_exactly("@#{group.name}", "@#{create_post_group.name}")+ create_post_category_group =+ Fabricate(+ :category_group,+ category: private_category,+ group: create_post_group,+ permission_type: CategoryGroup.permission_types[:create_post],+ )+ get "/chat/api/category-chatables/#{private_category.id}/permissions"++ expect(response.parsed_body["allowed_groups"]).to contain_exactly(+ "@#{group.name}",+ "@#{create_post_group.name}",+ )expect(response.parsed_body["members_count"]).to eq(0)expect(response.parsed_body["private"]).to eq(true)end@@ -30,7 +44,7 @@ describe Chat::Api::CategoryChatablesController dogroup_2.add(a_member)category_2 = Fabricate(:private_category, group: group_2)- get "/chat/api/category-chatables/#{category_2.id}/permissions.json"+ get "/chat/api/category-chatables/#{category_2.id}/permissions"expect(response.parsed_body["allowed_groups"]).to contain_exactly("@#{group_2.name}")expect(response.parsed_body["members_count"]).to eq(1)@@ -42,7 +56,7 @@ describe Chat::Api::CategoryChatablesController docategory_2 = Fabricate(:category)everyone_group = Group.find(Group::AUTO_GROUPS[:everyone])- get "/chat/api/category-chatables/#{category_2.id}/permissions.json"+ get "/chat/api/category-chatables/#{category_2.id}/permissions"expect(response.parsed_body["allowed_groups"]).to contain_exactly("@#{everyone_group.name}")expect(response.parsed_body["members_count"]).to be_nil@@ -53,7 +67,7 @@ describe Chat::Api::CategoryChatablesController donumber_of_users = 3number_of_users.times { group.add(Fabricate(:user)) }- get "/chat/api/category-chatables/#{private_category.id}/permissions.json"+ get "/chat/api/category-chatables/#{private_category.id}/permissions"expect(response.parsed_body["allowed_groups"]).to contain_exactly("@#{group.name}")expect(response.parsed_body["members_count"]).to eq(number_of_users)@@ -61,7 +75,7 @@ describe Chat::Api::CategoryChatablesController doendit "returns a 404 when passed an invalid category" do- get "/chat/api/category-chatables/-99/permissions.json"+ get "/chat/api/category-chatables/-99/permissions"expect(response.status).to eq(404)end@@ -69,7 +83,7 @@ describe Chat::Api::CategoryChatablesController docontext "as anon" doit "returns a 404" do- get "/chat/api/category-chatables/#{private_category.id}/permissions.json"+ get "/chat/api/category-chatables/#{private_category.id}/permissions"expect(response.status).to eq(404)end@@ -81,7 +95,7 @@ describe Chat::Api::CategoryChatablesController dobefore { sign_in(user) }it "returns a 404" do- get "/chat/api/category-chatables/#{private_category.id}/permissions.json"+ get "/chat/api/category-chatables/#{private_category.id}/permissions"expect(response.status).to eq(404)enddiff --git a/plugins/chat/spec/requests/api/chat_channel_memberships_spec.rb b/plugins/chat/spec/requests/api/chat_channel_memberships_spec.rbdeleted file mode 100644index 5c765321242..00000000000--- a/plugins/chat/spec/requests/api/chat_channel_memberships_spec.rb+++ /dev/null@@ -1,39 +0,0 @@-# frozen_string_literal: true--require "rails_helper"--describe Chat::Api::ChatChannelMembershipsController do- fab!(:user_1) { Fabricate(:user, username: "bob") }- fab!(:user_2) { Fabricate(:user, username: "clark") }- fab!(:channel_1) { Fabricate(:category_channel) }-- before do- SiteSetting.chat_enabled = true- SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]- end-- describe "#index" do- include_examples "channel access example", :get, "/memberships.json"-- context "when memberships exist" do- before do- UserChatChannelMembership.create(user: user_1, chat_channel: channel_1, following: true)- UserChatChannelMembership.create(- user: Fabricate(:user),- chat_channel: channel_1,- following: false,- )- UserChatChannelMembership.create(user: user_2, chat_channel: channel_1, following: true)- sign_in(user_1)- end-- it "lists followed memberships" do- get "/chat/api/chat_channels/#{channel_1.id}/memberships.json"-- expect(response.parsed_body.length).to eq(2)- expect(response.parsed_body[0]["user"]["id"]).to eq(user_1.id)- expect(response.parsed_body[1]["user"]["id"]).to eq(user_2.id)- end- end- end-enddiff --git a/plugins/chat/spec/requests/api/chat_channel_notifications_settings_controller_spec.rb b/plugins/chat/spec/requests/api/chat_channel_notifications_settings_controller_spec.rbdeleted file mode 100644index 955e26b5ccd..00000000000--- a/plugins/chat/spec/requests/api/chat_channel_notifications_settings_controller_spec.rb+++ /dev/null@@ -1,145 +0,0 @@-# frozen_string_literal: true--RSpec.describe Chat::Api::ChatChannelNotificationsSettingsController do- before do- SiteSetting.chat_enabled = true- SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]- end-- fab!(:chat_channel) { Fabricate(:category_channel) }- fab!(:user) { Fabricate(:user) }-- describe "#update" do- include_examples "channel access example", :put, "/notifications_settings.json"-- it 'calls guardian ensure_can_join_chat_channel!' do- sign_in(user)- Guardian.any_instance.expects(:ensure_can_join_chat_channel!).once- put "/chat/api/chat_channels/#{chat_channel.id}/notifications_settings.json",- params: {- muted: true,- desktop_notification_level: "always",- mobile_notification_level: "never",- }- end-- context "when category channel has invalid params" do- fab!(:membership) do- Fabricate(:user_chat_channel_membership, user: user, chat_channel: chat_channel)- end-- before { sign_in(user) }-- it "doesn’t use invalid params" do- UserChatChannelMembership.any_instance.expects(:update!).with({ "muted" => "true" }).once-- put "/chat/api/chat_channels/#{chat_channel.id}/notifications_settings.json",- params: {- muted: true,- foo: 1,- }-- expect(response.status).to eq(200)- end- end-- context "when category channel has valid params" do- fab!(:membership) do- Fabricate(- :user_chat_channel_membership,- muted: false,- user: user,- chat_channel: chat_channel,- )- end-- before { sign_in(user) }-- it "updates the notifications settings" do- put "/chat/api/chat_channels/#{chat_channel.id}/notifications_settings.json",- params: {- muted: true,- desktop_notification_level: "always",- mobile_notification_level: "never",- }-- expect(response.status).to eq(200)- expect(response.parsed_body).to match_response_schema("user_chat_channel_membership")-- membership.reload-- expect(membership.muted).to eq(true)- expect(membership.desktop_notification_level).to eq("always")- expect(membership.mobile_notification_level).to eq("never")- end- end-- context "when membership doesn’t exist" do- fab!(:chat_channel) { Fabricate(:category_channel) }- fab!(:user) { Fabricate(:user) }-- before { sign_in(user) }-- it "raises a 404" do- put "/chat/api/chat_channels/#{chat_channel.id}/notifications_settings.json"-- expect(response.status).to eq(404)- end- end-- context "when direct message channel has invalid params" do- fab!(:user) { Fabricate(:user) }- fab!(:chat_channel) { Fabricate(:direct_message_channel, users: [user, Fabricate(:user)]) }- fab!(:membership) do- Fabricate(:user_chat_channel_membership, user: user, chat_channel: chat_channel)- end-- before { sign_in(user) }-- it "doesn’t use invalid params" do- UserChatChannelMembership.any_instance.expects(:update!).with({ "muted" => "true" }).once-- put "/chat/api/chat_channels/#{chat_channel.id}/notifications_settings.json",- params: {- muted: true,- foo: 1,- }-- expect(response.status).to eq(200)- end- end-- context "when direct message channel has valid params" do- fab!(:user) { Fabricate(:user) }- fab!(:chat_channel) { Fabricate(:direct_message_channel, users: [user, Fabricate(:user)]) }- fab!(:membership) do- Fabricate(- :user_chat_channel_membership,- muted: false,- user: user,- chat_channel: chat_channel,- )- end-- before { sign_in(user) }-- it "updates the notifications settings" do- put "/chat/api/chat_channels/#{chat_channel.id}/notifications_settings.json",- params: {- muted: true,- desktop_notification_level: "always",- mobile_notification_level: "never",- }-- expect(response.status).to eq(200)- expect(response.parsed_body).to match_response_schema("user_chat_channel_membership")-- membership.reload-- expect(membership.muted).to eq(true)- expect(membership.desktop_notification_level).to eq("always")- expect(membership.mobile_notification_level).to eq("never")- end- end- end-enddiff --git a/plugins/chat/spec/requests/api/chat_channels_archives_controller_spec.rb b/plugins/chat/spec/requests/api/chat_channels_archives_controller_spec.rbnew file mode 100644index 00000000000..c209f5f4985--- /dev/null+++ b/plugins/chat/spec/requests/api/chat_channels_archives_controller_spec.rb@@ -0,0 +1,145 @@+# frozen_string_literal: true++require "rails_helper"++RSpec.describe Chat::Api::ChatChannelsArchivesController do+ fab!(:user) { Fabricate(:user) }+ fab!(:admin) { Fabricate(:admin) }+ fab!(:category) { Fabricate(:category) }+ fab!(:channel) { Fabricate(:category_channel, chatable: category) }++ let(:new_topic_params) do+ {+ archive: {+ type: "new_topic",+ title: "This is a test archive topic",+ category_id: category.id,+ },+ }+ end+ let(:existing_topic_params) do+ { archive: { type: "existing_topic", topic_id: Fabricate(:topic).id } }+ end++ before do+ SiteSetting.chat_enabled = true+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]+ SiteSetting.chat_duplicate_message_sensitivity = 0+ end++ describe "#create" do+ it "returns error if user is not staff" do+ sign_in(user)+ post "/chat/api/channels/#{channel.id}/archives", params: new_topic_params+ expect(response.status).to eq(403)+ end++ it "returns error if type or chat_channel_id is not provided" do+ sign_in(admin)+ post "/chat/api/channels/#{channel.id}/archives"+ expect(response.status).to eq(400)+ end++ it "returns error if title is not provided for new topic" do+ sign_in(admin)+ post "/chat/api/channels/#{channel.id}/archives", params: { type: "new_topic" }+ expect(response.status).to eq(400)+ end++ it "returns error if topic_id is not provided for existing topic" do+ sign_in(admin)+ post "/chat/api/channels/#{channel.id}/archives", params: { type: "existing_topic" }+ expect(response.status).to eq(400)+ end++ it "returns error if the channel cannot be archived" do+ channel.update!(status: :archived)+ sign_in(admin)+ post "/chat/api/channels/#{channel.id}/archives", params: new_topic_params+ expect(response.status).to eq(403)+ end++ it "starts the archive process using a new topic" do+ sign_in(admin)+ post "/chat/api/channels/#{channel.id}/archives", params: new_topic_params+ channel_archive = ChatChannelArchive.find_by(chat_channel: channel)+ expect(+ job_enqueued?(+ job: :chat_channel_archive,+ args: {+ chat_channel_archive_id: channel_archive.id,+ },+ ),+ ).to eq(true)+ expect(channel.reload.status).to eq("read_only")+ end++ it "starts the archive process using an existing topic" do+ sign_in(admin)+ post "/chat/api/channels/#{channel.id}/archives", params: existing_topic_params+ channel_archive = ChatChannelArchive.find_by(chat_channel: channel)+ expect(+ job_enqueued?(+ job: :chat_channel_archive,+ args: {+ chat_channel_archive_id: channel_archive.id,+ },+ ),+ ).to eq(true)+ expect(channel.reload.status).to eq("read_only")+ end++ it "does nothing if the chat channel archive already exists" do+ sign_in(admin)+ post "/chat/api/channels/#{channel.id}/archives", params: new_topic_params+ expect(response.status).to eq(200)+ expect {+ post "/chat/api/channels/#{channel.id}/archives", params: new_topic_params+ }.not_to change { ChatChannelArchive.count }+ end++ describe "when retrying the archive process" do+ fab!(:channel) { Fabricate(:category_channel, chatable: category, status: :read_only) }+ fab!(:archive) do+ ChatChannelArchive.create!(+ chat_channel: channel,+ destination_topic_title: "test archive topic title",+ archived_by: admin,+ total_messages: 10,+ )+ end++ it "returns error if user is not staff" do+ sign_in(user)+ post "/chat/api/channels/#{channel.id}/archives"+ expect(response.status).to eq(403)+ end++ it "returns a 403 error if the archive is not currently failed" do+ sign_in(admin)+ archive.update!(archive_error: nil)+ post "/chat/api/channels/#{channel.id}/archives"+ expect(response.status).to eq(403)+ end++ it "returns a 403 error if the channel is not read_only" do+ sign_in(admin)+ archive.update!(archive_error: "bad stuff", archived_messages: 1)+ channel.update!(status: "open")+ post "/chat/api/channels/#{channel.id}/archives"+ expect(response.status).to eq(403)+ end++ it "re-enqueues the archive job" do+ sign_in(admin)+ archive.update!(archive_error: "bad stuff", archived_messages: 1)++ expect { post "/chat/api/channels/#{channel.id}/archives" }.to change(+ Jobs::ChatChannelArchive.jobs,+ :size,+ ).by (1)+ expect(response.status).to eq(200)+ end+ end+ end+enddiff --git a/plugins/chat/spec/requests/api/chat_channels_controller_spec.rb b/plugins/chat/spec/requests/api/chat_channels_controller_spec.rbindex f3da20c1d77..fd1a3375ea0 100644--- a/plugins/chat/spec/requests/api/chat_channels_controller_spec.rb+++ b/plugins/chat/spec/requests/api/chat_channels_controller_spec.rb@@ -2,7 +2,7 @@require "rails_helper"-describe Chat::Api::ChatChannelsController do+RSpec.describe Chat::Api::ChatChannelsController dobefore doSiteSetting.chat_enabled = trueSiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]@@ -10,72 +10,231 @@ describe Chat::Api::ChatChannelsController dodescribe "#index" docontext "as anonymous user" do- it "returns a 403" do- get "/chat/api/chat_channels.json"+ it "returns an error" do+ get "/chat/api/channels"++ expect(response.status).to eq(403)+ end+ end++ context "as disallowed user" do+ fab!(:current_user) { Fabricate(:user) }++ before do+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:staff]+ sign_in(current_user)+ end++ it "returns an error" do+ get "/chat/api/channels"++ expect(response.status).to eq(403)+ end+ end++ context "as allowed user" do+ fab!(:current_user) { Fabricate(:user) }++ before { sign_in(current_user) }++ context "with category channels" do+ context "when channel is public" do+ fab!(:channel_1) { Fabricate(:category_channel) }++ it "returns the channel" do+ get "/chat/api/channels"++ expect(response.status).to eq(200)+ expect(response.parsed_body["channels"].map { |channel| channel["id"] }).to eq(+ [channel_1.id],+ )+ end++ context "when chatable is destroyed" do+ before { channel_1.chatable.destroy! }++ it "returns nothing" do+ get "/chat/api/channels"++ expect(response.status).to eq(200)+ expect(response.parsed_body["channels"]).to be_blank+ end+ end+ end++ context "when channel has limited access" do+ fab!(:group_1) { Fabricate(:group) }+ fab!(:channel_1) { Fabricate(:private_category_channel, group: group_1) }++ context "when user has access" do+ before { group_1.add(current_user) }++ it "returns the channel" do+ get "/chat/api/channels"++ expect(response.status).to eq(200)+ expect(response.parsed_body["channels"].map { |channel| channel["id"] }).to eq(+ [channel_1.id],+ )+ end+ end++ context "when user has no access" do+ it "returns nothing" do+ get "/chat/api/channels"++ expect(response.status).to eq(200)+ expect(response.parsed_body["channels"]).to be_blank+ end++ context "when user is admin" do+ before { sign_in(Fabricate(:admin)) }++ it "returns the channels" do+ get "/chat/api/channels"++ expect(response.status).to eq(200)+ expect(response.parsed_body["channels"].map { |channel| channel["id"] }).to eq(+ [channel_1.id],+ )+ end+ end+ end+ end+ end++ context "with direct message channels" do+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user]) }++ it "doesnt return direct message channels" do+ get "/chat/api/channels"+ expect(response.parsed_body["channels"]).to be_blank+ end+ end+ end+ end++ describe "#show" do+ context "when anonymous" do+ it "returns an error" do+ get "/chat/api/channels/-999"+expect(response.status).to eq(403)endend- describe "params" do- fab!(:opened_channel) { Fabricate(:category_channel, name: "foo") }- fab!(:closed_channel) { Fabricate(:category_channel, name: "bar", status: :closed) }+ context "when user cannot access channel" do+ fab!(:channel_1) { Fabricate(:private_category_channel) }before { sign_in(Fabricate(:user)) }- it "returns all channels by default" do- get "/chat/api/chat_channels.json"+ it "returns an error" do+ get "/chat/api/channels/#{channel_1.id}"- expect(response.status).to eq(200)- expect(response.parsed_body.length).to eq(2)+ expect(response.status).to eq(403)end+ end++ context "when user can access channel" do+ fab!(:current_user) { Fabricate(:user) }- it "returns serialized channels " do- get "/chat/api/chat_channels.json"+ before { sign_in(current_user) }- expect(response.status).to eq(200)- response.parsed_body.each do |channel|- expect(channel).to match_response_schema("category_chat_channel")+ context "when channel doesn’t exist" do+ it "returns an error" do+ get "/chat/api/channels/-999"++ expect(response.status).to eq(404)endend- describe "filter" do- it "returns channels filtered by name" do- get "/chat/api/chat_channels.json?filter=foo"+ context "when channel exists" do+ fab!(:channel_1) { Fabricate(:category_channel) }++ it "can find channel by id" do+ get "/chat/api/channels/#{channel_1.id}"expect(response.status).to eq(200)- results = response.parsed_body- expect(results.length).to eq(1)- expect(results[0]["title"]).to eq("foo")+ expect(response.parsed_body["channel"]["id"]).to eq(channel_1.id)endend+ end+ end- describe "status" do- it "returns channels with the status" do- get "/chat/api/chat_channels.json?status=closed"+ describe "#destroy" do+ fab!(:channel_1) { Fabricate(:category_channel) }- expect(response.status).to eq(200)- results = response.parsed_body- expect(results.length).to eq(1)- expect(results[0]["status"]).to eq("closed")+ context "when user is not staff" do+ fab!(:current_user) { Fabricate(:user) }++ before { sign_in(current_user) }++ it "returns an error" do+ delete "/chat/api/channels/#{channel_1.id}",+ params: {+ channel: {+ name_confirmation: channel_1.title(current_user),+ },+ }++ expect(response.status).to eq(403)+ end+ end++ context "when user is admin" do+ fab!(:current_user) { Fabricate(:admin) }++ before { sign_in(current_user) }++ context "when the channel doesn’t exist" do+ before { channel_1.destroy! }++ it "returns an error" do+ delete "/chat/api/channels/#{channel_1.id}",+ params: {+ channel: {+ name_confirmation: channel_1.title(current_user),+ },+ }++ expect(response.status).to eq(404)endend- describe "limit" do- it "returns a number of channel equal to the limit" do- get "/chat/api/chat_channels.json?limit=1"+ context "when the confirmation doesn’t match the channel name" do+ it "returns an error" do+ delete "/chat/api/channels/#{channel_1.id}",+ params: {+ channel: {+ name_confirmation: channel_1.title(current_user) + "foo",+ },+ }- expect(response.status).to eq(200)- results = response.parsed_body- expect(results.length).to eq(1)+ expect(response.status).to eq(400)endend- describe "offset" do- it "returns channels from the offset" do- get "/chat/api/chat_channels.json?offset=2"++ context "with valid params" do+ it "properly destroys the channel" do+ delete "/chat/api/channels/#{channel_1.id}",+ params: {+ channel: {+ name_confirmation: channel_1.title(current_user),+ },+ }expect(response.status).to eq(200)- results = response.parsed_body- expect(results.length).to eq(0)+ expect(channel_1.reload.trashed?).to eq(true)+ expect(+ job_enqueued?(job: :chat_channel_delete, args: { chat_channel_id: channel_1.id }),+ ).to eq(true)+ expect(+ UserHistory.exists?(+ acting_user_id: current_user.id,+ action: UserHistory.actions[:custom_staff],+ custom_type: "chat_channel_delete",+ ),+ ).to eq(true)endendend@@ -87,28 +246,30 @@ describe Chat::Api::ChatChannelsController dolet(:params) do{- type: category.class.name,- id: category.id,- name: "channel name",- description: "My new channel",+ channel: {+ type: category.class.name,+ chatable_id: category.id,+ name: "channel name",+ description: "My new channel",+ },}endbefore { sign_in(admin) }it "creates a channel associated to a category" do- put "/chat/chat_channels.json", params: params+ post "/chat/api/channels", params: paramsnew_channel = ChatChannel.last- expect(new_channel.name).to eq(params[:name])- expect(new_channel.description).to eq(params[:description])+ expect(new_channel.name).to eq(params[:channel][:name])+ expect(new_channel.description).to eq(params[:channel][:description])expect(new_channel.chatable_type).to eq(category.class.name)expect(new_channel.chatable_id).to eq(category.id)endit "creates a channel sets auto_join_users to false by default" do- put "/chat/chat_channels.json", params: params+ post "/chat/api/channels", params: paramsnew_channel = ChatChannel.last@@ -116,7 +277,8 @@ describe Chat::Api::ChatChannelsController doendit "creates a channel with auto_join_users set to true" do- put "/chat/chat_channels.json", params: params.merge(auto_join_users: true)+ params[:channel][:auto_join_users] = true+ post "/chat/api/channels", params: paramsnew_channel = ChatChannel.last@@ -134,9 +296,10 @@ describe Chat::Api::ChatChannelsController doendit "joins the user when auto_join_users is true" do- put "/chat/chat_channels.json", params: params.merge(auto_join_users: true)+ params[:channel][:auto_join_users] = true+ post "/chat/api/channels", params: params- created_channel_id = response.parsed_body.dig("chat_channel", "id")+ created_channel_id = response.parsed_body.dig("channel", "id")membership_exists =UserChatChannelMembership.find_by(user: user,@@ -148,9 +311,10 @@ describe Chat::Api::ChatChannelsController doendit "doesn't join the user when auto_join_users is false" do- put "/chat/chat_channels.json", params: params.merge(auto_join_users: false)+ params[:channel][:auto_join_users] = false+ post "/chat/api/channels", params: params- created_channel_id = response.parsed_body.dig("chat_channel", "id")+ created_channel_id = response.parsed_body.dig("channel", "id")membership_exists =UserChatChannelMembership.find_by(user: user,@@ -167,79 +331,79 @@ describe Chat::Api::ChatChannelsController doinclude_examples "channel access example", :putcontext "when user can’t edit channel" do- fab!(:chat_channel) { Fabricate(:category_channel) }+ fab!(:channel) { Fabricate(:category_channel) }before { sign_in(Fabricate(:user)) }it "returns a 403" do- put "/chat/api/chat_channels/#{chat_channel.id}.json"+ put "/chat/api/channels/#{channel.id}"expect(response.status).to eq(403)endendcontext "when user provided invalid params" do- fab!(:chat_channel) { Fabricate(:category_channel, user_count: 10) }+ fab!(:channel) { Fabricate(:category_channel, user_count: 10) }before { sign_in(Fabricate(:admin)) }it "doesn’t change invalid properties" do- put "/chat/api/chat_channels/#{chat_channel.id}.json", params: { user_count: 40 }+ put "/chat/api/channels/#{channel.id}", params: { user_count: 40 }- expect(chat_channel.reload.user_count).to eq(10)+ expect(channel.reload.user_count).to eq(10)endendcontext "when user provided an empty name" dofab!(:user) { Fabricate(:admin) }- fab!(:chat_channel) do+ fab!(:channel) doFabricate(:category_channel, name: "something", description: "something else")endbefore { sign_in(user) }it "nullifies the field and doesn’t store an empty string" do- put "/chat/api/chat_channels/#{chat_channel.id}.json", params: { name: " " }+ put "/chat/api/channels/#{channel.id}", params: { channel: { name: " " } }- expect(chat_channel.reload.name).to be_nil+ expect(channel.reload.name).to be_nilendit "doesn’t nullify the description" do- put "/chat/api/chat_channels/#{chat_channel.id}.json", params: { name: " " }+ put "/chat/api/channels/#{channel.id}", params: { channel: { name: " " } }- expect(chat_channel.reload.description).to eq("something else")+ expect(channel.reload.description).to eq("something else")endendcontext "when user provides an empty description" dofab!(:user) { Fabricate(:admin) }- fab!(:chat_channel) do+ fab!(:channel) doFabricate(:category_channel, name: "something else", description: "something")endbefore { sign_in(user) }it "nullifies the field and doesn’t store an empty string" do- put "/chat/api/chat_channels/#{chat_channel.id}.json", params: { description: " " }+ put "/chat/api/channels/#{channel.id}", params: { channel: { description: " " } }- expect(chat_channel.reload.description).to be_nil+ expect(channel.reload.description).to be_nilendit "doesn’t nullify the name" do- put "/chat/api/chat_channels/#{chat_channel.id}.json", params: { description: " " }+ put "/chat/api/channels/#{channel.id}", params: { channel: { description: " " } }- expect(chat_channel.reload.name).to eq("something else")+ expect(channel.reload.name).to eq("something else")endendcontext "when channel is a direct message channel" dofab!(:user) { Fabricate(:admin) }- fab!(:chat_channel) { Fabricate(:direct_message_channel) }+ fab!(:channel) { Fabricate(:direct_message_channel) }before { sign_in(user) }it "raises a 403" do- put "/chat/api/chat_channels/#{chat_channel.id}.json"+ put "/chat/api/channels/#{channel.id}"expect(response.status).to eq(403)end@@ -247,60 +411,69 @@ describe Chat::Api::ChatChannelsController docontext "when user provides valid params" dofab!(:user) { Fabricate(:admin) }- fab!(:chat_channel) { Fabricate(:category_channel) }+ fab!(:channel) { Fabricate(:category_channel) }before { sign_in(user) }it "sets properties" do- put "/chat/api/chat_channels/#{chat_channel.id}.json",+ put "/chat/api/channels/#{channel.id}",params: {- name: "joffrey",- description: "cat owner",+ channel: {+ name: "joffrey",+ description: "cat owner",+ },}- expect(chat_channel.reload.name).to eq("joffrey")- expect(chat_channel.reload.description).to eq("cat owner")+ expect(channel.reload.name).to eq("joffrey")+ expect(channel.reload.description).to eq("cat owner")endit "publishes an update" domessages =MessageBus.track_publish("/chat/channel-edits") do- put "/chat/api/chat_channels/#{chat_channel.id}.json"+ put "/chat/api/channels/#{channel.id}",+ params: {+ channel: {+ name: "A new cat overlord",+ },+ }end- expect(messages[0].data[:chat_channel_id]).to eq(chat_channel.id)+ expect(messages[0].data[:chat_channel_id]).to eq(channel.id)endit "returns a valid chat channel" do- put "/chat/api/chat_channels/#{chat_channel.id}.json"+ put "/chat/api/channels/#{channel.id}", params: { channel: { name: "A new cat is born" } }- expect(response.parsed_body).to match_response_schema("category_chat_channel")+ expect(response.parsed_body["channel"]).to match_response_schema("category_chat_channel")enddescribe "when updating allow_channel_wide_mentions" doit "sets the new value" do- put "/chat/api/chat_channels/#{chat_channel.id}.json",+ put "/chat/api/channels/#{channel.id}",params: {- allow_channel_wide_mentions: false,+ channel: {+ allow_channel_wide_mentions: false,+ },}- expect(response.parsed_body["allow_channel_wide_mentions"]).to eq(false)+ expect(response.parsed_body["channel"]["allow_channel_wide_mentions"]).to eq(false)endenddescribe "Updating a channel to add users automatically" doit "sets the channel to auto-update users automatically" do- put "/chat/api/chat_channels/#{chat_channel.id}.json", params: { auto_join_users: true }+ put "/chat/api/channels/#{channel.id}", params: { channel: { auto_join_users: true } }- expect(response.parsed_body["auto_join_users"]).to eq(true)+ expect(response.parsed_body["channel"]["auto_join_users"]).to eq(true)endit "tells staff members to slow down when toggling auto-update multiple times" doRateLimiter.enable- put "/chat/api/chat_channels/#{chat_channel.id}.json", params: { auto_join_users: true }- put "/chat/api/chat_channels/#{chat_channel.id}.json", params: { auto_join_users: false }- put "/chat/api/chat_channels/#{chat_channel.id}.json", params: { auto_join_users: true }+ put "/chat/api/channels/#{channel.id}", params: { channel: { auto_join_users: true } }+ put "/chat/api/channels/#{channel.id}", params: { channel: { auto_join_users: false } }+ put "/chat/api/channels/#{channel.id}", params: { channel: { auto_join_users: true } }expect(response.status).to eq(429)end@@ -311,14 +484,14 @@ describe Chat::Api::ChatChannelsController dobefore doJobs.run_immediately!- Fabricate(:category_group, category: chat_channel.chatable, group: chatters_group)+ Fabricate(:category_group, category: channel.chatable, group: chatters_group)chatters_group.add(another_user)endit "joins the user when auto_join_users is true" do- put "/chat/api/chat_channels/#{chat_channel.id}.json", params: { auto_join_users: true }+ put "/chat/api/channels/#{channel.id}", params: { channel: { auto_join_users: true } }- created_channel_id = response.parsed_body["id"]+ created_channel_id = response.parsed_body["channel"]["id"]membership_exists =UserChatChannelMembership.find_by(user: another_user,@@ -330,12 +503,12 @@ describe Chat::Api::ChatChannelsController doendit "doesn't join the user when auto_join_users is false" do- put "/chat/api/chat_channels/#{chat_channel.id}.json",- params: {- auto_join_users: false,- }+ put "/chat/api/channels/#{channel.id}", params: { channel: { auto_join_users: false } }++ created_channel_id = response.parsed_body["channel"]["id"]++ expect(created_channel_id).to be_present- created_channel_id = response.parsed_body["id"]membership_exists =UserChatChannelMembership.find_by(user: another_user,diff --git a/plugins/chat/spec/requests/api/chat_channels_current_user_membership_spec.rb b/plugins/chat/spec/requests/api/chat_channels_current_user_membership_spec.rbnew file mode 100644index 00000000000..80fd842fb34--- /dev/null+++ b/plugins/chat/spec/requests/api/chat_channels_current_user_membership_spec.rb@@ -0,0 +1,151 @@+# frozen_string_literal: true++require "rails_helper"++describe Chat::Api::ChatChannelsCurrentUserMembershipController do+ fab!(:current_user) { Fabricate(:user) }+ fab!(:channel_1) { Fabricate(:category_channel) }++ before do+ SiteSetting.chat_enabled = true+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]+ sign_in(current_user)+ end++ describe "#create" do+ context "when no existing membership exists" do+ it "creates a membership" do+ expect { post "/chat/api/channels/#{channel_1.id}/memberships/me" }.to change {+ UserChatChannelMembership.where(user_id: current_user.id, following: true).count+ }.by(1)+ expect(response.status).to eq(200)+ expect(response.parsed_body["membership"]["following"]).to eq(true)+ expect(response.parsed_body["membership"]["chat_channel_id"]).to eq(channel_1.id)+ expect(response.parsed_body["membership"]["user"]["id"]).to eq(current_user.id)+ end+ end++ context "when current user can’t see the channel" do+ fab!(:channel_2) { Fabricate(:private_category_channel, group: Fabricate(:group)) }++ it "fails" do+ expect { post "/chat/api/channels/#{channel_2.id}/memberships/me" }.not_to change {+ UserChatChannelMembership.where(user_id: current_user.id).count+ }+ expect(response.status).to eq(403)+ end+ end++ context "when channel is channel" do+ context "when current user can't write in channel" do+ fab!(:private_category_1) { Fabricate(:private_category, group: Fabricate(:group)) }+ fab!(:readonly_group_1) { Fabricate(:group) }+ fab!(:channel_2) { Fabricate(:category_channel, chatable: private_category_1) }++ before do+ Fabricate(+ :category_group,+ category: private_category_1,+ group: readonly_group_1,+ permission_type: CategoryGroup.permission_types[:readonly],+ )+ readonly_group_1.add(current_user)+ end++ it "fails" do+ expect { post "/chat/api/channels/#{channel_2.id}/memberships/me" }.not_to change {+ UserChatChannelMembership.where(user_id: current_user.id).count+ }+ expect(response.status).to eq(403)+ end+ end++ context "when current user can write in channel" do+ fab!(:private_category_1) { Fabricate(:private_category, group: Fabricate(:group)) }+ fab!(:readonly_group_1) { Fabricate(:group) }+ fab!(:channel_2) { Fabricate(:category_channel, chatable: private_category_1) }++ before do+ Fabricate(+ :category_group,+ category: private_category_1,+ group: readonly_group_1,+ permission_type: CategoryGroup.permission_types[:create_post],+ )+ readonly_group_1.add(current_user)+ end++ it "works" do+ expect { post "/chat/api/channels/#{channel_2.id}/memberships/me" }.to change {+ UserChatChannelMembership.where(user_id: current_user.id).count+ }.by(1)+ expect(response.status).to eq(200)+ end+ end+ end++ context "when an existing membership exists" do+ it "enforces 'following' to true" do+ membership_record =+ UserChatChannelMembership.create!(+ chat_channel_id: channel_1.id,+ user_id: current_user.id,+ following: false,+ )++ expect { post "/chat/api/channels/#{channel_1.id}/memberships/me" }.to change {+ membership_record.reload.following+ }.to(true).from(false)+ expect(response.status).to eq(200)+ expect(response.parsed_body["membership"]["following"]).to eq(true)+ expect(response.parsed_body["membership"]["chat_channel_id"]).to eq(channel_1.id)+ expect(response.parsed_body["membership"]["user"]["id"]).to eq(current_user.id)+ end+ end+ end++ describe "#destroy" do+ context "when an existing membership exists" do+ before { channel_1.add(current_user) }++ it "enforces 'following' to false" do+ membership_record = channel_1.membership_for(current_user)++ expect { delete "/chat/api/channels/#{channel_1.id}/memberships/me" }.to change {+ membership_record.reload.following+ }.to(false).from(true)+ expect(response.status).to eq(200)+ expect(response.parsed_body["membership"]["following"]).to eq(false)+ expect(response.parsed_body["membership"]["chat_channel_id"]).to eq(channel_1.id)+ expect(response.parsed_body["membership"]["user"]["id"]).to eq(current_user.id)+ end++ context "when current user can’t see the channel" do+ fab!(:channel_2) { Fabricate(:private_category_channel, group: Fabricate(:group)) }++ it "fails" do+ expect { delete "/chat/api/channels/#{channel_2.id}/memberships/me" }.not_to change {+ UserChatChannelMembership.where(user_id: current_user.id).count+ }+ expect(response.status).to eq(403)+ end+ end++ context "when the channel is a direct message channel" do+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user]) }++ it "enforces 'following' to false" do+ membership_record = dm_channel_1.membership_for(current_user)++ expect { delete "/chat/api/channels/#{dm_channel_1.id}/memberships/me" }.to change {+ membership_record.reload.following+ }.to(false).from(true)+ expect(response.status).to eq(200)+ expect(response.parsed_body["membership"]["following"]).to eq(false)+ expect(response.parsed_body["membership"]["chat_channel_id"]).to eq(dm_channel_1.id)+ expect(response.parsed_body["membership"]["user"]["id"]).to eq(current_user.id)+ end+ end+ end+ end+enddiff --git a/plugins/chat/spec/requests/api/chat_channels_current_user_notifications_settings_controller_spec.rb b/plugins/chat/spec/requests/api/chat_channels_current_user_notifications_settings_controller_spec.rbnew file mode 100644index 00000000000..bf0dc2c3536--- /dev/null+++ b/plugins/chat/spec/requests/api/chat_channels_current_user_notifications_settings_controller_spec.rb@@ -0,0 +1,140 @@+# frozen_string_literal: true++RSpec.describe Chat::Api::ChatChannelsCurrentUserNotificationsSettingsController do+ fab!(:current_user) { Fabricate(:user) }++ before do+ SiteSetting.chat_enabled = true+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]+ end++ describe "#update" do+ include_examples "channel access example",+ :put,+ "/notifications-settings/me",+ {+ notifications_settings: {+ muted: true,+ },+ }++ context "when category channel has invalid params" do+ fab!(:channel_1) { Fabricate(:category_channel) }++ before do+ channel_1.add(current_user)+ sign_in(current_user)+ end++ it "doesn’t use invalid params" do+ UserChatChannelMembership.any_instance.expects(:update!).with({ "muted" => "true" }).once++ put "/chat/api/channels/#{channel_1.id}/notifications-settings/me",+ params: {+ notifications_settings: {+ muted: true,+ foo: 1,+ },+ }++ expect(response.status).to eq(200)+ end+ end++ context "when category channel has valid params" do+ fab!(:channel_1) { Fabricate(:category_channel) }++ before do+ channel_1.add(current_user)+ sign_in(current_user)+ end++ it "updates the notifications settings" do+ put "/chat/api/channels/#{channel_1.id}/notifications-settings/me",+ params: {+ notifications_settings: {+ muted: true,+ desktop_notification_level: "always",+ mobile_notification_level: "never",+ },+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body["membership"]).to match_response_schema(+ "user_chat_channel_membership",+ )++ membership = channel_1.membership_for(current_user)++ expect(membership.muted).to eq(true)+ expect(membership.desktop_notification_level).to eq("always")+ expect(membership.mobile_notification_level).to eq("never")+ end+ end++ context "when membership doesn’t exist" do+ fab!(:channel_1) { Fabricate(:category_channel) }++ before { sign_in(current_user) }++ it "raises a 404" do+ put "/chat/api/channels/#{channel_1.id}/notifications-settings/me",+ params: {+ notifications_settings: {+ muted: true,+ },+ }++ expect(response.status).to eq(404)+ end+ end++ context "when direct message channel has invalid params" do+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user]) }++ before { sign_in(current_user) }++ it "doesn’t use invalid params" do+ UserChatChannelMembership.any_instance.expects(:update!).with({ "muted" => "true" }).once++ put "/chat/api/channels/#{dm_channel_1.id}/notifications-settings/me",+ params: {+ notifications_settings: {+ muted: true,+ foo: 1,+ },+ }++ expect(response.status).to eq(200)+ end+ end++ context "when direct message channel has valid params" do+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user]) }++ before { sign_in(current_user) }++ it "updates the notifications settings" do+ put "/chat/api/channels/#{dm_channel_1.id}/notifications-settings/me",+ params: {+ notifications_settings: {+ muted: true,+ desktop_notification_level: "always",+ mobile_notification_level: "never",+ },+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body["membership"]).to match_response_schema(+ "user_chat_channel_membership",+ )++ membership = dm_channel_1.membership_for(current_user)++ expect(membership.muted).to eq(true)+ expect(membership.desktop_notification_level).to eq("always")+ expect(membership.mobile_notification_level).to eq("never")+ end+ end+ end+enddiff --git a/plugins/chat/spec/requests/api/chat_channels_moves_controller_spec.rb b/plugins/chat/spec/requests/api/chat_channels_moves_controller_spec.rbnew file mode 100644index 00000000000..767b55e8220--- /dev/null+++ b/plugins/chat/spec/requests/api/chat_channels_moves_controller_spec.rb@@ -0,0 +1,123 @@+# frozen_string_literal: true++require "rails_helper"++RSpec.describe Chat::Api::ChatChannelsMessagesMovesController do+ fab!(:channel) { Fabricate(:category_channel) }++ 70.times { |n| fab!("message_#{n}") { Fabricate(:chat_message, chat_channel: channel) } }++ before do+ SiteSetting.chat_enabled = true+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]+ end++ def flag_message(message, flagger, flag_type: ReviewableScore.types[:off_topic])+ Chat::ChatReviewQueue.new.flag_message(message, Guardian.new(flagger), flag_type)[:reviewable]+ end++ describe "#create" do+ fab!(:message_to_move_1) do+ Fabricate(:chat_message, chat_channel: channel, created_at: 2.minutes.ago)+ end+ fab!(:message_to_move_2) do+ Fabricate(:chat_message, chat_channel: channel, created_at: 1.minute.ago)+ end+ fab!(:destination_channel) { Fabricate(:category_channel) }+ let(:message_ids) { [message_to_move_1.id, message_to_move_2.id] }++ context "when the user is not admin" do+ before { sign_in(Fabricate(:user)) }++ it "returns an access denied error" do+ post "/chat/api/channels/#{channel.id}/messages/moves",+ params: {+ move: {+ destination_channel_id: destination_channel.id,+ message_ids: message_ids,+ },+ }+ expect(response.status).to eq(403)+ end+ end++ context "when the user is admin" do+ fab!(:current_user) { Fabricate(:admin) }++ before { sign_in(current_user) }++ it "shows an error if the source channel is not found" do+ channel.trash!+ post "/chat/api/channels/#{channel.id}/messages/moves",+ params: {+ move: {+ destination_channel_id: destination_channel.id,+ message_ids: message_ids,+ },+ }+ expect(response.status).to eq(404)+ end++ it "shows an error if the destination channel is not found" do+ destination_channel.trash!+ post "/chat/api/channels/#{channel.id}/messages/moves",+ params: {+ move: {+ destination_channel_id: destination_channel.id,+ message_ids: message_ids,+ },+ }+ expect(response.status).to eq(404)+ end++ it "successfully moves the messages to the new channel" do+ post "/chat/api/channels/#{channel.id}/messages/moves",+ params: {+ move: {+ destination_channel_id: destination_channel.id,+ message_ids: message_ids,+ },+ }+ expect(response.status).to eq(200)+ latest_destination_messages = destination_channel.chat_messages.last(2)+ expect(latest_destination_messages.first.message).to eq(message_to_move_1.message)+ expect(latest_destination_messages.second.message).to eq(message_to_move_2.message)+ expect(message_to_move_1.reload.deleted_at).not_to eq(nil)+ expect(message_to_move_2.reload.deleted_at).not_to eq(nil)+ end++ it "shows an error message when the destination channel is invalid" do+ invalid_channel = Fabricate(:direct_message_channel, users: [current_user])++ post "/chat/api/channels/#{channel.id}/messages/moves",+ params: {+ move: {+ destination_channel_id: invalid_channel.id,+ message_ids: message_ids,+ },+ }+ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to include(+ I18n.t("chat.errors.message_move_invalid_channel"),+ )+ end++ it "shows an error when none of the messages can be found" do+ destroyed_message = Fabricate(:chat_message, chat_channel: channel)+ destroyed_message.trash!++ post "/chat/api/channels/#{channel.id}/messages/moves",+ params: {+ move: {+ destination_channel_id: destination_channel.id,+ message_ids: [destroyed_message],+ },+ }+ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"]).to include(+ I18n.t("chat.errors.message_move_no_messages_found"),+ )+ end+ end+ end+enddiff --git a/plugins/chat/spec/requests/api/chat_channels_status_controller_spec.rb b/plugins/chat/spec/requests/api/chat_channels_status_controller_spec.rbnew file mode 100644index 00000000000..942d063a7ed--- /dev/null+++ b/plugins/chat/spec/requests/api/chat_channels_status_controller_spec.rb@@ -0,0 +1,89 @@+# frozen_string_literal: true++require "rails_helper"++RSpec.describe Chat::Api::ChatChannelsStatusController do+ fab!(:channel_1) { Fabricate(:category_channel, status: :open) }++ before do+ SiteSetting.chat_enabled = true+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]+ SiteSetting.chat_duplicate_message_sensitivity = 0+ end++ def status(status)+ { status: status }+ end++ describe "#update" do+ context "when user is not staff" do+ before { sign_in(Fabricate(:user)) }++ it "returns an error" do+ put "/chat/api/channels/#{channel_1.id}/status", params: status("closed")++ expect(response.status).to eq(403)+ end+ end++ context "when user is admin" do+ before { sign_in(Fabricate(:admin)) }++ context "when channel doesn’t exist" do+ before { channel_1.destroy! }++ it "returns an error" do+ put "/chat/api/channels/#{channel_1.id}/status", params: status("closed")++ expect(response.status).to eq(404)+ end+ end++ context "when channel is in read-only" do+ before { channel_1.update!(status: "read_only") }++ it "returns an error" do+ put "/chat/api/channels/#{channel_1.id}/status", params: status("closed")++ expect(response.status).to eq(403)+ end+ end++ context "when channel is archived" do+ before { channel_1.update!(status: "archived") }++ it "returns an error" do+ put "/chat/api/channels/#{channel_1.id}/status", params: status("closed")++ expect(response.status).to eq(403)+ end+ end++ context "when changing from open to closed" do+ it "changes the status" do+ expect { put "/chat/api/channels/#{channel_1.id}/status", params: status("closed") }.to change {+ channel_1.reload.status+ }.to("closed").from("open")++ expect(response.status).to eq(200)+ channel = response.parsed_body["channel"]+ expect(channel["id"]).to eq(channel_1.id)+ end+ end++ context "when changing from closed to open" do+ before { channel_1.update!(status: "closed") }++ it "changes the status" do+ expect { put "/chat/api/channels/#{channel_1.id}/status", params: status("open") }.to change {+ channel_1.reload.status+ }.to("open").from("closed")++ expect(response.status).to eq(200)+ channel = response.parsed_body["channel"]+ expect(channel["id"]).to eq(channel_1.id)+ end+ end+ end+ end+enddiff --git a/plugins/chat/spec/requests/api/chat_chatables_controller_spec.rb b/plugins/chat/spec/requests/api/chat_chatables_controller_spec.rbnew file mode 100644index 00000000000..a0ba6ee4ffd--- /dev/null+++ b/plugins/chat/spec/requests/api/chat_chatables_controller_spec.rb@@ -0,0 +1,201 @@+# frozen_string_literal: true++require "rails_helper"++RSpec.describe Chat::Api::ChatChatablesController do+ before do+ SiteSetting.chat_enabled = true+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]+ end++ describe "#index" do+ fab!(:user) { Fabricate(:user, username: "johndoe", name: "John Doe") }++ describe "without chat permissions" do+ it "errors errors for anon" do+ get "/chat/api/chatables", params: { filter: "so" }+ expect(response.status).to eq(403)+ end++ it "errors when user cannot chat" do+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:staff]+ sign_in(user)+ get "/chat/api/chatables", params: { filter: "so" }+ expect(response.status).to eq(403)+ end+ end++ describe "with chat permissions" do+ fab!(:other_user) { Fabricate(:user, username: "janemay", name: "Jane May") }+ fab!(:admin) { Fabricate(:admin, username: "andyjones", name: "Andy Jones") }+ fab!(:category) { Fabricate(:category) }+ fab!(:chat_channel) { Fabricate(:category_channel, chatable: category) }+ fab!(:dm_chat_channel) { Fabricate(:direct_message_channel, users: [user, admin]) }++ before do+ chat_channel.update(name: "something")+ sign_in(user)+ end++ it "returns the correct channels with filter 'so'" do+ get "/chat/api/chatables", params: { filter: "so" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["public_channels"][0]["id"]).to eq(chat_channel.id)+ expect(response.parsed_body["direct_message_channels"].count).to eq(0)+ expect(response.parsed_body["users"].count).to eq(0)+ end++ it "returns the correct channels with filter 'something'" do+ get "/chat/api/chatables", params: { filter: "something" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["public_channels"][0]["id"]).to eq(chat_channel.id)+ expect(response.parsed_body["direct_message_channels"].count).to eq(0)+ expect(response.parsed_body["users"].count).to eq(0)+ end++ it "returns the correct channels with filter 'andyjones'" do+ get "/chat/api/chatables", params: { filter: "andyjones" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["public_channels"].count).to eq(0)+ expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_chat_channel.id)+ expect(response.parsed_body["users"].count).to eq(0)+ end++ it "returns the current user inside the users array if their username matches the filter too" do+ user.update!(username: "andysmith")+ get "/chat/api/chatables", params: { filter: "andy" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_chat_channel.id)+ expect(response.parsed_body["users"].map { |u| u["id"] }).to match_array([user.id])+ end++ it "returns no channels with a whacky filter" do+ get "/chat/api/chatables", params: { filter: "hello good sir" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["public_channels"].count).to eq(0)+ expect(response.parsed_body["direct_message_channels"].count).to eq(0)+ expect(response.parsed_body["users"].count).to eq(0)+ end++ it "only returns open channels" do+ chat_channel.update(status: ChatChannel.statuses[:closed])+ get "/chat/api/chatables", params: { filter: "so" }+ expect(response.parsed_body["public_channels"].count).to eq(0)++ chat_channel.update(status: ChatChannel.statuses[:read_only])+ get "/chat/api/chatables", params: { filter: "so" }+ expect(response.parsed_body["public_channels"].count).to eq(0)++ chat_channel.update(status: ChatChannel.statuses[:archived])+ get "/chat/api/chatables", params: { filter: "so" }+ expect(response.parsed_body["public_channels"].count).to eq(0)++ # Now set status to open and the channel is there!+ chat_channel.update(status: ChatChannel.statuses[:open])+ get "/chat/api/chatables", params: { filter: "so" }+ expect(response.parsed_body["public_channels"][0]["id"]).to eq(chat_channel.id)+ end++ it "only finds users by username_lower if not enable_names" do+ SiteSetting.enable_names = false+ get "/chat/api/chatables", params: { filter: "Andy J" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["public_channels"].count).to eq(0)+ expect(response.parsed_body["direct_message_channels"].count).to eq(0)++ get "/chat/api/chatables", params: { filter: "andyjones" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["public_channels"].count).to eq(0)+ expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_chat_channel.id)+ end++ it "only finds users by username if prioritize_username_in_ux" do+ SiteSetting.prioritize_username_in_ux = true+ get "/chat/api/chatables", params: { filter: "Andy J" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["public_channels"].count).to eq(0)+ expect(response.parsed_body["direct_message_channels"].count).to eq(0)++ get "/chat/api/chatables", params: { filter: "andyjones" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["public_channels"].count).to eq(0)+ expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_chat_channel.id)+ end++ it "can find users by name or username if not prioritize_username_in_ux and enable_names" do+ SiteSetting.prioritize_username_in_ux = false+ SiteSetting.enable_names = true+ get "/chat/api/chatables", params: { filter: "Andy J" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["public_channels"].count).to eq(0)+ expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_chat_channel.id)++ get "/chat/api/chatables", params: { filter: "andyjones" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["public_channels"].count).to eq(0)+ expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_chat_channel.id)+ end++ it "does not return DM channels for users who do not have chat enabled" do+ admin.user_option.update!(chat_enabled: false)+ get "/chat/api/chatables", params: { filter: "andyjones" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["direct_message_channels"].count).to eq(0)+ end++ it "does not return DM channels for users who are not in the chat allowed group" do+ group = Fabricate(:group, name: "chatpeeps")+ SiteSetting.chat_allowed_groups = group.id+ GroupUser.create(user: user, group: group)+ dm_chat_channel_2 = Fabricate(:direct_message_channel, users: [user, other_user])++ get "/chat/api/chatables", params: { filter: "janemay" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["direct_message_channels"].count).to eq(0)++ GroupUser.create(user: other_user, group: group)+ get "/chat/api/chatables", params: { filter: "janemay" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_chat_channel_2.id)+ end++ it "returns DM channels for staff users even if they are not in chat_allowed_groups" do+ group = Fabricate(:group, name: "chatpeeps")+ SiteSetting.chat_allowed_groups = group.id+ GroupUser.create(user: user, group: group)++ get "/chat/api/chatables", params: { filter: "andyjones" }+ expect(response.status).to eq(200)+ expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_chat_channel.id)+ end++ it "returns followed channels" do+ Fabricate(+ :user_chat_channel_membership,+ user: user,+ chat_channel: chat_channel,+ following: true,+ )++ get "/chat/api/chatables", params: { filter: chat_channel.name }++ expect(response.status).to eq(200)+ expect(response.parsed_body["public_channels"][0]["id"]).to eq(chat_channel.id)+ end++ it "returns not followed channels" do+ Fabricate(+ :user_chat_channel_membership,+ user: user,+ chat_channel: chat_channel,+ following: false,+ )++ get "/chat/api/chatables", params: { filter: chat_channel.name }++ expect(response.status).to eq(200)+ expect(response.parsed_body["public_channels"][0]["id"]).to eq(chat_channel.id)+ end+ end+ end+enddiff --git a/plugins/chat/spec/requests/api/chat_current_user_channels_spec.rb b/plugins/chat/spec/requests/api/chat_current_user_channels_spec.rbnew file mode 100644index 00000000000..6b7a21bb264--- /dev/null+++ b/plugins/chat/spec/requests/api/chat_current_user_channels_spec.rb@@ -0,0 +1,134 @@+# frozen_string_literal: true++require "rails_helper"++describe Chat::Api::ChatCurrentUserChannelsController do+ fab!(:current_user) { Fabricate(:user) }++ before do+ SiteSetting.chat_enabled = true+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]+ end++ describe "#index" do+ context "as anonymous user" do+ it "returns an error" do+ get "/chat/api/channels/me"+ expect(response.status).to eq(403)+ end+ end++ context "as disallowed user" do+ before do+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:staff]+ sign_in(Fabricate(:user))+ end++ it "returns an error" do+ get "/chat/api/channels/me"++ expect(response.status).to eq(403)+ end+ end++ context "as allowed user" do+ fab!(:current_user) { Fabricate(:user) }++ before { sign_in(current_user) }++ it "returns public channels with memberships" do+ channel = Fabricate(:category_channel)+ channel.add(current_user)+ get "/chat/api/channels/me"++ expect(response.parsed_body["public_channels"][0]["id"]).to eq(channel.id)+ end++ it "returns limited access public channels with memberships" do+ group = Fabricate(:group)+ channel = Fabricate(:private_category_channel, group: group)+ group.add(current_user)+ channel.add(current_user)+ get "/chat/api/channels/me"++ expect(response.parsed_body["public_channels"][0]["id"]).to eq(channel.id)+ end++ it "doesn’t return unaccessible private channels" do+ group = Fabricate(:group)+ channel = Fabricate(:private_category_channel, group: group)+ channel.add(current_user) # TODO: we should error here+ get "/chat/api/channels/me"++ expect(response.parsed_body["public_channels"]).to be_blank+ end++ it "returns dm channels you are part of" do+ dm_channel = Fabricate(:direct_message_channel, users: [current_user])+ get "/chat/api/channels/me"++ expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_channel.id)+ end++ it "doesn’t return dm channels from other users" do+ Fabricate(:direct_message_channel)+ get "/chat/api/channels/me"++ expect(response.parsed_body["direct_message_channels"]).to be_blank+ end++ it "includes message bus ids" do+ Fabricate(:direct_message_channel, users: [current_user])+ channel = Fabricate(:category_channel)+ channel.add(current_user)+ get "/chat/api/channels/me"++ expect(response.status).to eq(200)++ response.parsed_body["meta"]["message_bus_last_ids"].tap do |ids|+ expect(ids["channel_metadata"]).not_to eq(nil)+ expect(ids["channel_edits"]).not_to eq(nil)+ expect(ids["channel_status"]).not_to eq(nil)+ expect(ids["new_channel"]).not_to eq(nil)+ end++ response.parsed_body["public_channels"][0]["meta"]["message_bus_last_ids"].tap do |ids|+ expect(ids["new_messages"]).not_to eq(nil)+ expect(ids["new_mentions"]).not_to eq(nil)+ end++ response.parsed_body["direct_message_channels"][0]["meta"][+ "message_bus_last_ids"+ ].tap do |ids|+ expect(ids["new_messages"]).not_to eq(nil)+ expect(ids["new_mentions"]).not_to eq(nil)+ end+ end++ context "when the chatable of a channel is destroyed" do+ context "when the channel is a category" do+ it "doesn’t return the channel" do+ channel = Fabricate(:category_channel)+ channel.add(current_user)+ channel.chatable.destroy!+ get "/chat/api/channels/me"++ expect(response.status).to eq(200)+ expect(response.parsed_body["public_channels"]).to be_blank+ end+ end++ context "when the channel is a direct message" do+ it "doesn’t return the channel" do+ channel = Fabricate(:direct_message_channel, users: [current_user])+ channel.chatable.destroy!+ get "/chat/api/channels/me"++ expect(response.status).to eq(200)+ expect(response.parsed_body["direct_message_channels"]).to be_blank+ end+ end+ end+ end+ end+enddiff --git a/plugins/chat/spec/requests/api/hints_controller_spec.rb b/plugins/chat/spec/requests/api/hints_controller_spec.rbindex 1ca4d0b10f6..c5fa42df8d0 100644--- a/plugins/chat/spec/requests/api/hints_controller_spec.rb+++ b/plugins/chat/spec/requests/api/hints_controller_spec.rb@@ -4,7 +4,7 @@ RSpec.describe Chat::Api::HintsController dodescribe "#check_group_mentions" docontext "for anons" doit "returns a 404" do- get "/chat/api/mentions/groups.json", params: { mentions: %w[group1] }+ get "/chat/api/mentions/groups", params: { mentions: %w[group1] }expect(response.status).to eq(403)end@@ -12,21 +12,26 @@ RSpec.describe Chat::Api::HintsController docontext "for logged in users" dofab!(:user) { Fabricate(:user) }- fab!(:mentionable_group) { Fabricate(:group, mentionable_level: Group::ALIAS_LEVELS[:everyone]) }- fab!(:admin_mentionable_group) { Fabricate(:group, mentionable_level: Group::ALIAS_LEVELS[:only_admins]) }+ fab!(:mentionable_group) do+ Fabricate(:group, mentionable_level: Group::ALIAS_LEVELS[:everyone])+ end+ fab!(:admin_mentionable_group) do+ Fabricate(:group, mentionable_level: Group::ALIAS_LEVELS[:only_admins])+ endbefore { sign_in(user) }it "returns a 400 when no mentions are given" do- get "/chat/api/mentions/groups.json"+ get "/chat/api/mentions/groups"expect(response.status).to eq(400)endit "returns a warning when a group is not mentionable" do- get "/chat/api/mentions/groups.json", params: {- mentions: [mentionable_group.name, admin_mentionable_group.name]- }+ get "/chat/api/mentions/groups",+ params: {+ mentions: [mentionable_group.name, admin_mentionable_group.name],+ }expect(response.status).to eq(200)expect(response.parsed_body["unreachable"]).to contain_exactly(admin_mentionable_group.name)@@ -34,9 +39,10 @@ RSpec.describe Chat::Api::HintsController doit "returns no warning if the user is allowed to mention" douser.update!(admin: true)- get "/chat/api/mentions/groups.json", params: {- mentions: [mentionable_group.name, admin_mentionable_group.name]- }+ get "/chat/api/mentions/groups",+ params: {+ mentions: [mentionable_group.name, admin_mentionable_group.name],+ }expect(response.status).to eq(200)expect(response.parsed_body["unreachable"]).to be_empty@@ -49,18 +55,19 @@ RSpec.describe Chat::Api::HintsController domentionable_group.add(user_2)SiteSetting.max_users_notified_per_group_mention = 1- get "/chat/api/mentions/groups.json", params: {- mentions: [mentionable_group.name, admin_mentionable_group.name]- }+ get "/chat/api/mentions/groups",+ params: {+ mentions: [mentionable_group.name, admin_mentionable_group.name],+ }expect(response.status).to eq(200)- expect(response.parsed_body["over_members_limit"]).to contain_exactly(mentionable_group.name)+ expect(response.parsed_body["over_members_limit"]).to contain_exactly(+ mentionable_group.name,+ )endit "returns no warnings when the group doesn't exist" do- get "/chat/api/mentions/groups.json", params: {- mentions: ["a_fake_group"]- }+ get "/chat/api/mentions/groups", params: { mentions: ["a_fake_group"] }expect(response.status).to eq(200)expect(response.parsed_body["unreachable"]).to be_empty@@ -68,14 +75,14 @@ RSpec.describe Chat::Api::HintsController doendit "doesn't leak groups that are not visible" do- invisible_group = Fabricate(:group,- visibility_level: Group.visibility_levels[:staff],- mentionable_level: Group::ALIAS_LEVELS[:only_admins]- )+ invisible_group =+ Fabricate(+ :group,+ visibility_level: Group.visibility_levels[:staff],+ mentionable_level: Group::ALIAS_LEVELS[:only_admins],+ )- get "/chat/api/mentions/groups.json", params: {- mentions: [invisible_group.name]- }+ get "/chat/api/mentions/groups", params: { mentions: [invisible_group.name] }expect(response.status).to eq(200)expect(response.parsed_body["unreachable"]).to be_empty@@ -86,15 +93,9 @@ RSpec.describe Chat::Api::HintsController doit "triggers a rate-limit on too many requests" doRateLimiter.enable- 5.times do- get "/chat/api/mentions/groups.json", params: {- mentions: [mentionable_group.name]- }- end+ 5.times { get "/chat/api/mentions/groups", params: { mentions: [mentionable_group.name] } }- get "/chat/api/mentions/groups.json", params: {- mentions: [mentionable_group.name]- }+ get "/chat/api/mentions/groups", params: { mentions: [mentionable_group.name] }expect(response.status).to eq(429)enddiff --git a/plugins/chat/spec/requests/chat_channel_controller_spec.rb b/plugins/chat/spec/requests/chat_channel_controller_spec.rbdeleted file mode 100644index 7ea20a6ed72..00000000000--- a/plugins/chat/spec/requests/chat_channel_controller_spec.rb+++ /dev/null@@ -1,849 +0,0 @@-# frozen_string_literal: true--require "rails_helper"--RSpec.describe Chat::ChatChannelsController do- fab!(:user) { Fabricate(:user, username: "johndoe", name: "John Doe") }- fab!(:other_user) { Fabricate(:user, username: "janemay", name: "Jane May") }- fab!(:admin) { Fabricate(:admin, username: "andyjones", name: "Andy Jones") }- fab!(:category) { Fabricate(:category) }- fab!(:chat_channel) { Fabricate(:category_channel, chatable: category) }- fab!(:dm_chat_channel) { Fabricate(:direct_message_channel, users: [user, admin]) }-- before do- SiteSetting.chat_enabled = true- SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]- SiteSetting.chat_duplicate_message_sensitivity = 0- end-- describe "#index" do- fab!(:private_group) { Fabricate(:group) }- fab!(:user_with_private_access) { Fabricate(:user, group_ids: [private_group.id]) }-- fab!(:private_category) { Fabricate(:private_category, group: private_group) }- fab!(:private_category_cc) { Fabricate(:category_channel, chatable: private_category) }-- describe "with memberships for all channels" do- before do- ChatChannel.all.each do |cc|- model =- (- if cc.direct_message_channel?- :user_chat_channel_membership_for_dm- else- :user_chat_channel_membership- end- )-- Fabricate(model, chat_channel: cc, user: user)- Fabricate(model, chat_channel: cc, user: user_with_private_access)- Fabricate(model, chat_channel: cc, user: admin)- end- end-- it "errors for user that is not allowed to chat" do- sign_in(user)- SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:staff]-- get "/chat/chat_channels.json"-- expect(response.status).to eq(403)- end-- it "returns public channels to only-public user" do- sign_in(user)- get "/chat/chat_channels.json"-- expect(response.status).to eq(200)- expect(- response.parsed_body["public_channels"].map { |channel| channel["id"] },- ).to match_array([chat_channel.id])- end-- it "returns channels visible to user with private access" do- sign_in(user_with_private_access)- get "/chat/chat_channels.json"-- expect(response.status).to eq(200)- expect(- response.parsed_body["public_channels"].map { |channel| channel["id"] },- ).to match_array([chat_channel.id, private_category_cc.id])- end-- it "returns all channels for admin" do- sign_in(admin)- get "/chat/chat_channels.json"-- expect(response.status).to eq(200)- expect(- response.parsed_body["public_channels"].map { |channel| channel["id"] },- ).to match_array([chat_channel.id, private_category_cc.id])- end-- it "doesn't error when a chat channel's chatable is destroyed" do- sign_in(user_with_private_access)- private_category.destroy!-- get "/chat/chat_channels.json"- expect(response.status).to eq(200)- end-- it "serializes unread_mentions properly" do- sign_in(admin)- Jobs.run_immediately!- Chat::ChatMessageCreator.create(- chat_channel: chat_channel,- user: user,- content: "Hi @#{admin.username}",- )- get "/chat/chat_channels.json"- cc = response.parsed_body["public_channels"].detect { |c| c["id"] == chat_channel.id }- expect(cc["current_user_membership"]["unread_mentions"]).to eq(1)- end-- it "returns the last message bus ids for various message bus channels scoped to this channel id" do- sign_in(admin)- get "/chat/chat_channels.json"- expect(response.status).to eq(200)-- expect(response.parsed_body["message_bus_last_ids"]["channel_metadata"]).not_to eq(nil)- expect(response.parsed_body["message_bus_last_ids"]["channel_edits"]).not_to eq(nil)- expect(response.parsed_body["message_bus_last_ids"]["channel_status"]).not_to eq(nil)- expect(response.parsed_body["message_bus_last_ids"]["new_channel"]).not_to eq(nil)-- first_channel = response.parsed_body["public_channels"][0]- expect(first_channel["message_bus_last_ids"]["new_messages"]).not_to eq(nil)- expect(first_channel["message_bus_last_ids"]["new_mentions"]).not_to eq(nil)- end-- describe "direct messages" do- fab!(:user1) { Fabricate(:user) }- fab!(:user2) { Fabricate(:user) }- fab!(:user3) { Fabricate(:user) }-- before do- Group.refresh_automatic_groups!- @dm1 =- Chat::DirectMessageChannelCreator.create!(- acting_user: user1,- target_users: [user1, user2],- )- @dm2 =- Chat::DirectMessageChannelCreator.create!(- acting_user: user1,- target_users: [user1, user3],- )- @dm3 =- Chat::DirectMessageChannelCreator.create!(- acting_user: user1,- target_users: [user1, user2, user3],- )- @dm4 =- Chat::DirectMessageChannelCreator.create!(- acting_user: user1,- target_users: [user2, user3],- )- end-- it "returns correct DMs for creator" do- sign_in(user1)-- get "/chat/chat_channels.json"- expect(- response.parsed_body["direct_message_channels"].map { |c| c["id"] },- ).to match_array([@dm1.id, @dm2.id, @dm3.id])- end-- it "returns correct DMs when not following" do- sign_in(user2)-- get "/chat/chat_channels.json"- expect(- response.parsed_body["direct_message_channels"].map { |c| c["id"] },- ).to match_array([])- end-- it "returns correct DMs when following" do- user3- .user_chat_channel_memberships- .where(chat_channel_id: @dm3.id)- .update!(following: true)-- sign_in(user3)-- get "/chat/chat_channels.json"- dm3_response = response.parsed_body- expect(dm3_response["direct_message_channels"].map { |c| c["id"] }).to match_array(- [@dm3.id],- )- end-- it "correctly set unread_count for DMs for creator" do- sign_in(user1)- Chat::ChatMessageCreator.create(- chat_channel: @dm2,- user: user1,- content: "What's going on?!",- )- get "/chat/chat_channels.json"- dm2_response =- response.parsed_body["direct_message_channels"].detect { |c| c["id"] == @dm2.id }- expect(dm2_response["current_user_membership"]["unread_count"]).to eq(0)- end-- it "correctly set membership for DMs when user is not following" do- sign_in(user2)- Chat::ChatMessageCreator.create(- chat_channel: @dm2,- user: user1,- content: "What's going on?!",- )- get "/chat/chat_channels.json"- dm2_channel =- response.parsed_body["direct_message_channels"].detect { |c| c["id"] == @dm2.id }- expect(dm2_channel).to be_nil- end-- it "correctly set unread_count for DMs when user is following" do- user3- .user_chat_channel_memberships- .where(chat_channel_id: @dm2.id)- .update!(following: true)-- sign_in(user3)- Chat::ChatMessageCreator.create(- chat_channel: @dm2,- user: user1,- content: "What's going on?!",- )- get "/chat/chat_channels.json"- dm3_response =- response.parsed_body["direct_message_channels"].detect { |c| c["id"] == @dm2.id }- expect(dm3_response["current_user_membership"]["unread_count"]).to eq(1)- end- end- end- end-- describe "#follow" do- it "creates a user_chat_channel_membership record if one doesn't exist" do- sign_in(user)- expect { post "/chat/chat_channels/#{chat_channel.id}/follow.json" }.to change {- UserChatChannelMembership.where(user_id: user.id, following: true).count- }.by(1)- expect(response.status).to eq(200)- end-- it "updates 'following' to true for existing record" do- sign_in(user)- membership_record =- UserChatChannelMembership.create!(- chat_channel_id: chat_channel.id,- user_id: user.id,- following: false,- )-- expect { post "/chat/chat_channels/#{chat_channel.id}/follow.json" }.to change {- membership_record.reload.following- }.to(true).from(false)- expect(response.status).to eq(200)- expect(response.parsed_body["current_user_membership"]["following"]).to eq(true)- expect(response.parsed_body["current_user_membership"]["chat_channel_id"]).to eq(- chat_channel.id,- )- end- end-- describe "#unfollow" do- it "updates 'following' to false for existing record" do- sign_in(user)- membership_record =- UserChatChannelMembership.create!(- chat_channel_id: chat_channel.id,- user_id: user.id,- following: true,- )-- expect { post "/chat/chat_channels/#{chat_channel.id}/unfollow.json" }.to change {- membership_record.reload.following- }.to(false).from(true)- expect(response.status).to eq(200)- expect(response.parsed_body["current_user_membership"]["following"]).to eq(false)- expect(response.parsed_body["current_user_membership"]["chat_channel_id"]).to eq(- chat_channel.id,- )- end-- it "allows to unfollow a direct_message_channel" do- sign_in(user)- membership_record =- UserChatChannelMembership.create!(- chat_channel_id: dm_chat_channel.id,- user_id: user.id,- following: true,- desktop_notification_level: 2,- mobile_notification_level: 2,- )-- post "/chat/chat_channels/#{dm_chat_channel.id}/unfollow.json"- expect(response.status).to eq(200)- expect(membership_record.reload.following).to eq(false)- end- end-- describe "#create" do- fab!(:category2) { Fabricate(:category) }-- it "errors for non-staff" do- sign_in(user)- put "/chat/chat_channels.json", params: { id: category2.id, name: "hi" }- expect(response.status).to eq(403)- end-- it "errors when chatable doesn't exist" do- sign_in(admin)- put "/chat/chat_channels.json", params: { id: Category.last.id + 1, name: "hi" }- expect(response.status).to eq(404)- end-- it "errors when the name is over SiteSetting.max_topic_title_length" do- sign_in(admin)- SiteSetting.max_topic_title_length = 10- put "/chat/chat_channels.json",- params: {- id: category2.id,- name: "Hi, this is over 10 characters",- }- expect(response.status).to eq(400)- end-- it "errors when channel for category and same name already exists" do- sign_in(admin)- name = "beep boop hi"- category2.create_chat_channel!(name: name)-- put "/chat/chat_channels.json", params: { id: category2.id, name: name }- expect(response.status).to eq(400)- end-- it "creates a channel for category and if name is unique" do- sign_in(admin)- category2.create_chat_channel!(name: "this is a name")-- expect {- put "/chat/chat_channels.json", params: { id: category2.id, name: "Different name!" }- }.to change { ChatChannel.where(chatable: category2).count }.by(1)- expect(response.status).to eq(200)- end-- it "creates a user_chat_channel_membership when the channel is created" do- sign_in(admin)- expect {- put "/chat/chat_channels.json", params: { id: category2.id, name: "hi hi" }- }.to change { UserChatChannelMembership.where(user: admin).count }.by(1)- expect(response.status).to eq(200)- end- end-- describe "#edit" do- it "errors for non-staff" do- sign_in(user)- post "/chat/chat_channels/#{chat_channel.id}.json", params: { name: "hello" }- expect(response.status).to eq(403)- end-- it "returns a 404 when chat_channel doesn't exist" do- sign_in(admin)- chat_channel.destroy!- post "/chat/chat_channels/#{chat_channel.id}.json", params: { name: "hello" }- expect(response.status).to eq(404)- end-- it "updates name correctly and leaves description alone" do- sign_in(admin)- new_name = "newwwwwwwww name"- description = "this is something"- chat_channel.update(description: description)- post "/chat/chat_channels/#{chat_channel.id}.json", params: { name: new_name }- expect(response.status).to eq(200)- expect(chat_channel.reload.name).to eq(new_name)- expect(chat_channel.description).to eq(description)- end-- it "updates name correctly and leaves description alone" do- sign_in(admin)- name = "beep boop"- new_description = "this is something"- chat_channel.update(name: name)- post "/chat/chat_channels/#{chat_channel.id}.json", params: { description: new_description }- expect(response.status).to eq(200)- expect(chat_channel.reload.name).to eq(name)- expect(chat_channel.description).to eq(new_description)- end-- it "updates name and description together" do- sign_in(admin)- new_name = "beep boop"- new_description = "this is something"- post "/chat/chat_channels/#{chat_channel.id}.json",- params: {- name: new_name,- description: new_description,- }- expect(response.status).to eq(200)- expect(chat_channel.reload.name).to eq(new_name)- expect(chat_channel.description).to eq(new_description)- end- end-- describe "#search" do- describe "without chat permissions" do- it "errors errors for anon" do- get "/chat/chat_channels/search.json", params: { filter: "so" }- expect(response.status).to eq(403)- end-- it "errors when user cannot chat" do- SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:staff]- sign_in(user)- get "/chat/chat_channels/search.json", params: { filter: "so" }- expect(response.status).to eq(403)- end- end-- describe "with chat permissions" do- before do- sign_in(user)- chat_channel.update(name: "something")- end-- it "returns the correct channels with filter 'so'" do- get "/chat/chat_channels/search.json", params: { filter: "so" }- expect(response.status).to eq(200)- expect(response.parsed_body["public_channels"][0]["id"]).to eq(chat_channel.id)- expect(response.parsed_body["direct_message_channels"].count).to eq(0)- expect(response.parsed_body["users"].count).to eq(0)- end-- it "returns the correct channels with filter 'something'" do- get "/chat/chat_channels/search.json", params: { filter: "something" }- expect(response.status).to eq(200)- expect(response.parsed_body["public_channels"][0]["id"]).to eq(chat_channel.id)- expect(response.parsed_body["direct_message_channels"].count).to eq(0)- expect(response.parsed_body["users"].count).to eq(0)- end-- it "returns the correct channels with filter 'andyjones'" do- get "/chat/chat_channels/search.json", params: { filter: "andyjones" }- expect(response.status).to eq(200)- expect(response.parsed_body["public_channels"].count).to eq(0)- expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_chat_channel.id)- expect(response.parsed_body["users"].count).to eq(0)- end-- it "returns the current user inside the users array if their username matches the filter too" do- user.update(username: "andysmith")- get "/chat/chat_channels/search.json", params: { filter: "andy" }- expect(response.status).to eq(200)- expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_chat_channel.id)- expect(response.parsed_body["users"].map { |u| u["id"] }).to match_array([user.id])- end-- it "returns no channels with a whacky filter" do- get "/chat/chat_channels/search.json", params: { filter: "hello good sir" }- expect(response.status).to eq(200)- expect(response.parsed_body["public_channels"].count).to eq(0)- expect(response.parsed_body["direct_message_channels"].count).to eq(0)- expect(response.parsed_body["users"].count).to eq(0)- end-- it "only returns open channels" do- chat_channel.update(status: ChatChannel.statuses[:closed])- get "/chat/chat_channels/search.json", params: { filter: "so" }- expect(response.parsed_body["public_channels"].count).to eq(0)-- chat_channel.update(status: ChatChannel.statuses[:read_only])- get "/chat/chat_channels/search.json", params: { filter: "so" }- expect(response.parsed_body["public_channels"].count).to eq(0)-- chat_channel.update(status: ChatChannel.statuses[:archived])- get "/chat/chat_channels/search.json", params: { filter: "so" }- expect(response.parsed_body["public_channels"].count).to eq(0)-- # Now set status to open and the channel is there!- chat_channel.update(status: ChatChannel.statuses[:open])- get "/chat/chat_channels/search.json", params: { filter: "so" }- expect(response.parsed_body["public_channels"][0]["id"]).to eq(chat_channel.id)- end-- it "only finds users by username_lower if not enable_names" do- SiteSetting.enable_names = false- get "/chat/chat_channels/search.json", params: { filter: "Andy J" }- expect(response.status).to eq(200)- expect(response.parsed_body["public_channels"].count).to eq(0)- expect(response.parsed_body["direct_message_channels"].count).to eq(0)-- get "/chat/chat_channels/search.json", params: { filter: "andyjones" }- expect(response.status).to eq(200)- expect(response.parsed_body["public_channels"].count).to eq(0)- expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_chat_channel.id)- end-- it "only finds users by username if prioritize_username_in_ux" do- SiteSetting.prioritize_username_in_ux = true- get "/chat/chat_channels/search.json", params: { filter: "Andy J" }- expect(response.status).to eq(200)- expect(response.parsed_body["public_channels"].count).to eq(0)- expect(response.parsed_body["direct_message_channels"].count).to eq(0)-- get "/chat/chat_channels/search.json", params: { filter: "andyjones" }- expect(response.status).to eq(200)- expect(response.parsed_body["public_channels"].count).to eq(0)- expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_chat_channel.id)- end-- it "can find users by name or username if not prioritize_username_in_ux and enable_names" do- SiteSetting.prioritize_username_in_ux = false- SiteSetting.enable_names = true- get "/chat/chat_channels/search.json", params: { filter: "Andy J" }- expect(response.status).to eq(200)- expect(response.parsed_body["public_channels"].count).to eq(0)- expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_chat_channel.id)-- get "/chat/chat_channels/search.json", params: { filter: "andyjones" }- expect(response.status).to eq(200)- expect(response.parsed_body["public_channels"].count).to eq(0)- expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_chat_channel.id)- end-- it "does not return DM channels for users who do not have chat enabled" do- admin.user_option.update!(chat_enabled: false)- get "/chat/chat_channels/search.json", params: { filter: "andyjones" }- expect(response.status).to eq(200)- expect(response.parsed_body["direct_message_channels"].count).to eq(0)- end-- it "does not return DM channels for users who are not in the chat allowed group" do- group = Fabricate(:group, name: "chatpeeps")- SiteSetting.chat_allowed_groups = group.id- GroupUser.create(user: user, group: group)- dm_chat_channel_2 = Fabricate(:direct_message_channel, users: [user, other_user])-- get "/chat/chat_channels/search.json", params: { filter: "janemay" }- expect(response.status).to eq(200)- expect(response.parsed_body["direct_message_channels"].count).to eq(0)-- GroupUser.create(user: other_user, group: group)- get "/chat/chat_channels/search.json", params: { filter: "janemay" }- expect(response.status).to eq(200)- expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_chat_channel_2.id)- end-- it "returns DM channels for staff users even if they are not in chat_allowed_groups" do- group = Fabricate(:group, name: "chatpeeps")- SiteSetting.chat_allowed_groups = group.id- GroupUser.create(user: user, group: group)-- get "/chat/chat_channels/search.json", params: { filter: "andyjones" }- expect(response.status).to eq(200)- expect(response.parsed_body["direct_message_channels"][0]["id"]).to eq(dm_chat_channel.id)- end-- it "returns followed channels" do- Fabricate(- :user_chat_channel_membership,- user: user,- chat_channel: chat_channel,- following: true,- )-- get "/chat/chat_channels/search.json", params: { filter: chat_channel.name }-- expect(response.status).to eq(200)- expect(response.parsed_body["public_channels"][0]["id"]).to eq(chat_channel.id)- end-- it "returns not followed channels" do- Fabricate(- :user_chat_channel_membership,- user: user,- chat_channel: chat_channel,- following: false,- )-- get "/chat/chat_channels/search.json", params: { filter: chat_channel.name }-- expect(response.status).to eq(200)- expect(response.parsed_body["public_channels"][0]["id"]).to eq(chat_channel.id)- end- end- end-- describe "#show" do- fab!(:channel) do- Fabricate(:category_channel, chatable: category, name: "My Great Channel & Stuff")- end-- it "can find channel by id" do- sign_in(user)- get "/chat/chat_channels/#{channel.id}.json"- expect(response.status).to eq(200)- expect(response.parsed_body["id"]).to eq(channel.id)- end-- it "can find channel by name" do- sign_in(user)- get "/chat/chat_channels/#{UrlHelper.encode_component("My Great Channel & Stuff")}.json"- expect(response.status).to eq(200)- expect(response.parsed_body["id"]).to eq(channel.id)- end-- it "can find channel by chatable title/name" do- sign_in(user)-- channel.update!(chatable: Fabricate(:category, name: "Support Chat"))- get "/chat/chat_channels/#{UrlHelper.encode_component("Support Chat")}.json"- expect(response.status).to eq(200)- expect(response.parsed_body["id"]).to eq(channel.id)- end-- it "gives a not found error if the channel cannot be found by name or id" do- channel.destroy- sign_in(user)- get "/chat/chat_channels/#{channel.id}.json"- expect(response.status).to eq(404)- get "/chat/chat_channels/#{UrlHelper.encode_component(channel.name)}.json"- expect(response.status).to eq(404)- end- end-- describe "#archive" do- fab!(:channel) { Fabricate(:category_channel, chatable: category, name: "The English Channel") }- let(:new_topic_params) do- { type: "newTopic", title: "This is a test archive topic", category_id: category.id }- end- let(:existing_topic_params) { { type: "existingTopic", topic_id: Fabricate(:topic).id } }-- it "returns error if user is not staff" do- sign_in(user)- put "/chat/chat_channels/#{channel.id}/archive.json", params: new_topic_params- expect(response.status).to eq(403)- end-- it "returns error if type or chat_channel_id is not provided" do- sign_in(admin)- put "/chat/chat_channels/#{channel.id}/archive.json", params: {}- expect(response.status).to eq(400)- end-- it "returns error if title is not provided for new topic" do- sign_in(admin)- put "/chat/chat_channels/#{channel.id}/archive.json", params: { type: "newTopic" }- expect(response.status).to eq(400)- end-- it "returns error if topic_id is not provided for existing topic" do- sign_in(admin)- put "/chat/chat_channels/#{channel.id}/archive.json", params: { type: "existingTopic" }- expect(response.status).to eq(400)- end-- it "returns error if the channel cannot be archived" do- channel.update!(status: :archived)- sign_in(admin)- put "/chat/chat_channels/#{channel.id}/archive.json", params: new_topic_params- expect(response.status).to eq(403)- end-- it "starts the archive process using a new topic" do- sign_in(admin)- put "/chat/chat_channels/#{channel.id}/archive.json", params: new_topic_params- channel_archive = ChatChannelArchive.find_by(chat_channel: channel)- expect(- job_enqueued?(- job: :chat_channel_archive,- args: {- chat_channel_archive_id: channel_archive.id,- },- ),- ).to eq(true)- expect(channel.reload.status).to eq("read_only")- end-- it "starts the archive process using an existing topic" do- sign_in(admin)- put "/chat/chat_channels/#{channel.id}/archive.json", params: existing_topic_params- channel_archive = ChatChannelArchive.find_by(chat_channel: channel)- expect(- job_enqueued?(- job: :chat_channel_archive,- args: {- chat_channel_archive_id: channel_archive.id,- },- ),- ).to eq(true)- expect(channel.reload.status).to eq("read_only")- end-- it "does nothing if the chat channel archive already exists" do- sign_in(admin)- put "/chat/chat_channels/#{channel.id}/archive.json", params: new_topic_params- expect(response.status).to eq(200)- expect {- put "/chat/chat_channels/#{channel.id}/archive.json", params: new_topic_params- }.not_to change { ChatChannelArchive.count }- end- end-- describe "#retry_archive" do- fab!(:channel) do- Fabricate(- :category_channel,- chatable: category,- name: "The English Channel",- status: :read_only,- )- end- fab!(:archive) do- ChatChannelArchive.create!(- chat_channel: channel,- destination_topic_title: "test archive topic title",- archived_by: admin,- total_messages: 10,- )- end-- it "returns error if user is not staff" do- sign_in(user)- put "/chat/chat_channels/#{channel.id}/retry_archive.json"- expect(response.status).to eq(403)- end-- it "returns a 404 if the archive has not been started" do- archive.destroy- sign_in(admin)- put "/chat/chat_channels/#{channel.id}/retry_archive.json"- expect(response.status).to eq(404)- end-- it "returns a 403 error if the archive is not currently failed" do- sign_in(admin)- archive.update!(archive_error: nil)- put "/chat/chat_channels/#{channel.id}/retry_archive.json"- expect(response.status).to eq(403)- end-- it "returns a 403 error if the channel is not read_only" do- sign_in(admin)- archive.update!(archive_error: "bad stuff", archived_messages: 1)- channel.update!(status: "open")- put "/chat/chat_channels/#{channel.id}/retry_archive.json"- expect(response.status).to eq(403)- end-- it "re-enqueues the archive job" do- sign_in(admin)- archive.update!(archive_error: "bad stuff", archived_messages: 1)- put "/chat/chat_channels/#{channel.id}/retry_archive.json"- expect(response.status).to eq(200)- expect(- job_enqueued?(job: :chat_channel_archive, args: { chat_channel_archive_id: archive.id }),- ).to eq(true)- end- end-- describe "#change_status" do- fab!(:channel) do- Fabricate(:category_channel, chatable: category, name: "Channel Orange", status: :open)- end-- it "returns error if user is not staff" do- sign_in(user)- put "/chat/chat_channels/#{channel.id}/change_status.json", params: { status: "closed" }- expect(response.status).to eq(403)- end-- it "returns a 404 if the channel does not exist" do- channel.destroy!- sign_in(admin)- put "/chat/chat_channels/#{channel.id}/change_status.json", params: { status: "closed" }- expect(response.status).to eq(404)- end-- it "returns a 400 if the channel status is not closed or open" do- channel.update!(status: "read_only")- sign_in(admin)- put "/chat/chat_channels/#{channel.id}/change_status.json", params: { status: "closed" }- expect(response.status).to eq(403)- end-- it "changes the channel to closed if it is open" do- sign_in(admin)- put "/chat/chat_channels/#{channel.id}/change_status.json", params: { status: "closed" }- expect(response.status).to eq(200)- expect(channel.reload.status).to eq("closed")- end-- it "changes the channel to open if it is closed" do- channel.update!(status: "closed")- sign_in(admin)- put "/chat/chat_channels/#{channel.id}/change_status.json", params: { status: "open" }- expect(response.status).to eq(200)- expect(channel.reload.status).to eq("open")- end- end-- describe "#delete" do- fab!(:channel) do- Fabricate(:category_channel, chatable: category, name: "Ambrose Channel", status: :open)- end-- it "returns error if user is not staff" do- sign_in(user)- delete "/chat/chat_channels/#{channel.id}.json",- params: {- channel_name_confirmation: "ambrose channel",- }- expect(response.status).to eq(403)- end-- it "returns a 404 if the channel does not exist" do- channel.destroy!- sign_in(admin)- delete "/chat/chat_channels/#{channel.id}.json",- params: {- channel_name_confirmation: "ambrose channel",- }- expect(response.status).to eq(404)- end-- it "returns a 400 if the channel_name_confirmation does not match the channel name" do- sign_in(admin)- delete "/chat/chat_channels/#{channel.id}.json",- params: {- channel_name_confirmation: "some Other channel",- }- expect(response.status).to eq(400)- end-- it "deletes the channel right away and enqueues the background job to delete all its chat messages and related content" do- sign_in(admin)- delete "/chat/chat_channels/#{channel.id}.json",- params: {- channel_name_confirmation: "ambrose channel",- }- expect(response.status).to eq(200)- expect(channel.reload.trashed?).to eq(true)- expect(job_enqueued?(job: :chat_channel_delete, args: { chat_channel_id: channel.id })).to eq(- true,- )- expect(- UserHistory.exists?(- acting_user_id: admin.id,- action: UserHistory.actions[:custom_staff],- custom_type: "chat_channel_delete",- ),- ).to eq(true)- end- end-enddiff --git a/plugins/chat/spec/requests/chat_controller_spec.rb b/plugins/chat/spec/requests/chat_controller_spec.rbindex 949c5608b2f..8b08203a697 100644--- a/plugins/chat/spec/requests/chat_controller_spec.rb+++ b/plugins/chat/spec/requests/chat_controller_spec.rb@@ -358,40 +358,19 @@ RSpec.describe Chat::ChatController dofab!(:chatable) { Fabricate(:direct_message, users: [user1, user2]) }fab!(:direct_message_channel) { Fabricate(:direct_message_channel, chatable: chatable) }- def create_memberships- UserChatChannelMembership.create!(- user: user1,- chat_channel: direct_message_channel,- following: true,- desktop_notification_level: UserChatChannelMembership::NOTIFICATION_LEVELS[:always],- mobile_notification_level: UserChatChannelMembership::NOTIFICATION_LEVELS[:always],- )- UserChatChannelMembership.create!(- user: user2,- chat_channel: direct_message_channel,- following: false,- desktop_notification_level: UserChatChannelMembership::NOTIFICATION_LEVELS[:always],- mobile_notification_level: UserChatChannelMembership::NOTIFICATION_LEVELS[:always],- )- Group.refresh_automatic_groups!- end-it "forces users to follow the channel" do- create_memberships-- expect(UserChatChannelMembership.find_by(user_id: user2.id).following).to be false+ direct_message_channel.remove(user2)ChatPublisher.expects(:publish_new_channel).oncesign_in(user1)+post "/chat/#{direct_message_channel.id}.json", params: { message: message }expect(UserChatChannelMembership.find_by(user_id: user2.id).following).to be trueendit "errors when the user is not part of the direct message channel" do- create_memberships-DirectMessageUser.find_by(user: user1, direct_message: chatable).destroy!sign_in(user1)post "/chat/#{direct_message_channel.id}.json", params: { message: message }@@ -405,7 +384,6 @@ RSpec.describe Chat::ChatController docontext "when current user is silenced" dobefore do- create_membershipssign_in(user1)UserSilencer.new(user1).silenceend@@ -422,9 +400,7 @@ RSpec.describe Chat::ChatController doendit "does not force them to follow the channel or send a publish_new_channel message" do- create_memberships-- expect(UserChatChannelMembership.find_by(user_id: user2.id).following).to be false+ direct_message_channel.remove(user2)ChatPublisher.expects(:publish_new_channel).never@@ -1377,105 +1353,4 @@ RSpec.describe Chat::ChatController doendendend-- describe "#move_messages_to_channel" do- fab!(:message_to_move1) do- Fabricate(- :chat_message,- chat_channel: chat_channel,- message: "some cool message",- created_at: 2.minutes.ago,- )- end- fab!(:message_to_move2) do- Fabricate(- :chat_message,- chat_channel: chat_channel,- message: "and another thing",- created_at: 1.minute.ago,- )- end- fab!(:destination_channel) { Fabricate(:category_channel) }- let(:message_ids) { [message_to_move1.id, message_to_move2.id] }- let(:invalid_destination_channel) do- Fabricate(:direct_message_channel, users: [admin, Fabricate(:user)])- end-- context "when the user is not admin" do- it "returns an access denied error" do- sign_in(user)- put "/chat/#{chat_channel.id}/move_messages_to_channel.json",- params: {- destination_channel_id: destination_channel.id,- message_ids: message_ids,- }- expect(response.status).to eq(403)- end- end-- context "when the user is admin" do- before { sign_in(admin) }-- it "shows an error if the source channel is not found" do- chat_channel.trash!- put "/chat/#{chat_channel.id}/move_messages_to_channel.json",- params: {- destination_channel_id: destination_channel.id,- message_ids: message_ids,- }- expect(response.status).to eq(404)- end-- it "shows an error if the destination channel is not found" do- destination_channel.trash!- put "/chat/#{chat_channel.id}/move_messages_to_channel.json",- params: {- destination_channel_id: destination_channel.id,- message_ids: message_ids,- }- expect(response.status).to eq(404)- end-- it "successfully moves the messages to the new channel" do- put "/chat/#{chat_channel.id}/move_messages_to_channel.json",- params: {- destination_channel_id: destination_channel.id,- message_ids: message_ids,- }- expect(response.status).to eq(200)- latest_destination_messages = destination_channel.chat_messages.last(2)- expect(latest_destination_messages.first.message).to eq("some cool message")- expect(latest_destination_messages.second.message).to eq("and another thing")- expect(message_to_move1.reload.deleted_at).not_to eq(nil)- expect(message_to_move2.reload.deleted_at).not_to eq(nil)- end-- it "shows an error message when the destination channel is invalid" do- put "/chat/#{chat_channel.id}/move_messages_to_channel.json",- params: {- destination_channel_id: invalid_destination_channel.id,- message_ids: message_ids,- }- expect(response.status).to eq(422)- expect(response.parsed_body["errors"]).to include(- I18n.t("chat.errors.message_move_invalid_channel"),- )- end-- it "shows an error when none of the messages can be found" do- destroyed_message = Fabricate(:chat_message, chat_channel: chat_channel)- destroyed_message.trash!-- put "/chat/#{chat_channel.id}/move_messages_to_channel.json",- params: {- destination_channel_id: destination_channel.id,- message_ids: [destroyed_message],- }- expect(response.status).to eq(422)- expect(response.parsed_body["errors"]).to include(- I18n.t("chat.errors.message_move_no_messages_found"),- )- end- end- endenddiff --git a/plugins/chat/spec/requests/categories_controller_spec.rb b/plugins/chat/spec/requests/core_ext/categories_controller_spec.rbsimilarity index 100%rename from plugins/chat/spec/requests/categories_controller_spec.rbrename to plugins/chat/spec/requests/core_ext/categories_controller_spec.rbdiff --git a/plugins/chat/spec/requests/email_controller_spec.rb b/plugins/chat/spec/requests/core_ext/email_controller_spec.rbsimilarity index 100%rename from plugins/chat/spec/requests/email_controller_spec.rbrename to plugins/chat/spec/requests/core_ext/email_controller_spec.rbdiff --git a/plugins/chat/spec/requests/users_controller_spec.rb b/plugins/chat/spec/requests/core_ext/users_controller_spec.rbsimilarity index 100%rename from plugins/chat/spec/requests/users_controller_spec.rbrename to plugins/chat/spec/requests/core_ext/users_controller_spec.rbdiff --git a/plugins/chat/spec/requests/direct_messages_controller_spec.rb b/plugins/chat/spec/requests/direct_messages_controller_spec.rbindex 5a327efe33f..c4c32de74f4 100644--- a/plugins/chat/spec/requests/direct_messages_controller_spec.rb+++ b/plugins/chat/spec/requests/direct_messages_controller_spec.rb@@ -50,7 +50,7 @@ RSpec.describe Chat::DirectMessagesController doit "returns the channel" doget "/chat/direct_messages.json", params: { usernames: user1.username }expect(response.status).to eq(200)- expect(response.parsed_body["chat_channel"]["id"]).to eq(channel.id)+ expect(response.parsed_body["channel"]["id"]).to eq(channel.id)endcontext "with more than two users" do@@ -63,7 +63,7 @@ RSpec.describe Chat::DirectMessagesController dousernames: [user1.username, user.username, user3.username].join(","),}expect(response.status).to eq(200)- expect(response.parsed_body["chat_channel"]["id"]).to eq(channel.id)+ expect(response.parsed_body["channel"]["id"]).to eq(channel.id)endendenddiff --git a/plugins/chat/spec/serializer/structured_channel_serializer_spec.rb b/plugins/chat/spec/serializer/structured_channel_serializer_spec.rbindex 503760588eb..0cfd801ebbf 100644--- a/plugins/chat/spec/serializer/structured_channel_serializer_spec.rb+++ b/plugins/chat/spec/serializer/structured_channel_serializer_spec.rb@@ -7,8 +7,12 @@ RSpec.describe StructuredChannelSerializer dofab!(:user3) { Fabricate(:user) }fab!(:channel1) { Fabricate(:category_channel) }fab!(:channel2) { Fabricate(:category_channel) }- fab!(:channel3) { Fabricate(:direct_message_channel, users: [user1, user2]) }- fab!(:channel4) { Fabricate(:direct_message_channel, users: [user1, user3]) }+ fab!(:channel3) do+ Fabricate(:direct_message_channel, users: [user1, user2], with_membership: false)+ end+ fab!(:channel4) do+ Fabricate(:direct_message_channel, users: [user1, user3], with_membership: false)+ endfab!(:membership1) doFabricate(:user_chat_channel_membership, user: user1, chat_channel: channel1)end@@ -78,8 +82,9 @@ RSpec.describe StructuredChannelSerializer do.new(fetch_data, scope: Guardian.new).public_channels.find { |channel| channel.id == channel1.id }- .current_user_membership- .as_json,+ .as_json[+ :current_user_membership+ ],).to eq(nil)end@@ -88,13 +93,15 @@ RSpec.describe StructuredChannelSerializer dodata[:memberships] = data[:memberships].reject do |membership|membership.chat_channel_id == channel1.idend+expect(described_class.new(data, scope: guardian).public_channels.find { |channel| channel.id == channel1.id }- .current_user_membership- .as_json,+ .as_json[+ :current_user_membership+ ],).to eq(nil)endenddiff --git a/plugins/chat/spec/support/api/schemas/category_chat_channel.json b/plugins/chat/spec/support/api/schemas/category_chat_channel.jsonindex a0905eab33f..60fe90b3fd6 100644--- a/plugins/chat/spec/support/api/schemas/category_chat_channel.json+++ b/plugins/chat/spec/support/api/schemas/category_chat_channel.json@@ -1,7 +1,19 @@{"type": "object","additionalProperties": {- "auto_join_users": { "type": "boolean" }+ "auto_join_users": { "type": "boolean" },+ "current_user_membership": {+ "type": ["object"],+ "properties": {+ "last_read_message_id": { "type": ["number", "null"] },+ "muted": { "type": "boolean" },+ "unread_count": { "type": "number" },+ "unread_mentions": { "type": "number" },+ "desktop_notification_level": { "type": "string" },+ "mobile_notification_level": { "type": "string" },+ "following": { "type": "boolean" }+ }+ }},"properties": {"id": { "type": "number" },@@ -14,18 +26,6 @@"chatable": {"type": "object","required": ["id", "name", "slug", "color"]- },- "current_user_membership": {- "type": ["object", "null"],- "properties": {- "last_read_message_id": { "type": ["number", "null"] },- "muted": { "type": "boolean" },- "unread_count": { "type": "number" },- "unread_mentions": { "type": "number" },- "desktop_notification_level": { "type": "string" },- "mobile_notification_level": { "type": "string" },- "following": { "type": "boolean" }- }}}}diff --git a/plugins/chat/spec/support/examples/channel_access_example.rb b/plugins/chat/spec/support/examples/channel_access_example.rbindex 4a242bcd8c1..775f698683a 100644--- a/plugins/chat/spec/support/examples/channel_access_example.rb+++ b/plugins/chat/spec/support/examples/channel_access_example.rb@@ -1,13 +1,14 @@# frozen_string_literal: true-RSpec.shared_examples "channel access example" do |verb, endpoint|+RSpec.shared_examples "channel access example" do |verb, endpoint, params|endpoint ||= ".json"+ params ||= {}context "when channel is not found" dobefore { sign_in(Fabricate(:admin)) }it "returns a 404" do- public_send(verb, "/chat/api/chat_channels/-999#{endpoint}")+ public_send(verb, "/chat/api/channels/-999#{endpoint}", params: params)expect(response.status).to eq(404)endend@@ -16,7 +17,7 @@ RSpec.shared_examples "channel access example" do |verb, endpoint|fab!(:chat_channel) { Fabricate(:category_channel) }it "returns a 403" do- public_send(verb, "/chat/api/chat_channels/#{chat_channel.id}#{endpoint}")+ public_send(verb, "/chat/api/channels/#{chat_channel.id}#{endpoint}", params: params)expect(response.status).to eq(403)endend@@ -32,7 +33,7 @@ RSpec.shared_examples "channel access example" do |verb, endpoint|before { sign_in(user) }it "returns a 403" do- public_send(verb, "/chat/api/chat_channels/#{chat_channel.id}#{endpoint}")+ public_send(verb, "/chat/api/channels/#{chat_channel.id}#{endpoint}", params: params)expect(response.status).to eq(403)endenddiff --git a/plugins/chat/spec/system/anonymous_spec.rb b/plugins/chat/spec/system/anonymous_spec.rbnew file mode 100644index 00000000000..e33ffa97462--- /dev/null+++ b/plugins/chat/spec/system/anonymous_spec.rb@@ -0,0 +1,15 @@+# frozen_string_literal: true++RSpec.describe "Anonymous", type: :system, js: true do+ fab!(:topic) { Fabricate(:topic) }++ before { chat_system_bootstrap }++ context "when anonymous" do+ it "doesn’t cause issues" do+ visit("/")++ expect(page).to have_content(topic.title)+ end+ end+enddiff --git a/plugins/chat/spec/system/archive_channel_spec.rb b/plugins/chat/spec/system/archive_channel_spec.rbnew file mode 100644index 00000000000..409d86671b6--- /dev/null+++ b/plugins/chat/spec/system/archive_channel_spec.rb@@ -0,0 +1,124 @@+# frozen_string_literal: true++RSpec.describe "Archive channel", type: :system, js: true do+ fab!(:channel_1) { Fabricate(:chat_channel) }++ let(:chat) { PageObjects::Pages::Chat.new }+ let(:channel) { PageObjects::Pages::ChatChannel.new }++ before do+ SiteSetting.navigation_menu = "sidebar"+ chat_system_bootstrap+ sign_in(current_user)+ end++ context "when archiving is disabled" do+ context "when admin user" do+ fab!(:current_user) { Fabricate(:admin) }++ before { sign_in(current_user) }++ it "doesn’t allow to archive a channel" do+ chat.visit_channel_settings(channel_1)++ expect(page).to have_no_content(I18n.t("js.chat.channel_settings.archive_channel"))+ end+ end+ end++ context "when archiving is enabled" do+ before { SiteSetting.chat_allow_archiving_channels = true }++ context "when regular user" do+ fab!(:current_user) { Fabricate(:user) }++ before { sign_in(current_user) }++ it "doesn’t allow to archive a channel" do+ chat.visit_channel_settings(channel_1)++ expect(page).to have_no_content(I18n.t("js.chat.channel_settings.archive_channel"))+ end+ end++ context "when admin user" do+ fab!(:current_user) { Fabricate(:admin) }++ before { sign_in(current_user) }++ it "allows to archive a channel" do+ chat.visit_channel_settings(channel_1)++ expect(page).to have_content(I18n.t("js.chat.channel_settings.archive_channel"))+ end++ context "when archiving" do+ before { Jobs.run_immediately! }++ it "works" do+ chat.visit_channel_settings(channel_1)+ click_button(I18n.t("js.chat.channel_settings.archive_channel"))+ find("#split-topic-name").fill_in(with: "An interesting topic for cats")+ click_button(I18n.t("js.chat.channel_archive.title"))++ expect(page).to have_content(I18n.t("js.chat.channel_archive.process_started"))++ chat.visit_channel(channel_1)++ expect(page).to have_content(I18n.t("js.chat.channel_status.archived_header"))+ end++ context "when archived channels had unreads" do+ before do+ other_user = Fabricate(:user)+ channel_1.add(other_user)+ channel_1.add(current_user)+ Chat::ChatMessageCreator.create(+ chat_channel: channel_1,+ user: other_user,+ content: "this is fine @#{current_user.username}",+ )+ end++ it "clears unread indicators" do+ visit("/")+ expect(page.find(".chat-channel-unread-indicator")).to have_content(1)++ chat.visit_channel_settings(channel_1)+ click_button(I18n.t("js.chat.channel_settings.archive_channel"))+ find("#split-topic-name").fill_in(with: "An interesting topic for cats")+ click_button(I18n.t("js.chat.channel_archive.title"))++ expect(page).to have_no_css(".chat-channel-unread-indicator")+ end+ end+ end++ context "when archiving failed" do+ before do+ Jobs.run_immediately!+ channel_1.update!(status: :read_only)+ end++ fab!(:archive) do+ ChatChannelArchive.create!(+ chat_channel: channel_1,+ archived_by: current_user,+ destination_topic_title: "This will be the archive topic",+ total_messages: 2,+ archived_messages: 1,+ archive_error: "Something went wrong",+ )+ end++ it "can be retried" do+ chat.visit_channel(channel_1)+ click_button(I18n.t("js.chat.channel_archive.retry"))+ visit(find(".chat-channel-archive-status a")["href"])++ expect(page).to have_content(archive.destination_topic_title)+ end+ end+ end+ end+enddiff --git a/plugins/chat/spec/system/bookmark_message_spec.rb b/plugins/chat/spec/system/bookmark_message_spec.rbnew file mode 100644index 00000000000..e2ebe82eb24--- /dev/null+++ b/plugins/chat/spec/system/bookmark_message_spec.rb@@ -0,0 +1,45 @@+# frozen_string_literal: true++RSpec.describe "Bookmark message", type: :system, js: true do+ fab!(:current_user) { Fabricate(:user) }++ let(:chat) { PageObjects::Pages::Chat.new }+ let(:channel) { PageObjects::Pages::ChatChannel.new }+ fab!(:category_channel_1) { Fabricate(:category_channel) }+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: category_channel_1) }++ before do+ chat_system_bootstrap+ category_channel_1.add(current_user)+ sign_in(current_user)+ end++ context "when desktop" do+ it "allows to bookmark a message" do+ chat.visit_channel(category_channel_1)+ channel.bookmark_message(message_1)++ expect(page).to have_css("#bookmark-reminder-modal")++ find("#bookmark-name").fill_in(with: "Check this out later")+ find("#tap_tile_next_month").click++ expect(channel).to have_bookmarked_message(message_1)+ end+ end++ context "when mobile", mobile: true do+ it "allows to bookmark a message" do+ chat.visit_channel(category_channel_1)++ channel.message_by_id(message_1.id).click(delay: 0.5)+ find(".bookmark-btn").click+ expect(page).to have_css("#bookmark-reminder-modal")++ find("#bookmark-name").fill_in(with: "Check this out later")+ find("#tap_tile_next_month").click++ expect(channel).to have_bookmarked_message(message_1)+ end+ end+enddiff --git a/plugins/chat/spec/system/browse_page_spec.rb b/plugins/chat/spec/system/browse_page_spec.rbnew file mode 100644index 00000000000..9022ca05245--- /dev/null+++ b/plugins/chat/spec/system/browse_page_spec.rb@@ -0,0 +1,190 @@+# frozen_string_literal: true++RSpec.describe "Browse page", type: :system, js: true do+ fab!(:current_user) { Fabricate(:user) }++ let(:chat) { PageObjects::Pages::Chat.new }++ def browse_view+ page.find(".chat-browse-view")+ end++ before do+ sign_in(current_user)+ chat_system_bootstrap+ end++ context "when user has chat disabled" do+ before { current_user.user_option.update!(chat_enabled: false) }++ it "redirects to homepage" do+ visit("/chat/browse")++ expect(page).to have_current_path("/latest")+ end+ end++ context "when user has chat enabled" do+ context "when visiting browse page" do+ it "defaults to open filer" do+ visit("/chat/browse")++ expect(page).to have_current_path("/chat/browse/open")+ end++ it "has the expected tabs" do+ visit("/chat/browse")++ expect(browse_view).to have_content(I18n.t("js.chat.browse.filter_all"))+ expect(browse_view).to have_content(I18n.t("js.chat.browse.filter_open"))+ expect(browse_view).to have_content(I18n.t("js.chat.browse.filter_closed"))+ end++ it "has not archived tab available" do+ visit("/chat/browse")++ expect(browse_view).to have_no_content(I18n.t("js.chat.browse.filter_archived"))+ end++ it "redirects archived tab to default tab" do+ visit("/chat/browse/archived")++ expect(page).to have_current_path("/chat/browse/open")+ end++ context "when archiving channels is enabled" do+ before { SiteSetting.chat_allow_archiving_channels = true }++ it "has the archived tab" do+ visit("/chat/browse")++ expect(browse_view).to have_content(I18n.t("js.chat.browse.filter_archived"))+ end+ end+ end++ context "when on mobile", mobile: true do+ it "has a back button" do+ visit("/chat/browse")+ find(".chat-full-page-header__back-btn").click++ expect(page).to have_current_path("/chat")+ end+ end++ context "when filtering resuls" do+ fab!(:category_channel_1) { Fabricate(:chat_channel, name: "foo") }+ fab!(:category_channel_2) { Fabricate(:chat_channel, name: "bar") }++ context "when results are found" do+ it "lists expected results" do+ visit("/chat/browse")+ find(".dc-filter-input").fill_in(with: category_channel_1.name)++ expect(browse_view).to have_content(category_channel_1.name)+ expect(browse_view).to have_no_content(category_channel_2.name)+ end+ end++ context "when results are not found" do+ it "displays the correct message" do+ visit("/chat/browse")+ find(".dc-filter-input").fill_in(with: "x")++ expect(browse_view).to have_content(I18n.t("js.chat.empty_state.title"))+ end++ it "doesn’t display any channel" do+ visit("/chat/browse")+ find(".dc-filter-input").fill_in(with: "x")++ expect(browse_view).to have_no_content(category_channel_1.name)+ expect(browse_view).to have_no_content(category_channel_2.name)+ end+ end+ end++ context "when visiting tabs" do+ fab!(:category_channel_1) { Fabricate(:chat_channel, status: :open) }+ fab!(:category_channel_2) { Fabricate(:chat_channel, status: :read_only) }+ fab!(:category_channel_3) { Fabricate(:chat_channel, status: :closed) }+ fab!(:category_channel_4) { Fabricate(:chat_channel, status: :archived) }+ fab!(:category_channel_5) { Fabricate(:chat_channel, status: :open) }+ fab!(:direct_message_channel_1) { Fabricate(:direct_message_channel, users: [current_user]) }++ before { category_channel_5.destroy! }++ shared_examples "never visible channels" do+ it "doesn’t list direct message channel" do+ expect(browse_view).to have_no_content(direct_message_channel_1.title(current_user))+ end++ it "doesn’t list destroyed channels" do+ expect(browse_view).to have_no_content(category_channel_5.title)+ end+ end++ context "when filter is all" do+ it "lists all category channels" do+ visit("/chat/browse/all")++ expect(browse_view).to have_content(category_channel_1.name)+ expect(browse_view).to have_content(category_channel_2.name)+ expect(browse_view).to have_content(category_channel_3.name)+ expect(browse_view).to have_content(category_channel_4.name)+ end++ include_examples "never visible channels" do+ before { visit("/chat/browse/all") }+ end+ end++ context "when filter is open" do+ it "lists all opened category channels" do+ visit("/chat/browse/open")++ expect(browse_view).to have_content(category_channel_1.name)+ expect(browse_view).to have_no_content(category_channel_2.name)+ expect(browse_view).to have_no_content(category_channel_3.name)+ expect(browse_view).to have_no_content(category_channel_4.name)+ end++ include_examples "never visible channels" do+ before { visit("/chat/browse/open") }+ end+ end++ context "when filter is closed" do+ it "lists all closed category channels" do+ visit("/chat/browse/closed")++ expect(browse_view).to have_no_content(category_channel_1.name)+ expect(browse_view).to have_no_content(category_channel_2.name)+ expect(browse_view).to have_content(category_channel_3.name)+ expect(browse_view).to have_no_content(category_channel_4.name)+ end++ include_examples "never visible channels" do+ before { visit("/chat/browse/closed") }+ end+ end++ context "when filter is archived" do+ before { SiteSetting.chat_allow_archiving_channels = true }++ it "lists all archived category channels" do+ visit("/chat/browse/archived")++ expect(browse_view).to have_no_content(category_channel_1.name)+ expect(browse_view).to have_no_content(category_channel_2.name)+ expect(browse_view).to have_no_content(category_channel_3.name)+ expect(browse_view).to have_content(category_channel_4.name)+ end++ include_examples "never visible channels" do+ before { visit("/chat/browse/archived") }+ end+ end+ end+ end+enddiff --git a/plugins/chat/spec/system/channel_about_page_spec.rb b/plugins/chat/spec/system/channel_about_page_spec.rbnew file mode 100644index 00000000000..a1cd22bd851--- /dev/null+++ b/plugins/chat/spec/system/channel_about_page_spec.rb@@ -0,0 +1,111 @@+# frozen_string_literal: true++RSpec.describe "Channel - Info - About page", type: :system, js: true do+ fab!(:channel_1) { Fabricate(:category_channel) }++ let(:chat_page) { PageObjects::Pages::Chat.new }++ before { chat_system_bootstrap }++ context "as regular user" do+ fab!(:current_user) { Fabricate(:user) }++ before { sign_in(current_user) }++ it "shows channel info" do+ chat_page.visit_channel_about(channel_1)++ expect(page.find(".category-name")).to have_content(channel_1.chatable.name)+ expect(page.find(".channel-info-about-view__title")).to have_content(channel_1.title)+ end++ it "escapes channel title" do+ channel_1.update!(name: "<script>alert('hello')</script>")+ chat_page.visit_channel_about(channel_1)++ expect(page.find(".channel-info-about-view__title")["innerHTML"].strip).to eq(+ "<script>alert('hello')</script>",+ )+ expect(page.find(".chat-channel-title__name")["innerHTML"].strip).to eq(+ "<script>alert('hello')</script>",+ )+ end++ it "can’t edit title" do+ chat_page.visit_channel_about(channel_1)++ expect(page).to have_no_selector(".edit-title-btn")+ end++ it "can’t edit description" do+ chat_page.visit_channel_about(channel_1)++ expect(page).to have_no_selector(".edit-description-btn")+ end++ context "as a member" do+ before { channel_1.add(current_user) }++ it "can leave channel" do+ chat_page.visit_channel_about(channel_1)+ membership = channel_1.membership_for(current_user)++ expect {+ click_button(I18n.t("js.chat.channel_settings.leave_channel"))+ expect(page).to have_content(I18n.t("js.chat.channel_settings.join_channel"))+ }.to change { membership.reload.following }.from(true).to(false)+ end+ end++ context "as not a member" do+ it "can join channel" do+ chat_page.visit_channel_about(channel_1)++ expect {+ click_button(I18n.t("js.chat.channel_settings.join_channel"))+ expect(page).to have_content(I18n.t("js.chat.channel_settings.leave_channel"))+ }.to change {+ UserChatChannelMembership.where(user_id: current_user.id, following: true).count+ }.by(1)+ end+ end+ end++ context "as admin" do+ fab!(:current_user) { Fabricate(:admin) }++ before { sign_in(current_user) }++ it "can edit title" do+ chat_page.visit_channel_about(channel_1)+ find(".edit-title-btn").click++ expect(page).to have_selector(+ ".chat-channel-edit-title-modal__title-input",+ text: channel_1.title,+ )++ title = "A new title"+ find(".chat-channel-edit-title-modal__title-input").fill_in(with: title)+ find(".create").click++ expect(page).to have_content(title)+ end++ it "can edit description" do+ chat_page.visit_channel_about(channel_1)+ find(".edit-description-btn").click++ expect(page).to have_selector(+ ".chat-channel-edit-description-modal__description-input",+ text: channel_1.description,+ )++ description = "A new description"+ find(".chat-channel-edit-description-modal__description-input").fill_in(with: description)+ find(".create").click++ expect(page).to have_content(description)+ end+ end+enddiff --git a/plugins/chat/spec/system/channel_info_pages_spec.rb b/plugins/chat/spec/system/channel_info_pages_spec.rbnew file mode 100644index 00000000000..64fb8b8da26--- /dev/null+++ b/plugins/chat/spec/system/channel_info_pages_spec.rb@@ -0,0 +1,38 @@+# frozen_string_literal: true++RSpec.describe "Info pages", type: :system, js: true do+ let(:chat_page) { PageObjects::Pages::Chat.new }+ let(:channel) { PageObjects::Pages::ChatChannel.new }+ fab!(:current_user) { Fabricate(:user) }+ fab!(:channel_1) { Fabricate(:chat_channel) }++ before do+ chat_system_bootstrap+ sign_in(current_user)+ channel_1.add(current_user)+ end++ context "when visiting from browse page" do+ context "when clicking back button" do+ it "redirects to browse page" do+ chat_page.visit_browse+ find(".chat-channel-card__setting").click+ find(".chat-full-page-header__back-btn").click++ expect(page).to have_current_path("/chat/browse/open")+ end+ end+ end++ context "when visiting from channel page" do+ context "when clicking back button" do+ it "redirects to channel page" do+ chat_page.visit_channel(channel_1)+ find(".chat-channel-title-wrapper").click+ find(".chat-full-page-header__back-btn").click++ expect(page).to have_current_path(chat.channel_path(channel_1.id, channel_1.slug))+ end+ end+ end+enddiff --git a/plugins/chat/spec/system/channel_members_page_spec.rb b/plugins/chat/spec/system/channel_members_page_spec.rbnew file mode 100644index 00000000000..5643e937f99--- /dev/null+++ b/plugins/chat/spec/system/channel_members_page_spec.rb@@ -0,0 +1,69 @@+# frozen_string_literal: true++RSpec.describe "Channel - Info - Members page", type: :system, js: true do+ let(:chat_page) { PageObjects::Pages::Chat.new }++ fab!(:current_user) { Fabricate(:user) }+ fab!(:channel_1) { Fabricate(:category_channel) }++ before do+ chat_system_bootstrap+ sign_in(current_user)+ end++ context "as unauthorized user" do+ before { SiteSetting.chat_allowed_groups = Fabricate(:group).id }++ it "can’t see channel members" do+ chat_page.visit_channel_members(channel_1)++ expect(page).to have_current_path("/latest")+ end+ end++ context "as authorized user" do+ context "with no members" do+ it "redirects to about page" do+ chat_page.visit_channel_members(channel_1)++ expect(page).to have_current_path(+ "/chat/channel/#{channel_1.id}/#{channel_1.slug}/info/about",+ )+ end+ end++ context "with members" do+ before do+ channel_1.add(current_user)+ channel_1.add(Fabricate(:user, username: "cat"))+ 98.times { channel_1.add(Fabricate(:user)) }++ channel_1.update!(user_count_stale: true)+ Jobs::UpdateChannelUserCount.new.execute(chat_channel_id: channel_1.id)+ end++ it "shows all members" do+ chat_page.visit_channel_members(channel_1)++ expect(page).to have_selector(".channel-members-view__list-item", count: 50)++ scroll_to(find(".channel-members-view__list-item:nth-child(50)"))++ expect(page).to have_selector(".channel-members-view__list-item", count: 100)++ scroll_to(find(".channel-members-view__list-item:nth-child(100)"))++ expect(page).to have_selector(".channel-members-view__list-item", count: 100)+ end++ context "with filter" do+ it "filters members" do+ chat_page.visit_channel_members(channel_1)+ find(".channel-members-view__search-input").fill_in(with: "cat")++ expect(page).to have_selector(".channel-members-view__list-item", count: 1, text: "cat")+ end+ end+ end+ end+enddiff --git a/plugins/chat/spec/system/channel_selector_modal_spec.rb b/plugins/chat/spec/system/channel_selector_modal_spec.rbnew file mode 100644index 00000000000..255101ea93e--- /dev/null+++ b/plugins/chat/spec/system/channel_selector_modal_spec.rb@@ -0,0 +1,79 @@+# frozen_string_literal: true++RSpec.describe "Channel selector modal", type: :system, js: true do+ fab!(:current_user) { Fabricate(:user) }++ let(:chat_page) { PageObjects::Pages::Chat.new }+ let(:channel_page) { PageObjects::Pages::ChatChannel.new }++ before do+ chat_system_bootstrap+ sign_in(current_user)+ end++ KEY_MODIFIER = RUBY_PLATFORM =~ /darwin/i ? :meta : :control++ context "when used with public channel" do+ fab!(:channel_1) { Fabricate(:category_channel) }++ it "works" do+ find("body").send_keys([KEY_MODIFIER, "k"])+ find("#chat-channel-selector-input").fill_in(with: channel_1.title)+ find(".chat-channel-selection-row[data-id='#{channel_1.id}']").click+ channel_page.send_message("Hello world")++ expect(channel_page).to have_message(text: "Hello world")+ end+ end++ context "when used with user" do+ fab!(:user_1) { Fabricate(:user) }++ it "works" do+ find("body").send_keys([KEY_MODIFIER, "k"])+ find("#chat-channel-selector-input").fill_in(with: user_1.username)+ find(".chat-channel-selection-row[data-id='#{user_1.id}']").click+ channel_page.send_message("Hello world")++ expect(channel_page).to have_message(text: "Hello world")+ end+ end++ context "when used with dm channel" do+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user]) }++ it "works" do+ find("body").send_keys([KEY_MODIFIER, "k"])+ find("#chat-channel-selector-input").fill_in(with: current_user.username)+ find(".chat-channel-selection-row[data-id='#{dm_channel_1.id}']").click+ channel_page.send_message("Hello world")++ expect(channel_page).to have_message(text: "Hello world")+ end+ end++ context "when on a channel" do+ fab!(:channel_1) { Fabricate(:category_channel) }++ it "it doesn’t include current channel" do+ chat_page.visit_channel(channel_1)+ find("body").send_keys([KEY_MODIFIER, "k"])+ find("#chat-channel-selector-input").fill_in(with: channel_1.title)++ expect(page).to have_no_css(".chat-channel-selection-row[data-id='#{channel_1.id}']")+ end+ end++ context "with limited access channels" do+ fab!(:group_1) { Fabricate(:group) }+ fab!(:channel_1) { Fabricate(:private_category_channel, group: group_1) }++ it "it doesn’t include limited access channel" do+ chat_page.visit_channel(channel_1)+ find("body").send_keys([KEY_MODIFIER, "k"])+ find("#chat-channel-selector-input").fill_in(with: channel_1.title)++ expect(page).to have_no_css(".chat-channel-selection-row[data-id='#{channel_1.id}']")+ end+ end+enddiff --git a/plugins/chat/spec/system/channel_settings_page_spec.rb b/plugins/chat/spec/system/channel_settings_page_spec.rbnew file mode 100644index 00000000000..83df778c4fc--- /dev/null+++ b/plugins/chat/spec/system/channel_settings_page_spec.rb@@ -0,0 +1,186 @@+# frozen_string_literal: true++RSpec.describe "Channel - Info - Settings page", type: :system, js: true do+ let(:chat_page) { PageObjects::Pages::Chat.new }+ fab!(:current_user) { Fabricate(:user) }+ fab!(:channel_1) { Fabricate(:category_channel) }++ before do+ chat_system_bootstrap+ sign_in(current_user)+ end++ context "as unauthorized user" do+ before { SiteSetting.chat_allowed_groups = Fabricate(:group).id }++ it "redirects to home page" do+ chat_page.visit_channel_settings(channel_1)++ expect(page).to have_current_path("/latest")+ end+ end++ context "as authorized user" do+ context "as not member" do+ it "redirects to about tab" do+ chat_page.visit_channel_settings(channel_1)++ expect(page).to have_current_path(+ "/chat/channel/#{channel_1.id}/#{channel_1.slug}/info/about",+ )+ end++ it "doesn’t have settings tab" do+ chat_page.visit_channel_settings(channel_1)++ expect(page).to have_no_selector(".chat-tabs-list__item[aria-controls='settings-tab']")+ end++ context "as an admin" do+ before { sign_in(Fabricate(:admin)) }++ it "shows settings tab" do+ chat_page.visit_channel_settings(channel_1)++ expect(page).to have_selector(".chat-tabs-list__item[aria-controls='settings-tab']")+ end++ it "can navigate to settings tab" do+ chat_page.visit_channel_settings(channel_1)++ expect(page).to have_current_path(+ "/chat/channel/#{channel_1.id}/#{channel_1.slug}/info/settings",+ )+ end+ end+ end++ context "as a member" do+ before { channel_1.add(current_user) }++ context "when visitng the settings of a recently joined channel" do+ fab!(:channel_2) { Fabricate(:category_channel) }++ it "is correctly populated" do+ chat_page.visit_browse+ find(+ ".chat-channel-card[data-channel-id='#{channel_2.id}'] .toggle-channel-membership-button",+ ).click++ expect(+ page.find(".chat-channel-card[data-channel-id='#{channel_2.id}']"),+ ).to have_content(I18n.t("js.chat.joined").upcase)++ find(+ ".chat-channel-card[data-channel-id='#{channel_2.id}'] .chat-channel-card__setting",+ ).click++ expect(page).to have_content(I18n.t("js.chat.notification_levels.mention"))+ end+ end++ it "can mute channel" do+ chat_page.visit_channel_settings(channel_1)+ membership = channel_1.membership_for(current_user)++ expect {+ find(".channel-settings-view__muted-selector").click+ find(".channel-settings-view__muted-selector [data-name='On']").click+ expect(page).to have_content(I18n.t("js.chat.settings.saved"))+ }.to change { membership.reload.muted }.from(false).to(true)+ end++ it "can change desktop notification level" do+ chat_page.visit_channel_settings(channel_1)+ membership = channel_1.membership_for(current_user)++ expect {+ find(".channel-settings-view__desktop-notification-level-selector").click+ find(+ ".channel-settings-view__desktop-notification-level-selector [data-name='Never']",+ ).click+ expect(page).to have_content(I18n.t("js.chat.settings.saved"))+ }.to change { membership.reload.desktop_notification_level }.from("mention").to("never")+ end++ it "can change mobile notification level" do+ chat_page.visit_channel_settings(channel_1)+ membership = channel_1.membership_for(current_user)++ expect {+ find(".channel-settings-view__mobile-notification-level-selector").click+ find(+ ".channel-settings-view__mobile-notification-level-selector [data-name='Never']",+ ).click+ expect(page).to have_content(I18n.t("js.chat.settings.saved"))+ }.to change { membership.reload.mobile_notification_level }.from("mention").to("never")+ end++ it "doesn’t show admin section" do+ chat_page.visit_channel_settings(channel_1)++ expect(page).to have_no_content(I18n.t("js.chat.settings.admin_title"))+ end++ context "as an admin" do+ before { sign_in(Fabricate(:admin)) }++ it "shows admin section" do+ chat_page.visit_channel_settings(channel_1)++ expect(page).to have_content(I18n.t("js.chat.settings.admin_title"))+ end++ it "can change auto join setting" do+ chat_page.visit_channel_settings(channel_1)++ expect {+ find(".channel-settings-view__auto-join-selector").click+ find(".channel-settings-view__auto-join-selector [data-name='Yes']").click+ find("#dialog-holder .btn-primary").click+ expect(page).to have_content(I18n.t("js.chat.settings.saved"))+ }.to change { channel_1.reload.auto_join_users }.from(false).to(true)+ end++ it "can change allow channel wide mentions" do+ chat_page.visit_channel_settings(channel_1)++ expect {+ find(".channel-settings-view__channel-wide-mentions-selector").click+ find(".channel-settings-view__channel-wide-mentions-selector [data-name='No']").click+ expect(page).to have_content(I18n.t("js.chat.settings.saved"))+ }.to change { channel_1.reload.allow_channel_wide_mentions }.from(true).to(false)+ end++ it "can close channel" do+ chat_page.visit_channel_settings(channel_1)++ expect {+ click_button(I18n.t("js.chat.channel_settings.close_channel"))+ find("#chat-channel-toggle-btn").click+ expect(page).to have_content(I18n.t("js.chat.channel_status.closed_header"))+ }.to change { channel_1.reload.status }.from("open").to("closed")+ end++ it "can delete channel" do+ chat_page.visit_channel_settings(channel_1)++ click_button(I18n.t("js.chat.channel_settings.delete_channel"))+ fill_in("channel-delete-confirm-name", with: channel_1.title)+ find_button("chat-confirm-delete-channel", disabled: false).click+ expect(page).to have_content(I18n.t("js.chat.channel_delete.process_started"))+ end++ context "when confirmation name is wrong" do+ it "doesn’t delete submission" do+ chat_page.visit_channel_settings(channel_1)+ find(".delete-btn").click+ fill_in("channel-delete-confirm-name", with: channel_1.title + "wrong")++ expect(page).to have_button("chat-confirm-delete-channel", disabled: true)+ end+ end+ end+ end+ end+enddiff --git a/plugins/chat/spec/system/chat_channel_spec.rb b/plugins/chat/spec/system/chat_channel_spec.rbnew file mode 100644index 00000000000..b5b3d0fc6a3--- /dev/null+++ b/plugins/chat/spec/system/chat_channel_spec.rb@@ -0,0 +1,200 @@+# frozen_string_literal: true++RSpec.describe "Chat channel", type: :system, js: true do+ fab!(:current_user) { Fabricate(:user) }+ fab!(:channel_1) { Fabricate(:chat_channel) }+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: channel_1) }++ let(:chat) { PageObjects::Pages::Chat.new }+ let(:channel) { PageObjects::Pages::ChatChannel.new }++ before { chat_system_bootstrap }++ context "when sending a message" do+ before do+ channel_1.add(current_user)+ 50.times { Fabricate(:chat_message, chat_channel: channel_1) }+ sign_in(current_user)+ end++ it "loads most recent messages" do+ unloaded_message = Fabricate(:chat_message, chat_channel: channel_1)+ visit("/chat/message/#{message_1.id}")++ expect(channel).to have_no_loading_skeleton+ expect(page).to have_no_css("[data-id='#{unloaded_message.id}']")++ find(".chat-composer-input").fill_in(with: "test message")+ find(".send-btn").click++ expect(channel).to have_no_loading_skeleton+ expect(page).to have_css("[data-id='#{unloaded_message.id}']")+ end+ end++ context "when clicking the arrow button" do+ before do+ channel_1.add(current_user)+ 50.times { Fabricate(:chat_message, chat_channel: channel_1) }+ sign_in(current_user)+ end++ it "jumps to the bottom of the channel" do+ unloaded_message = Fabricate(:chat_message, chat_channel: channel_1)+ visit("/chat/message/#{message_1.id}")++ expect(channel).to have_no_loading_skeleton+ expect(page).to have_no_css("[data-id='#{unloaded_message.id}']")++ find(".chat-scroll-to-bottom").click++ expect(channel).to have_no_loading_skeleton+ expect(page).to have_css("[data-id='#{unloaded_message.id}']")+ end+ end++ context "when a new message is created" do+ fab!(:other_user) { Fabricate(:user) }++ before do+ channel_1.add(other_user)+ channel_1.add(current_user)+ 50.times { Fabricate(:chat_message, chat_channel: channel_1) }+ sign_in(current_user)+ end++ it "doesn’t scroll the pane" do+ visit("/chat/message/#{message_1.id}")++ new_message =+ Chat::ChatMessageCreator.create(+ chat_channel: channel_1,+ user: other_user,+ content: "this is fine",+ ).chat_message++ expect(page).to have_no_content(new_message.message)+ end+ end++ context "when a message contains mentions" do+ fab!(:other_user) { Fabricate(:user) }++ before do+ channel_1.add(other_user)+ channel_1.add(current_user)+ Fabricate(+ :chat_message,+ chat_channel: channel_1,+ message: "hello @here @all @#{current_user.username} @#{other_user.username} @unexisting",+ user: other_user,+ )+ sign_in(current_user)+ end++ it "highlights the mentions" do+ chat.visit_channel(channel_1)++ expect(page).to have_selector(".mention.highlighted.valid-mention", text: "@here")+ expect(page).to have_selector(".mention.highlighted.valid-mention", text: "@all")+ expect(page).to have_selector(+ ".mention.highlighted.valid-mention",+ text: "@#{current_user.username}",+ )+ expect(page).to have_selector(".mention", text: "@#{other_user.username}")+ expect(page).to have_selector(".mention", text: "@unexisting")+ end+ end++ context "when reply is right under" do+ fab!(:other_user) { Fabricate(:user) }++ before do+ Fabricate(:chat_message, in_reply_to: message_1, user: other_user, chat_channel: channel_1)+ channel_1.add(other_user)+ channel_1.add(current_user)+ sign_in(current_user)+ end++ it "doesn’t show the reply-to line" do+ chat.visit_channel(channel_1)++ expect(page).to have_no_selector(".chat-reply__excerpt")+ end+ end++ context "when reply is not directly connected" do+ fab!(:other_user) { Fabricate(:user) }++ before do+ Fabricate(:chat_message, user: other_user, chat_channel: channel_1)+ Fabricate(:chat_message, in_reply_to: message_1, user: other_user, chat_channel: channel_1)+ channel_1.add(other_user)+ channel_1.add(current_user)+ sign_in(current_user)+ end++ it "shows the reply-to line" do+ chat.visit_channel(channel_1)++ expect(page).to have_selector(".chat-reply__excerpt")+ end+ end++ context "when messages are separated by a day" do+ before do+ Fabricate(:chat_message, chat_channel: channel_1, created_at: 2.days.ago)++ channel_1.add(current_user)+ sign_in(current_user)+ end++ it "shows a date separator" do+ chat.visit_channel(channel_1)++ expect(page).to have_selector(".first-daily-message", text: "Today")+ end+ end++ context "when visiting another channel" do+ fab!(:channel_2) { Fabricate(:chat_channel) }++ before do+ channel_1.add(current_user)+ channel_2.add(current_user)+ sign_in(current_user)+ end++ it "resets message selection" do+ chat.visit_channel(channel_1)+ channel.select_message(message_1)++ expect(page).to have_css(".chat-selection-management")++ chat.visit_channel(channel_2)++ expect(page).to have_no_css(".chat-selection-management")+ end+ end++ context "when a message contains code fence" do+ fab!(:message_2) { Fabricate(:chat_message, chat_channel: channel_1, message: <<~MESSAGE) }+ Here's a message with code highlighting++ \`\`\`ruby+ Widget.triangulate(arg: "test")+ \`\`\`+ MESSAGE++ before do+ channel_1.add(current_user)+ sign_in(current_user)+ end++ it "adds the correct lang" do+ chat.visit_channel(channel_1)++ expect(page).to have_selector("code.lang-ruby")+ end+ end+enddiff --git a/plugins/chat/spec/system/chat_composer_spec.rb b/plugins/chat/spec/system/chat_composer_spec.rbnew file mode 100644index 00000000000..dc7a4f9b8c2--- /dev/null+++ b/plugins/chat/spec/system/chat_composer_spec.rb@@ -0,0 +1,119 @@+# frozen_string_literal: true++RSpec.describe "Chat composer", type: :system, js: true do+ fab!(:current_user) { Fabricate(:user) }+ fab!(:channel_1) { Fabricate(:chat_channel) }+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: channel_1) }++ let(:chat) { PageObjects::Pages::Chat.new }+ let(:channel) { PageObjects::Pages::ChatChannel.new }++ before { chat_system_bootstrap }++ xit "it stores draft in replies" do+ end++ xit "it stores draft" do+ end++ context "when replying to a message" do+ before do+ channel_1.add(current_user)+ sign_in(current_user)+ end++ it "adds the reply indicator to the composer" do+ chat.visit_channel(channel_1)+ channel.reply_to(message_1)++ expect(page).to have_selector(+ ".chat-composer-message-details .chat-reply__username",+ text: message_1.user.username,+ )+ end+ end++ context "when editing a message" do+ fab!(:message_2) { Fabricate(:chat_message, chat_channel: channel_1, user: current_user) }++ before do+ channel_1.add(current_user)+ sign_in(current_user)+ end++ it "adds the edit indicator" do+ chat.visit_channel(channel_1)+ channel.edit_message(message_2)++ expect(page).to have_selector(+ ".chat-composer-message-details .chat-reply__username",+ text: current_user.username,+ )+ expect(find(".chat-composer-input").value).to eq(message_2.message)+ end++ context "when pressing escape" do+ it "cancels editing" do+ chat.visit_channel(channel_1)+ channel.edit_message(message_2)+ find(".chat-composer-input").send_keys(:escape)++ expect(page).to have_no_selector(".chat-composer-message-details .chat-reply__username")+ end+ end+ end++ context "when adding an emoji through the picker" do+ before do+ channel_1.add(current_user)+ sign_in(current_user)+ end++ it "adds the emoji to the composer" do+ chat.visit_channel(channel_1)+ find(".chat-composer-dropdown__trigger-btn").click+ find(".chat-composer-dropdown__action-btn.emoji").click+ find("[data-emoji='grimacing']").click(wait: 0.5)++ expect(find(".chat-composer-input").value).to eq(":grimacing:")+ end+ end++ context "when adding an emoji through the autocomplete" do+ before do+ channel_1.add(current_user)+ sign_in(current_user)+ end++ it "adds the emoji to the composer" do+ chat.visit_channel(channel_1)+ find(".chat-composer-input").fill_in(with: ":gri")+ find(".emoji-shortname", text: "grimacing").click++ expect(find(".chat-composer-input").value).to eq(":grimacing: ")+ end+ end++ context "when typing on keyboard" do+ before do+ channel_1.add(current_user)+ sign_in(current_user)+ end++ it "propagates keys to composer" do+ chat.visit_channel(channel_1)++ find("body").send_keys("b")++ expect(find(".chat-composer-input").value).to eq("b")++ find("body").send_keys("b")++ expect(find(".chat-composer-input").value).to eq("bb")++ find("body").send_keys(:enter) # special case++ expect(find(".chat-composer-input").value).to eq("bb")+ end+ end+enddiff --git a/plugins/chat/spec/system/closed_channel_spec.rb b/plugins/chat/spec/system/closed_channel_spec.rbnew file mode 100644index 00000000000..7237db225fe--- /dev/null+++ b/plugins/chat/spec/system/closed_channel_spec.rb@@ -0,0 +1,62 @@+# frozen_string_literal: true++RSpec.describe "Closed channel", type: :system, js: true do+ fab!(:channel_1) { Fabricate(:chat_channel) }++ let(:chat) { PageObjects::Pages::Chat.new }+ let(:channel) { PageObjects::Pages::ChatChannel.new }++ before { chat_system_bootstrap }++ context "when regular user" do+ fab!(:current_user) { Fabricate(:user) }++ before do+ channel_1.add(current_user)+ sign_in(current_user)+ end++ it "shows the closed status" do+ channel_1.closed!(Discourse.system_user)+ chat.visit_channel_settings(channel_1)+ chat.visit_channel(channel_1)++ expect(page).to have_content(I18n.t("js.chat.channel_status.closed_header"))+ end++ it "disables the composer" do+ channel_1.closed!(Discourse.system_user)+ chat.visit_channel_settings(channel_1)+ chat.visit_channel(channel_1)++ expect(page).to have_field(+ placeholder:+ I18n.t(+ "js.chat.placeholder_new_message_disallowed",+ status: I18n.t("js.chat.channel_status.closed").downcase,+ ),+ disabled: true,+ )+ end+ end++ context "when admin" do+ fab!(:current_user) { Fabricate(:admin) }++ before do+ channel_1.add(current_user)+ sign_in(current_user)+ end++ it "disables the composer" do+ channel_1.closed!(Discourse.system_user)+ chat.visit_channel_settings(channel_1)+ chat.visit_channel(channel_1)++ expect(page).to have_no_field(+ placeholder: I18n.t("js.chat.placeholder_new_message_disallowed"),+ disabled: true,+ )+ end+ end+enddiff --git a/plugins/chat/spec/system/create_channel_spec.rb b/plugins/chat/spec/system/create_channel_spec.rbnew file mode 100644index 00000000000..6f295d77d7d--- /dev/null+++ b/plugins/chat/spec/system/create_channel_spec.rb@@ -0,0 +1,111 @@+# frozen_string_literal: true++RSpec.describe "Create channel", type: :system, js: true do+ fab!(:current_admin_user) { Fabricate(:admin) }+ fab!(:category_1) { Fabricate(:category) }++ let(:chat_page) { PageObjects::Pages::Chat.new }++ before do+ chat_system_bootstrap+ sign_in(current_admin_user)+ end++ context "when can create channel" do+ context "when selecting a category" do+ it "shows access hint" do+ visit("/chat")+ find(".new-channel-btn").click+ find(".category-chooser").click+ find(".category-row[data-value=\"#{category_1.id}\"]").click++ expect(find(".create-channel-hint")).to have_content(Group[:everyone].name)+ end++ context "when category is private" do+ fab!(:group_1) { Fabricate(:group) }+ fab!(:private_category_1) { Fabricate(:private_category, group: group_1) }++ it "shows access hint when selecting the category" do+ visit("/chat")+ find(".new-channel-btn").click+ find(".category-chooser").click+ find(".category-row[data-value=\"#{private_category_1.id}\"]").click++ expect(find(".create-channel-hint")).to have_content(group_1.name)+ end++ context "when category is a child" do+ fab!(:group_2) { Fabricate(:group) }+ fab!(:child_category) do+ Fabricate(:private_category, parent_category_id: private_category_1.id, group: group_2)+ end++ it "shows access hint when selecting the category" do+ visit("/chat")+ find(".new-channel-btn").click+ find(".category-chooser").click+ find(".category-row[data-value=\"#{child_category.id}\"]").click++ expect(find(".create-channel-hint")).to have_content(group_2.name)+ end+ end+ end+ end++ context "when category has a malicous group name" do+ fab!(:group_1) do+ group = Group.new(name: "<script>e</script>")+ group.save(validate: false)+ group+ end+ fab!(:private_category_1) { Fabricate(:private_category, group: group_1) }++ it "escapes the group name" do+ visit("/chat")+ find(".new-channel-btn").click+ find(".category-chooser").click+ find(".category-row[data-value=\"#{private_category_1.id}\"]").click++ expect(find(".create-channel-hint")["innerHTML"]).to include(+ "<script>e</script>",+ )+ end+ end++ context "when saving" do+ context "when error" do+ it "displays the error" do+ existing_channel = Fabricate(:chat_channel)+ visit("/chat")+ find(".new-channel-btn").click+ find(".category-chooser").click+ find(".category-row[data-value=\"#{existing_channel.chatable_id}\"]").click+ fill_in("channel-name", with: existing_channel.name)+ find(".create-channel-modal .create").click++ expect(page).to have_content(I18n.t("chat.errors.channel_exists_for_category"))+ end+ end++ context "when successful" do+ it "redirects to created channel" do+ visit("/chat")+ find(".new-channel-btn").click+ name = "Cats"+ find(".category-chooser").click+ find(".category-row[data-value=\"#{category_1.id}\"]").click+ fill_in("channel-name", with: name)+ fill_in("channel-description", with: "All kind of cute cats")+ find(".create-channel-modal .create").click++ expect(page).to have_content(name)+ created_channel = ChatChannel.find_by(chatable_id: category_1.id)+ expect(page).to have_current_path(+ chat.channel_path(created_channel.id, created_channel.slug),+ )+ end+ end+ end+ end+enddiff --git a/plugins/chat/spec/system/deleted_channel_spec.rb b/plugins/chat/spec/system/deleted_channel_spec.rbnew file mode 100644index 00000000000..60b95d5f7ea--- /dev/null+++ b/plugins/chat/spec/system/deleted_channel_spec.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++RSpec.describe "Deleted channel", type: :system, js: true do+ fab!(:channel_1) { Fabricate(:chat_channel) }++ let(:chat_page) { PageObjects::Pages::Chat.new }++ before do+ chat_system_bootstrap+ channel_1.destroy!+ sign_in(Fabricate(:user))+ end++ context "when visiting deleted channel" do+ it "redirects to homepage" do+ chat_page.visit_channel(channel_1)++ expect(page).to have_current_path("/latest")+ end+ end+enddiff --git a/plugins/chat/spec/system/edited_message_spec.rb b/plugins/chat/spec/system/edited_message_spec.rbnew file mode 100644index 00000000000..d642e6a1f02--- /dev/null+++ b/plugins/chat/spec/system/edited_message_spec.rb@@ -0,0 +1,33 @@+# frozen_string_literal: true++RSpec.describe "Edited message", type: :system, js: true do+ let(:chat_page) { PageObjects::Pages::Chat.new }+ let(:channel_page) { PageObjects::Pages::ChatChannel.new }++ fab!(:current_user) { Fabricate(:user) }+ fab!(:editing_user) { Fabricate(:user) }+ fab!(:channel_1) { Fabricate(:category_channel) }+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: channel_1, user: editing_user) }++ before do+ chat_system_bootstrap+ channel_1.add(current_user)+ channel_1.add(editing_user)+ sign_in(current_user)+ end++ context "when editing message" do+ it "shows as edited for all users" do+ chat_page.visit_channel(channel_1)++ using_session(editing_user.username) do+ sign_in(editing_user)+ chat_page.visit_channel(channel_1)+ channel_page.edit_message(message_1, "a different message")+ expect(page).to have_content(I18n.t("js.chat.edited"))+ end++ expect(page).to have_content(I18n.t("js.chat.edited"))+ end+ end+enddiff --git a/plugins/chat/spec/system/flag_message_spec.rb b/plugins/chat/spec/system/flag_message_spec.rbnew file mode 100644index 00000000000..8b40ba93cd8--- /dev/null+++ b/plugins/chat/spec/system/flag_message_spec.rb@@ -0,0 +1,44 @@+# frozen_string_literal: true++RSpec.describe "Flag message", type: :system, js: true do+ fab!(:current_user) { Fabricate(:user) }++ let(:chat) { PageObjects::Pages::Chat.new }+ let(:channel) { PageObjects::Pages::ChatChannel.new }++ before do+ chat_system_bootstrap+ sign_in(current_user)+ end++ context "when category channel" do+ fab!(:category_channel_1) { Fabricate(:category_channel) }+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: category_channel_1) }++ before { category_channel_1.add(current_user) }++ it "allows to flag a message" do+ chat.visit_channel(category_channel_1)+ channel.flag_message(message_1)++ expect(page).to have_css(".flag-modal")++ choose("radio_spam")+ click_button(I18n.t("js.chat.flagging.action"))++ expect(channel.message_by_id(message_1.id)).to have_css(".chat-message-info__flag")+ end+ end++ context "when direct message channel" do+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user]) }+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: dm_channel_1, user: current_user) }++ it "doesn’t allow to flag a message" do+ chat.visit_channel(dm_channel_1)+ channel.expand_message_actions(message_1)++ expect(page).to have_no_css("[data-value='flag']")+ end+ end+enddiff --git a/plugins/chat/spec/system/jit_messages_spec.rb b/plugins/chat/spec/system/jit_messages_spec.rbnew file mode 100644index 00000000000..4d7efc860c4--- /dev/null+++ b/plugins/chat/spec/system/jit_messages_spec.rb@@ -0,0 +1,63 @@+# frozen_string_literal: true++RSpec.describe "JIT messages", type: :system, js: true do+ fab!(:channel_1) { Fabricate(:chat_channel) }+ fab!(:current_user) { Fabricate(:user) }+ fab!(:other_user) { Fabricate(:user) }++ let(:chat) { PageObjects::Pages::Chat.new }++ before do+ channel_1.add(current_user)+ chat_system_bootstrap+ sign_in(current_user)+ end++ context "when mentioning a user not on the channel" do+ it "displays a mention warning" do+ chat.visit_channel(channel_1)+ find(".chat-composer-input").fill_in(with: "hi @#{other_user.username}")+ find(".send-btn").click++ expect(page).to have_content(+ I18n.t("js.chat.mention_warning.without_membership.one", username: other_user.username),+ )+ end+ end++ context "when mentioning a user who can’t access the channel" do+ fab!(:group_1) { Fabricate(:group) }+ fab!(:private_channel_1) { Fabricate(:private_category_channel, group: group_1) }++ before do+ group_1.add(current_user)+ private_channel_1.add(current_user)+ end++ it "displays a mention warning" do+ chat.visit_channel(private_channel_1)+ find(".chat-composer-input").fill_in(with: "hi @#{other_user.username}")+ find(".send-btn").click++ expect(page).to have_content(+ I18n.t("js.chat.mention_warning.cannot_see.one", username: other_user.username),+ )+ end+ end++ context "when mention a group" do+ context "when group can't be mentioned" do+ fab!(:group_1) { Fabricate(:group, mentionable_level: Group::ALIAS_LEVELS[:nobody]) }++ it "displays a mention warning" do+ chat.visit_channel(channel_1)+ find(".chat-composer-input").fill_in(with: "hi @#{group_1.name}")+ find(".send-btn").click++ expect(page).to have_content(+ I18n.t("js.chat.mention_warning.group_mentions_disabled.one", group_name: group_1.name),+ )+ end+ end+ end+enddiff --git a/plugins/chat/spec/system/list_channels/mobile_spec.rb b/plugins/chat/spec/system/list_channels/mobile_spec.rbnew file mode 100644index 00000000000..025adc640ff--- /dev/null+++ b/plugins/chat/spec/system/list_channels/mobile_spec.rb@@ -0,0 +1,106 @@+# frozen_string_literal: true++RSpec.describe "List channels | mobile", type: :system, js: true, mobile: true do+ fab!(:current_user) { Fabricate(:user) }++ let(:chat) { PageObjects::Pages::Chat.new }++ before do+ chat_system_bootstrap+ sign_in(current_user)+ end++ context "when channels present" do+ context "when category channels" do+ fab!(:category_channel_1) { Fabricate(:category_channel) }++ context "when member of the channel" do+ before { category_channel_1.add(current_user) }++ it "shows the channel in the correct section" do+ visit("/chat")+ expect(page.find(".public-channels")).to have_content(category_channel_1.name)+ end+ end++ context "when not member of the channel" do+ it "doesn’t show the channel" do+ visit("/chat")+ expect(page.find(".public-channels")).to have_no_content(category_channel_1.name)+ end+ end+ end++ context "when direct message channels" do+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user]) }+ fab!(:inaccessible_dm_channel_1) { Fabricate(:direct_message_channel) }++ context "when member of the channel" do+ it "shows the channel in the correct section" do+ visit("/chat")+ expect(page.find(".direct-message-channels")).to have_content(current_user.username)+ end+ end++ context "when not member of the channel" do+ it "doesn’t show the channel" do+ visit("/chat")+ expect(page).to have_no_content(inaccessible_dm_channel_1.title(current_user))+ end+ end+ end+ end++ context "when no category channels" do+ it "doesn’t show the section" do+ visit("/chat")+ expect(page).to have_no_css(".public-channels-section")+ end++ context "when user can create channels" do+ before { current_user.update!(admin: true) }++ it "shows the section" do+ visit("/chat")+ expect(page).to have_css(".public-channels-section")+ end+ end+ end++ context "when no direct message channels" do+ it "shows the section" do+ visit("/chat")+ expect(page).to have_css(".direct-message-channels-section")+ end+ end++ context "when chat disabled" do+ before { SiteSetting.chat_enabled = false }++ it "doesn’t show the sections" do+ visit("/chat")+ expect(page).to have_no_css(".public-channels-section")+ expect(page).to have_no_css(".direct-message-channels-section")+ end+ end++ context "when user has chat disabled" do+ before do+ SiteSetting.chat_enabled = false+ current_user.user_option.update!(chat_enabled: false)+ end++ it "doesn’t show the sections" do+ visit("/chat")+ expect(page).to have_no_css(".public-channels-section")+ expect(page).to have_no_css(".direct-message-channels-section")+ end+ end++ it "has a new dm channel button" do+ visit("/chat")+ find(".open-draft-channel-page-btn").click++ expect(page).to have_current_path("/chat/draft-channel")+ end+enddiff --git a/plugins/chat/spec/system/list_channels/no_sidebar_spec.rb b/plugins/chat/spec/system/list_channels/no_sidebar_spec.rbnew file mode 100644index 00000000000..8f23c39413f--- /dev/null+++ b/plugins/chat/spec/system/list_channels/no_sidebar_spec.rb@@ -0,0 +1,100 @@+# frozen_string_literal: true++RSpec.describe "List channels | no sidebar", type: :system, js: true do+ fab!(:current_user) { Fabricate(:user) }++ let(:chat) { PageObjects::Pages::Chat.new }++ before do+ SiteSetting.navigation_menu = "legacy"+ chat_system_bootstrap+ sign_in(current_user)+ end++ context "when channels present" do+ context "when category channels" do+ fab!(:category_channel_1) { Fabricate(:category_channel) }++ context "when member of the channel" do+ before { category_channel_1.add(current_user) }++ it "shows the channel in the correct section" do+ visit("/chat")+ expect(page.find(".public-channels")).to have_content(category_channel_1.title)+ end+ end++ context "when not member of the channel" do+ it "doesn’t show the channel" do+ visit("/chat")+ expect(page.find(".public-channels")).to have_no_content(category_channel_1.title)+ end+ end+ end++ context "when direct message channels" do+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user]) }+ fab!(:inaccessible_dm_channel_1) { Fabricate(:direct_message_channel) }++ context "when member of the channel" do+ it "shows the channel in the correct section" do+ visit("/chat")+ expect(page.find(".direct-message-channels")).to have_content(current_user.username)+ end+ end++ context "when not member of the channel" do+ it "doesn’t show the channel" do+ visit("/chat")+ expect(page).to have_no_content(inaccessible_dm_channel_1.title(current_user))+ end+ end+ end+ end++ context "when no category channels" do+ it "doesn’t show the section" do+ visit("/chat")+ expect(page).to have_no_css(".public-channels-section")+ end++ context "when user can create channels" do+ before { current_user.update!(admin: true) }++ it "shows the section" do+ visit("/chat")+ expect(page).to have_css(".public-channels-section")+ end+ end+ end++ context "when no direct message channels" do+ it "shows the section" do+ visit("/chat")+ expect(page).to have_css(".direct-message-channels-section")+ end+ end++ context "when chat disabled" do+ before { SiteSetting.chat_enabled = false }++ it "doesn’t show the sections" do+ visit("/chat")+ expect(page).to have_no_css(".public-channels-section")+ expect(page).to have_no_css(".direct-message-channels-section")+ end+ end++ context "when user has chat disabled" do+ before do+ SiteSetting.chat_enabled = false+ current_user.user_option.update!(chat_enabled: false)+ end++ it "doesn’t show the sections" do+ visit("/chat")+ expect(page).to have_no_css(".public-channels-section")+ expect(page).to have_no_css(".direct-message-channels-section")+ end+ end+enddiff --git a/plugins/chat/spec/system/list_channels/sidebar_spec.rb b/plugins/chat/spec/system/list_channels/sidebar_spec.rbnew file mode 100644index 00000000000..3ebc9da89b2--- /dev/null+++ b/plugins/chat/spec/system/list_channels/sidebar_spec.rb@@ -0,0 +1,129 @@+# frozen_string_literal: true++RSpec.describe "List channels | sidebar", type: :system, js: true do+ fab!(:current_user) { Fabricate(:user) }++ let(:chat) { PageObjects::Pages::Chat.new }++ before do+ chat_system_bootstrap+ SiteSetting.navigation_menu = "sidebar"+ sign_in(current_user)+ end++ context "when channels present" do+ context "when category channel" do+ fab!(:category_channel_1) { Fabricate(:category_channel) }++ context "when member of the channel" do+ before do+ category_channel_1.add(current_user)+ visit("/")+ end++ it "shows the channel in the correct section" do+ expect(page.find(".sidebar-section-chat-channels")).to have_content(+ category_channel_1.name,+ )+ end++ it "doesn’t show the core channels list" do+ expect(page).to have_no_selector(".channels-list")+ end+ end++ context "when not member of the channel" do+ before { visit("/") }++ it "doesn’t show the channel" do+ expect(page).to have_no_content(category_channel_1.name)+ end+ end+ end++ context "when direct message channels" do+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user]) }+ fab!(:inaccessible_dm_channel_1) { Fabricate(:direct_message_channel) }++ context "when member of the channel" do+ before { visit("/") }++ it "shows the channel in the correct section" do+ expect(page.find(".sidebar-section-chat-dms")).to have_content(current_user.username)+ end+ end++ context "when not member of the channel" do+ before { visit("/") }++ it "doesn’t show the channel" do+ expect(page).to have_no_content(inaccessible_dm_channel_1.title(current_user))+ end+ end+ end+ end++ context "when no category channels" do+ it "doesn’t show the section" do+ visit("/")+ expect(page).to have_no_css(".sidebar-section-chat-channels")+ end++ context "when user can create channels" do+ before { current_user.update!(admin: true) }++ it "shows the section" do+ visit("/")+ expect(page).to have_css(".sidebar-section-chat-channels")+ end+ end+ end++ context "when no direct message channels" do+ before { visit("/") }++ it "shows the section" do+ expect(page).to have_css(".sidebar-section-chat-dms")+ end+ end++ context "when user can’t chat" do+ before do+ SiteSetting.chat_enabled = false+ visit("/")+ end++ it "doesn’t show the sections" do+ expect(page).to have_no_css(".sidebar-section-chat-channels")+ expect(page).to have_no_css(".sidebar-section-chat-dms")+ end+ end++ context "when user has chat disabled" do+ before do+ SiteSetting.chat_enabled = false+ current_user.user_option.update!(chat_enabled: false)+ visit("/")+ end++ it "doesn’t show the sections" do+ expect(page).to have_no_css(".sidebar-section-chat-channels")+ expect(page).to have_no_css(".sidebar-section-chat-dms")+ end+ end++ context "when leaving a channel" do+ context "when dm channel" do+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user]) }++ it "removes it from the sidebar" do+ visit("/")++ find(".sidebar-row.channel-#{dm_channel_1.id}").hover+ find(".sidebar-row.channel-#{dm_channel_1.id} .sidebar-section-hover-button").click++ expect(page).to have_no_selector(".sidebar-row.channel-#{dm_channel_1.id}")+ end+ end+ end+enddiff --git a/plugins/chat/spec/system/message_notifications_mobile_spec.rb b/plugins/chat/spec/system/message_notifications_mobile_spec.rbnew file mode 100644index 00000000000..da806c36920--- /dev/null+++ b/plugins/chat/spec/system/message_notifications_mobile_spec.rb@@ -0,0 +1,195 @@+# frozen_string_literal: true++RSpec.describe "Message notifications - mobile", type: :system, js: true, mobile: true do+ fab!(:current_user) { Fabricate(:user) }++ let!(:chat_page) { PageObjects::Pages::Chat.new }+ let!(:chat_channel_page) { PageObjects::Pages::ChatChannel.new }++ before do+ SiteSetting.navigation_menu = "sidebar"+ chat_system_bootstrap+ end++ def create_message(text: "this is fine", channel:, creator: Fabricate(:user))+ using_session(creator.username) do+ sign_in(creator)+ chat_page.visit_channel(channel)+ chat_channel_page.send_message(text)+ expect(chat_channel_page).to have_message(text: text)+ end+ end++ context "as a user" do+ before { sign_in(current_user) }++ context "when on homepage" do+ context "with public channel" do+ fab!(:channel_1) { Fabricate(:category_channel) }+ fab!(:channel_2) { Fabricate(:category_channel) }+ fab!(:user_1) { Fabricate(:user) }++ before { channel_1.add(user_1) }++ context "when not member of the channel" do+ context "when a message is created" do+ it "doesn't show anything" do+ visit("/chat")+ create_message(channel: channel_1, creator: user_1)++ expect(page).to have_no_css(".chat-header-icon .chat-channel-unread-indicator")+ expect(page).to have_no_css(+ ".chat-channel-row[data-chat-channel-id=\"#{channel_1.id}\"]",+ )+ end+ end+ end++ context "when member of the channel" do+ before { channel_1.add(current_user) }++ context "when user is in DnD" do+ before do+ Jobs.run_immediately!+ Fabricate(+ :do_not_disturb_timing,+ user: current_user,+ starts_at: 1.week.ago,+ ends_at: 1.week.from_now,+ )+ end++ it "doesn’t show indicator in header" do+ visit("/chat")+ create_message(channel: channel_1, creator: user_1)++ expect(page).to have_css(".do-not-disturb-background")+ expect(page).to have_no_css(".chat-header-icon .chat-channel-unread-indicator")+ end+ end++ context "when channel is muted" do+ before { channel_1.membership_for(current_user).update!(muted: true) }++ context "when a message is created" do+ it "doesn't show anything" do+ visit("/chat")+ create_message(channel: channel_1, creator: user_1)++ expect(page).to have_no_css(".chat-header-icon .chat-channel-unread-indicator")+ expect(page).to have_no_css(+ ".chat-channel-row[data-chat-channel-id=\"#{channel_1.id}\"] .chat-channel-unread-indicator",+ )+ end+ end+ end++ context "when a message is created" do+ it "correctly renders notifications" do+ visit("/chat")+ create_message(channel: channel_1, creator: user_1)++ expect(page).to have_css(".chat-header-icon .chat-channel-unread-indicator", text: "")+ expect(page).to have_css(+ ".chat-channel-row[data-chat-channel-id=\"#{channel_1.id}\"] .chat-channel-unread-indicator",+ text: 1,+ )+ end+ end++ context "when a message with mentions is created" do+ it "correctly renders notifications" do+ visit("/chat")+ create_message(+ channel: channel_1,+ creator: user_1,+ text: "hello @#{current_user.username} what's up?",+ )++ expect(page).to have_css(".chat-header-icon .chat-channel-unread-indicator")+ expect(page).to have_css(+ ".chat-channel-row[data-chat-channel-id=\"#{channel_1.id}\"] .chat-channel-unread-indicator",+ text: 1,+ )+ end+ end+ end+ end++ context "with dm channel" do+ fab!(:current_user) { Fabricate(:admin) }+ fab!(:user_1) { Fabricate(:user) }+ fab!(:user_2) { Fabricate(:user) }++ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user, user_1]) }+ fab!(:dm_channel_2) { Fabricate(:direct_message_channel, users: [current_user, user_2]) }++ context "when a message is created" do+ it "correctly renders notifications" do+ visit("/chat")+ create_message(channel: dm_channel_1, creator: user_1)++ expect(page).to have_css(".chat-header-icon .chat-channel-unread-indicator", text: "1")+ expect(page).to have_css(+ ".chat-channel-row[data-chat-channel-id=\"#{dm_channel_1.id}\"] .chat-channel-unread-indicator",+ )++ create_message(channel: dm_channel_1, creator: user_1)++ expect(page).to have_css(".chat-header-icon .chat-channel-unread-indicator", text: "2")+ end++ it "reorders channels" do+ visit("/chat")++ expect(page).to have_css(+ ".chat-channel-row:nth-child(1)[data-chat-channel-id=\"#{dm_channel_1.id}\"]",+ )+ expect(page).to have_css(+ ".chat-channel-row:nth-child(2)[data-chat-channel-id=\"#{dm_channel_2.id}\"]",+ )+ create_message(channel: dm_channel_2, creator: user_2)++ expect(page).to have_css(+ ".chat-channel-row:nth-child(1)[data-chat-channel-id=\"#{dm_channel_2.id}\"]",+ )+ expect(page).to have_css(+ ".chat-channel-row:nth-child(2)[data-chat-channel-id=\"#{dm_channel_1.id}\"]",+ )+ end+ end+ end++ context "with dm and public channel" do+ fab!(:current_user) { Fabricate(:admin) }+ fab!(:user_1) { Fabricate(:user) }+ fab!(:channel_1) { Fabricate(:category_channel) }+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user, user_1]) }++ before do+ channel_1.add(user_1)+ channel_1.add(current_user)+ end++ context "when messages are created" do+ it "correctly renders notifications" do+ visit("/chat")+ create_message(channel: channel_1, creator: user_1)++ expect(page).to have_css(".chat-header-icon .chat-channel-unread-indicator", text: "")+ expect(page).to have_css(+ ".chat-channel-row[data-chat-channel-id=\"#{channel_1.id}\"] .chat-channel-unread-indicator",+ )++ create_message(channel: dm_channel_1, creator: user_1)++ expect(page).to have_css(+ ".chat-channel-row[data-chat-channel-id=\"#{dm_channel_1.id}\"] .chat-channel-unread-indicator",+ )+ expect(page).to have_css(".chat-header-icon .chat-channel-unread-indicator", text: "1")+ end+ end+ end+ end+ end+enddiff --git a/plugins/chat/spec/system/message_notifications_with_sidebar_spec.rb b/plugins/chat/spec/system/message_notifications_with_sidebar_spec.rbnew file mode 100644index 00000000000..b677eb5d732--- /dev/null+++ b/plugins/chat/spec/system/message_notifications_with_sidebar_spec.rb@@ -0,0 +1,183 @@+# frozen_string_literal: true++RSpec.describe "Message notifications - with sidebar", type: :system, js: true do+ fab!(:current_user) { Fabricate(:user) }++ let!(:chat_page) { PageObjects::Pages::Chat.new }+ let!(:chat_channel_page) { PageObjects::Pages::ChatChannel.new }++ before do+ SiteSetting.navigation_menu = "sidebar"+ chat_system_bootstrap+ end++ def create_message(text: "this is fine", channel:, creator: Fabricate(:user))+ using_session(creator.username) do+ sign_in(creator)+ chat_page.visit_channel(channel)+ chat_channel_page.send_message(text)+ expect(chat_channel_page).to have_message(text: text)+ end+ end++ context "as a user" do+ before { sign_in(current_user) }++ context "when on homepage" do+ context "with public channel" do+ fab!(:channel_1) { Fabricate(:category_channel) }+ fab!(:channel_2) { Fabricate(:category_channel) }+ fab!(:user_1) { Fabricate(:user) }++ before { channel_1.add(user_1) }++ context "when not member of the channel" do+ context "when a message is created" do+ it "doesn't show anything" do+ visit("/")+ create_message(channel: channel_1, creator: user_1)++ expect(page).to have_no_css(".chat-header-icon .chat-channel-unread-indicator")+ expect(page).to have_no_css(".sidebar-row.channel-#{channel_1.id}")+ end+ end+ end++ context "when member of the channel" do+ before { channel_1.add(current_user) }++ context "when user is in DnD" do+ before do+ Jobs.run_immediately!+ Fabricate(+ :do_not_disturb_timing,+ user: current_user,+ starts_at: 1.week.ago,+ ends_at: 1.week.from_now,+ )+ end++ it "doesn’t show indicator in header" do+ visit("/")+ create_message(channel: channel_1, creator: user_1)++ expect(page).to have_css(".do-not-disturb-background")+ expect(page).to have_no_css(".chat-header-icon .chat-channel-unread-indicator")+ end+ end++ context "when channel is muted" do+ before { channel_1.membership_for(current_user).update!(muted: true) }++ context "when a message is created" do+ it "doesn't show anything" do+ visit("/")+ create_message(channel: channel_1, creator: user_1)++ expect(page).to have_no_css(".chat-header-icon .chat-channel-unread-indicator")+ expect(page).to have_no_css(".sidebar-row.channel-#{channel_1.id} .unread")+ end+ end+ end++ context "when a message is created" do+ it "correctly renders notifications" do+ visit("/")+ create_message(channel: channel_1, creator: user_1)++ expect(page).to have_css(".chat-header-icon .chat-channel-unread-indicator", text: "")+ expect(page).to have_css(".sidebar-row.channel-#{channel_1.id} .unread")+ end+ end++ context "when a message with mentions is created" do+ it "correctly renders notifications" do+ visit("/")+ create_message(+ channel: channel_1,+ creator: user_1,+ text: "hello @#{current_user.username} what's up?",+ )++ expect(page).to have_css(+ ".chat-header-icon .chat-channel-unread-indicator.urgent",+ text: "1",+ )+ expect(page).to have_css(".sidebar-row.channel-#{channel_1.id} .icon.urgent")+ end+ end+ end+ end++ context "with dm channel" do+ fab!(:current_user) { Fabricate(:admin) }+ fab!(:user_1) { Fabricate(:user) }+ fab!(:user_2) { Fabricate(:user) }++ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user, user_1]) }+ fab!(:dm_channel_2) { Fabricate(:direct_message_channel, users: [current_user, user_2]) }++ context "when a message is created" do+ it "correctly renders notifications" do+ visit("/")+ create_message(channel: dm_channel_1, creator: user_1)++ expect(page).to have_css(".chat-header-icon .chat-channel-unread-indicator", text: "1")+ expect(page).to have_css(".sidebar-row.channel-#{dm_channel_1.id} .icon.urgent")++ create_message(channel: dm_channel_1, creator: user_1)++ expect(page).to have_css(".chat-header-icon .chat-channel-unread-indicator", text: "2")+ end++ it "reorders channels" do+ visit("/chat")++ expect(page).to have_css(+ "#sidebar-section-content-chat-dms .sidebar-section-link-wrapper:nth-child(1) .channel-#{dm_channel_1.id}",+ )+ expect(page).to have_css(+ "#sidebar-section-content-chat-dms .sidebar-section-link-wrapper:nth-child(2) .channel-#{dm_channel_2.id}",+ )++ create_message(channel: dm_channel_2, creator: user_2)++ expect(page).to have_css(+ "#sidebar-section-content-chat-dms .sidebar-section-link-wrapper:nth-child(1) .channel-#{dm_channel_2.id}",+ )+ expect(page).to have_css(+ "#sidebar-section-content-chat-dms .sidebar-section-link-wrapper:nth-child(2) .channel-#{dm_channel_1.id}",+ )+ end+ end+ end++ context "with dm and public channel" do+ fab!(:current_user) { Fabricate(:admin) }+ fab!(:user_1) { Fabricate(:user) }+ fab!(:channel_1) { Fabricate(:category_channel) }+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user, user_1]) }++ before do+ channel_1.add(user_1)+ channel_1.add(current_user)+ end++ context "when messages are created" do+ it "correctly renders notifications" do+ visit("/")+ create_message(channel: channel_1, creator: user_1)++ expect(page).to have_css(".chat-header-icon .chat-channel-unread-indicator", text: "")+ expect(page).to have_css(".sidebar-row.channel-#{channel_1.id} .unread")++ create_message(channel: dm_channel_1, creator: user_1)++ expect(page).to have_css(".sidebar-row.channel-#{dm_channel_1.id} .icon.urgent")+ expect(page).to have_css(".chat-header-icon .chat-channel-unread-indicator", text: "1")+ end+ end+ end+ end+ end+enddiff --git a/plugins/chat/spec/system/move_message_to_channel_spec.rb b/plugins/chat/spec/system/move_message_to_channel_spec.rbnew file mode 100644index 00000000000..e605ce2b87b--- /dev/null+++ b/plugins/chat/spec/system/move_message_to_channel_spec.rb@@ -0,0 +1,95 @@+# frozen_string_literal: true++RSpec.describe "Move message to channel", type: :system, js: true do+ let(:chat) { PageObjects::Pages::Chat.new }+ let(:channel) { PageObjects::Pages::ChatChannel.new }++ before { chat_system_bootstrap }++ context "when user" do+ fab!(:current_user) { Fabricate(:user) }+ fab!(:channel_1) { Fabricate(:chat_channel) }+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: channel_1, user: current_user) }++ before do+ sign_in(current_user)+ channel_1.add(current_user)+ end++ it "is not available" do+ chat.visit_channel(channel_1)+ channel.select_message(message_1)++ expect(page).to have_no_content(I18n.t("js.chat.selection.move_selection_to_channel"))+ end++ context "when can moderate channel" do+ fab!(:group_1) { Fabricate(:group) }+ fab!(:channel_1) { Fabricate(:private_category_channel, group: group_1) }+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: channel_1, user: current_user) }++ before do+ SiteSetting.enable_category_group_moderation = true+ group_1.add(current_user)+ channel_1.add(current_user)+ channel_1.chatable.update!(reviewable_by_group_id: group_1.id)+ end++ it "is available" do+ chat.visit_channel(channel_1)+ channel.select_message(message_1)++ expect(page).to have_content(I18n.t("js.chat.selection.move_selection_to_channel"))+ end+ end+ end++ context "when admin" do+ fab!(:current_admin_user) { Fabricate(:admin) }++ before { sign_in(current_admin_user) }++ context "when dm channel" do+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_admin_user]) }+ fab!(:message_1) do+ Fabricate(:chat_message, chat_channel: dm_channel_1, user: current_admin_user)+ end++ it "is not available" do+ chat.visit_channel(dm_channel_1)+ channel.select_message(message_1)++ expect(page).to have_no_content(I18n.t("js.chat.selection.move_selection_to_channel"))+ end+ end++ context "when category channel" do+ fab!(:channel_1) { Fabricate(:chat_channel) }+ fab!(:channel_2) { Fabricate(:chat_channel) }+ fab!(:message_1) do+ Fabricate(:chat_message, chat_channel: channel_1, user: current_admin_user)+ end++ before do+ channel_1.add(current_admin_user)+ channel_2.add(current_admin_user)+ end++ it "moves the message" do+ chat.visit_channel(channel_1)+ channel.select_message(message_1)+ click_button(I18n.t("js.chat.selection.move_selection_to_channel"))+ find(".chat-move-message-channel-chooser").click+ find("[data-value='#{channel_2.id}']").click+ click_button(I18n.t("js.chat.move_to_channel.confirm_move"))++ expect(page).to have_content(message_1.message)++ chat.visit_channel(channel_1)++ expect(page).to have_no_content(message_1.message)+ expect(page).to have_content(I18n.t("js.chat.deleted"))+ end+ end+ end+enddiff --git a/plugins/chat/spec/system/navigation_spec.rb b/plugins/chat/spec/system/navigation_spec.rbindex 8744f6b5849..50f83a87073 100644--- a/plugins/chat/spec/system/navigation_spec.rb+++ b/plugins/chat/spec/system/navigation_spec.rb@@ -28,8 +28,8 @@ RSpec.describe "Navigation", type: :system, js: true doendcontext "when clicking chat icon on mobile and is viewing channel" do- it "navigates to index" do- visit("/chat?mobile_view=1")+ it "navigates to index", mobile: true do+ visit("/chat")chat_page.visit_channel(category_channel_2)chat_page.open_from_header@@ -152,9 +152,7 @@ RSpec.describe "Navigation", type: :system, js: true doendcontext "when sidebar is configured as the navigation menu" do- before do- SiteSetting.navigation_menu = "sidebar"- end+ before { SiteSetting.navigation_menu = "sidebar" }context "when opening channel from sidebar with drawer preferred" doit "opens channel in drawer" dodiff --git a/plugins/chat/spec/system/page_objects/chat/chat.rb b/plugins/chat/spec/system/page_objects/chat/chat.rbindex 67ebe55f416..c9e42661808 100644--- a/plugins/chat/spec/system/page_objects/chat/chat.rb+++ b/plugins/chat/spec/system/page_objects/chat/chat.rb@@ -4,20 +4,47 @@ module PageObjectsmodule Pagesclass Chat < PageObjects::Pages::Basedef open_from_header- find(".open-chat").click+ find(".chat-header-icon").clickenddef openvisit("/chat")end- def visit_channel(channel)- visit(channel.url)+ def visit_channel(channel, mobile: false)+ visit(channel.url + (mobile ? "?mobile_view=1" : ""))+ has_no_css?(".chat-skeleton")+ end++ def visit_channel_settings(channel)+ visit(channel.url + "/info/settings")+ end++ def visit_channel_about(channel)+ visit(channel.url + "/info/about")+ end++ def visit_channel_members(channel)+ visit(channel.url + "/info/members")+ end++ def visit_channel_info(channel)+ visit(channel.url + "/info")+ end++ def visit_browse+ visit("/chat/browse")enddef minimize_full_pagefind(".open-drawer-btn").clickend++ def has_message?(message)+ container = find(".chat-message-container[data-id=\"#{message.id}\"")+ container.has_content?(message.message)+ container.has_content?(message.user.username)+ endendendenddiff --git a/plugins/chat/spec/system/page_objects/chat/chat_channel.rb b/plugins/chat/spec/system/page_objects/chat/chat_channel.rbindex adbe0756a45..ebf544dcba7 100644--- a/plugins/chat/spec/system/page_objects/chat/chat_channel.rb+++ b/plugins/chat/spec/system/page_objects/chat/chat_channel.rb@@ -23,6 +23,86 @@ module PageObjectshas_no_css?(".chat-skeleton")end+ def expand_message_actions(message)+ hover_message(message)+ click_more_buttons(message)+ end++ def hover_message(message)+ message_by_id(message.id).hover+ end++ def bookmark_message(message)+ hover_message(message)+ find(".bookmark-btn").click+ end++ def click_more_buttons(message)+ find(".more-buttons").click+ end++ def flag_message(message)+ hover_message(message)+ click_more_buttons(message)+ find("[data-value='flag']").click+ end++ def select_message(message)+ hover_message(message)+ click_more_buttons(message)+ find("[data-value='selectMessage']").click+ end++ def edit_message(message, text = nil)+ hover_message(message)+ click_more_buttons(message)+ find("[data-value='edit']").click++ send_message(text) if text+ end++ def send_message(text = nil)+ find(".chat-composer-input").fill_in(with: text)+ click_send_message+ end++ def reply_to(message)+ hover_message(message)+ find(".reply-btn").click+ end++ def has_bookmarked_message?(message)+ within(message_by_id(message.id)) { find(".chat-message-bookmarked") }+ end++ def find_reaction(message, reaction)+ within(message_reactions_list(message)) do+ return find("[data-emoji-name=\"#{reaction.emoji}\"]")+ end+ end++ def has_reaction?(message, reaction, text = nil)+ within(message_reactions_list(message)) do+ has_css?("[data-emoji-name=\"#{reaction.emoji}\"]", text: text)+ end+ end++ def message_reactions_list(message)+ within(message_by_id(message.id)) { find(".chat-message-reaction-list") }+ end++ def has_reactions?(message)+ within(message_by_id(message.id)) { has_css?(".chat-message-reaction-list") }+ end++ def has_no_reactions?(message)+ within(message_by_id(message.id)) { has_no_css?(".chat-message-reaction-list") }+ end++ def click_reaction(message, reaction)+ find_reaction(message, reaction).click+ end+def has_message?(text: nil, id: nil)if texthas_css?(".chat-message-text", text: text)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 1fa4d9fcf2a..e49a1070162 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@@ -24,6 +24,7 @@ module PageObjectsfind("#{VISIBLE_DRAWER} .channels-list .chat-channel-row[data-chat-channel-id='#{channel.id}']",).click+ has_no_css?(".chat-skeleton")enddef maximizediff --git a/plugins/chat/spec/system/page_objects/sidebar/sidebar.rb b/plugins/chat/spec/system/page_objects/sidebar/sidebar.rbindex e7786fafc90..e416e67c897 100644--- a/plugins/chat/spec/system/page_objects/sidebar/sidebar.rb+++ b/plugins/chat/spec/system/page_objects/sidebar/sidebar.rb@@ -14,6 +14,11 @@ module PageObjectsdef open_channel(channel)find(".sidebar-section-link[href='/chat/channel/#{channel.id}/#{channel.slug}']").clickend++ def find_channel(channel)+ find(".sidebar-section-link[href='/chat/channel/#{channel.id}/#{channel.slug}']")+ self+ endendendenddiff --git a/plugins/chat/spec/system/react_to_message_spec.rb b/plugins/chat/spec/system/react_to_message_spec.rbnew file mode 100644index 00000000000..311ead6de1b--- /dev/null+++ b/plugins/chat/spec/system/react_to_message_spec.rb@@ -0,0 +1,144 @@+# frozen_string_literal: true++RSpec.describe "React to message", type: :system, js: true do+ fab!(:current_user) { Fabricate(:user) }+ fab!(:category_channel_1) { Fabricate(:category_channel) }+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: category_channel_1) }++ let(:chat) { PageObjects::Pages::Chat.new }+ let(:channel) { PageObjects::Pages::ChatChannel.new }++ before do+ chat_system_bootstrap+ category_channel_1.add(current_user)+ sign_in(current_user)+ end++ context "when other user has reacted" do+ fab!(:reaction_1) do+ Chat::ChatMessageReactor.new(Fabricate(:user), category_channel_1).react!(+ message_id: message_1.id,+ react_action: :add,+ emoji: "female_detective",+ )+ end++ shared_examples "inline reactions" do+ it "shows existing reactions under the message" do+ chat.visit_channel(category_channel_1)+ expect(channel).to have_reaction(message_1, reaction_1)+ end++ it "increments when clicking it" do+ chat.visit_channel(category_channel_1)+ channel.click_reaction(message_1, reaction_1)+ expect(channel).to have_reaction(message_1, reaction_1, 2)+ end+ end++ context "when desktop" do+ include_examples "inline reactions"+ end++ context "when mobile", mobile: true do+ include_examples "inline reactions"+ end+ end++ context "when current user reacts" do+ fab!(:reaction_1) do+ Chat::ChatMessageReactor.new(Fabricate(:user), category_channel_1).react!(+ message_id: message_1.id,+ react_action: :add,+ emoji: "female_detective",+ )+ end++ context "when desktop" do+ context "when using inline reaction button" do+ it "adds a reaction" do+ chat.visit_channel(category_channel_1)+ channel.hover_message(message_1)+ find(".chat-message-react-btn").click+ find(".chat-emoji-picker [data-emoji=\"nerd_face\"]").click++ expect(channel).to have_reaction(message_1, reaction_1)+ end++ xit "adds the reaction to the frequently used list" do+ chat.visit_channel(category_channel_1)+ channel.hover_message(message_1)+ find(".chat-message-react-btn").click+ find(".chat-emoji-picker [data-emoji=\"nerd_face\"]").click++ channel.hover_message(message_1)+ end+ end++ context "when using message actions menu" do+ context "when using the emoji picker" do+ it "adds a reaction" do+ chat.visit_channel(category_channel_1)+ channel.hover_message(message_1)+ find(".chat-message-actions .react-btn").click+ find(".chat-emoji-picker [data-emoji=\"nerd_face\"]").click++ expect(channel).to have_reaction(message_1, reaction_1)+ end++ xit "adds the reaction to the frequently used list" do+ chat.visit_channel(category_channel_1)+ channel.hover_message(message_1)+ find(".chat-message-actions .react-btn").click+ find(".chat-emoji-picker [data-emoji=\"nerd_face\"]").click++ channel.hover_message(message_1)+ end+ end++ context "when using frequent reactions" do+ it "adds a reaction" do+ chat.visit_channel(category_channel_1)+ channel.hover_message(message_1)+ find(".chat-message-actions [data-emoji-name=\"+1\"").click++ expect(channel.message_reactions_list(message_1)).to have_css(+ "[data-emoji-name=\"+1\"]",+ )+ end+ end+ end+ end+ end++ context "when current user has reacted" do+ fab!(:reaction_1) do+ Chat::ChatMessageReactor.new(current_user, category_channel_1).react!(+ message_id: message_1.id,+ react_action: :add,+ emoji: "female_detective",+ )+ end++ shared_examples "inline reactions" do+ it "shows existing reactions under the message" do+ chat.visit_channel(category_channel_1)+ expect(channel).to have_reaction(message_1, reaction_1)+ end++ it "removes it when clicking it" do+ chat.visit_channel(category_channel_1)+ channel.click_reaction(message_1, reaction_1)+ expect(channel).to have_no_reactions(message_1)+ end+ end++ context "when desktop" do+ include_examples "inline reactions"+ end++ context "when mobile", mobile: true do+ include_examples "inline reactions"+ end+ end+enddiff --git a/plugins/chat/spec/system/read_only_spec.rb b/plugins/chat/spec/system/read_only_spec.rbnew file mode 100644index 00000000000..3610e55020e--- /dev/null+++ b/plugins/chat/spec/system/read_only_spec.rb@@ -0,0 +1,58 @@+# frozen_string_literal: true++RSpec.describe "Read only", type: :system, js: true do+ fab!(:channel_1) { Fabricate(:chat_channel) }++ let(:chat) { PageObjects::Pages::Chat.new }+ let(:channel) { PageObjects::Pages::ChatChannel.new }++ before { chat_system_bootstrap }++ context "when regular user" do+ fab!(:current_user) { Fabricate(:user) }++ before do+ channel_1.add(current_user)+ sign_in(current_user)+ end++ it "shows the read only status" do+ channel_1.read_only!(Discourse.system_user)+ chat.visit_channel_settings(channel_1)+ chat.visit_channel(channel_1)++ expect(page).to have_content(I18n.t("js.chat.channel_status.read_only_header"))+ end++ it "disables the composer" do+ channel_1.read_only!(Discourse.system_user)+ chat.visit_channel_settings(channel_1)+ chat.visit_channel(channel_1)++ expect(page).to have_field(+ placeholder: I18n.t("js.chat.placeholder_new_message_disallowed", status: "read only"),+ disabled: true,+ )+ end+ end++ context "when admin" do+ fab!(:current_user) { Fabricate(:admin) }++ before do+ channel_1.add(current_user)+ sign_in(current_user)+ end++ it "disables the composer" do+ channel_1.read_only!(Discourse.system_user)+ chat.visit_channel_settings(channel_1)+ chat.visit_channel(channel_1)++ expect(page).to have_field(+ placeholder: I18n.t("js.chat.placeholder_new_message_disallowed", status: "read only"),+ disabled: true,+ )+ end+ end+enddiff --git a/plugins/chat/spec/system/receiving_message_spec.rb b/plugins/chat/spec/system/receiving_message_spec.rbdeleted file mode 100644index 96b412e0dd7..00000000000--- a/plugins/chat/spec/system/receiving_message_spec.rb+++ /dev/null@@ -1,51 +0,0 @@-# frozen_string_literal: true--RSpec.describe "Receiving message", type: :system, js: true do- fab!(:current_user) { Fabricate(:admin) }- fab!(:user_2) { Fabricate(:user) }- fab!(:user_3) { Fabricate(:user) }- fab!(:direct_message_channel_1) do- Fabricate(:direct_message_channel, users: [current_user, user_2])- end- fab!(:direct_message_channel_2) do- Fabricate(:direct_message_channel, users: [current_user, user_2, user_3])- end-- let(:chat_page) { PageObjects::Pages::Chat.new }-- before do- chat_system_bootstrap(current_user, [direct_message_channel_1, direct_message_channel_2])- sign_in(current_user)- end-- context "when core sidebar is enabled" do- before do- SiteSetting.navigation_menu = "sidebar"- end-- context "when receiving a direct message" do- it "reorders the direct messages sidebar section links ordering by last message received" do- visit("/")-- expect(- page.find(- "#sidebar-section-content-chat-dms .sidebar-section-link-wrapper:nth-child(2) .sidebar-row",- ),- ).to have_content(direct_message_channel_2.name)-- creator =- Chat::ChatMessageCreator.create(- chat_channel: direct_message_channel_2,- user: user_2,- content: "this is good",- )-- expect(- page.find(- "#sidebar-section-content-chat-dms .sidebar-section-link-wrapper:nth-child(1) .sidebar-row",- ),- ).to have_content(direct_message_channel_2.name)- end- end- end-enddiff --git a/plugins/chat/spec/system/replying_indicator_spec.rb b/plugins/chat/spec/system/replying_indicator_spec.rbnew file mode 100644index 00000000000..0752ff34db7--- /dev/null+++ b/plugins/chat/spec/system/replying_indicator_spec.rb@@ -0,0 +1,35 @@+# frozen_string_literal: true++RSpec.describe "Replying indicator", type: :system, js: true do+ fab!(:channel_1) { Fabricate(:chat_channel) }+ fab!(:current_user) { Fabricate(:user) }+ fab!(:other_user) { Fabricate(:user) }++ let(:chat) { PageObjects::Pages::Chat.new }++ before do+ channel_1.add(current_user)+ channel_1.add(other_user)+ chat_system_bootstrap+ sign_in(current_user)+ end++ context "when on a channel" do+ context "when another user is replying" do+ it "shows the replying indicator" do+ using_session(other_user.username) do+ sign_in(other_user)+ chat.visit_channel(channel_1)+ find(".chat-composer-input").fill_in(with: "hello there")+ end++ chat.visit_channel(channel_1)++ expect(page).to have_selector(+ ".chat-replying-indicator",+ text: I18n.t("js.chat.replying_indicator.single_user", username: other_user.username),+ )+ end+ end+ end+enddiff --git a/plugins/chat/spec/system/shortcuts/chat_composer_spec.rb b/plugins/chat/spec/system/shortcuts/chat_composer_spec.rbnew file mode 100644index 00000000000..7126ffa8322--- /dev/null+++ b/plugins/chat/spec/system/shortcuts/chat_composer_spec.rb@@ -0,0 +1,72 @@+# frozen_string_literal: true++RSpec.describe "Shorcuts | chat composer", type: :system, js: true do+ fab!(:channel_1) { Fabricate(:chat_channel) }+ fab!(:current_user) { Fabricate(:user) }++ let(:chat) { PageObjects::Pages::Chat.new }++ KEY_MODIFIER = RUBY_PLATFORM =~ /darwin/i ? :meta : :control++ before do+ chat_system_bootstrap+ channel_1.add(current_user)+ sign_in(current_user)+ end++ context "when using meta + l" do+ xit "handles insert link shorcut" do+ end+ end++ context "when using meta + b" do+ xit "adds bold text" do+ chat.visit_channel(channel_1)++ within(".chat-composer-input") do |composer|+ composer.send_keys([KEY_MODIFIER, "b"])++ expect(composer.value).to eq("**strong text**")+ end+ end+ end++ context "when using meta + i" do+ xit "adds italic text" do+ chat.visit_channel(channel_1)++ within(".chat-composer-input") do |composer|+ composer.send_keys([KEY_MODIFIER, "i"])++ expect(composer.value).to eq("_emphasized text_")+ end+ end+ end++ context "when using meta + e" do+ it "adds preformatted text" do+ chat.visit_channel(channel_1)++ within(".chat-composer-input") do |composer|+ composer.send_keys([KEY_MODIFIER, "e"])++ expect(composer.value).to eq("`indent preformatted text by 4 spaces`")+ end+ end+ end++ context "when using ArrowUp" do+ fab!(:message_1) do+ Fabricate(:chat_message, message: "message 1", chat_channel: channel_1, user: current_user)+ end+ before { Fabricate(:chat_message, message: "message 2", chat_channel: channel_1) }++ it "edits last editable message" do+ chat.visit_channel(channel_1)++ within(".chat-composer-input") { |composer| composer.send_keys(:arrow_up) }++ expect(page.find(".chat-composer-message-details")).to have_content(message_1.message)+ end+ end+enddiff --git a/plugins/chat/spec/system/shortcuts/drawer_spec.rb b/plugins/chat/spec/system/shortcuts/drawer_spec.rbindex 84f25675aa8..336e6988b45 100644--- a/plugins/chat/spec/system/shortcuts/drawer_spec.rb+++ b/plugins/chat/spec/system/shortcuts/drawer_spec.rb@@ -1,14 +1,15 @@# frozen_string_literal: true-RSpec.describe "Navigation", type: :system, js: true do+RSpec.describe "Shortcuts | drawer", type: :system, js: true dofab!(:user_1) { Fabricate(:admin) }- fab!(:category_channel_1) { Fabricate(:category_channel) }- fab!(:category_channel_2) { Fabricate(:category_channel) }+ fab!(:channel_1) { Fabricate(:chat_channel) }+ fab!(:channel_2) { Fabricate(:chat_channel) }+let(:chat_page) { PageObjects::Pages::Chat.new }- let(:chat_drawer_page) { PageObjects::Pages::ChatDrawer.new }+ let(:drawer) { PageObjects::Pages::ChatDrawer.new }before do- chat_system_bootstrap(user_1, [category_channel_1, category_channel_2])+ chat_system_bootstrap(user_1, [channel_1, channel_2])sign_in(user_1)end@@ -31,13 +32,33 @@ RSpec.describe "Navigation", type: :system, js: true doendcontext "when pressing escape" do- it "opens the drawer" do+ it "closes the drawer" doexpect(page).to have_css(".chat-drawer.is-expanded")- chat_drawer_page.open_channel(category_channel_1)+ drawer.open_channel(channel_1)find(".chat-composer-input").send_keys(:escape)- expect(page).to_not have_css(".chat-drawer.is-expanded")+ expect(page).to have_no_css(".chat-drawer.is-expanded")+ end+ end++ context "when using Up/Down arrows" do+ it "navigates through the channels" do+ drawer.open_channel(channel_1)++ expect(page).to have_selector(".chat-drawer[data-chat-channel-id=\"#{channel_1.id}\"]")++ find(".chat-composer-input").send_keys(%i[alt arrow_down])++ expect(page).to have_selector(".chat-drawer[data-chat-channel-id=\"#{channel_2.id}\"]")++ find(".chat-composer-input").send_keys(%i[alt arrow_down])++ expect(page).to have_selector(".chat-drawer[data-chat-channel-id=\"#{channel_1.id}\"]")++ find(".chat-composer-input").send_keys(%i[alt arrow_up])++ expect(page).to have_selector(".chat-drawer[data-chat-channel-id=\"#{channel_2.id}\"]")endendenddiff --git a/plugins/chat/spec/system/shortcuts/sidebar_spec.rb b/plugins/chat/spec/system/shortcuts/sidebar_spec.rbnew file mode 100644index 00000000000..ccf6c298e50--- /dev/null+++ b/plugins/chat/spec/system/shortcuts/sidebar_spec.rb@@ -0,0 +1,50 @@+# frozen_string_literal: true++RSpec.describe "Shorcuts | sidebar", type: :system, js: true do+ fab!(:current_user) { Fabricate(:admin) }++ let(:chat) { PageObjects::Pages::Chat.new }++ before do+ SiteSetting.navigation_menu = "sidebar"+ chat_system_bootstrap+ sign_in(current_user)+ end++ context "when using Up/Down arrows" do+ fab!(:channel_1) { Fabricate(:chat_channel) }+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user]) }++ before { channel_1.add(current_user) }++ context "when on homepage" do+ it "does nothing" do+ visit("/")+ find("body").send_keys(%i[alt arrow_down])++ expect(page).to have_no_selector(".channel-#{channel_1.id}.active")+ expect(page).to have_no_selector(".channel-#{dm_channel_1.id}.active")+ end+ end++ context "when on chat page" do+ it "navigates through the channels" do+ chat.visit_channel(channel_1)++ expect(page).to have_selector(".channel-#{channel_1.id}.active")++ find("body").send_keys(%i[alt arrow_down])++ expect(page).to have_selector(".channel-#{dm_channel_1.id}.active")++ find("body").send_keys(%i[alt arrow_down])++ expect(page).to have_selector(".channel-#{channel_1.id}.active")++ find("body").send_keys(%i[alt arrow_up])++ expect(page).to have_selector(".channel-#{dm_channel_1.id}.active")+ end+ end+ end+enddiff --git a/plugins/chat/spec/system/sidebar_navigation_menu_spec.rb b/plugins/chat/spec/system/sidebar_navigation_menu_spec.rbnew file mode 100644index 00000000000..11616a6a4e0--- /dev/null+++ b/plugins/chat/spec/system/sidebar_navigation_menu_spec.rb@@ -0,0 +1,187 @@+# frozen_string_literal: true++RSpec.describe "Sidebar navigation menu", type: :system, js: true do+ fab!(:current_user) { Fabricate(:user) }++ before do+ SiteSetting.navigation_menu = "sidebar"+ chat_system_bootstrap++ sign_in(current_user)+ end++ context "when displaying the public channels section" do+ fab!(:channel_1) { Fabricate(:chat_channel) }++ before { channel_1.add(current_user) }++ it "displays correct channels section title" do+ visit("/")++ expect(page).to have_css(+ ".sidebar-section-chat-channels .sidebar-section-header-text",+ text: I18n.t("js.chat.chat_channels"),+ )+ end++ it "displays the correct hash icon prefix" do+ visit("/")++ expect(page).to have_css(+ ".sidebar-section-chat-channels .sidebar-section-link-#{channel_1.slug} .sidebar-section-link-prefix svg.prefix-icon.d-icon-hashtag",+ )+ end++ it "channel link has the correct href" do+ visit("/")++ expect(page).to have_link(+ channel_1.name,+ href: "/chat/channel/#{channel_1.id}/#{channel_1.slug}",+ )+ end++ context "when the category is private" do+ fab!(:group_1) { Fabricate(:group) }+ fab!(:private_channel_1) { Fabricate(:private_category_channel, group: group_1) }++ before do+ group_1.add(current_user)+ private_channel_1.add(current_user)+ end++ it "has a lock badge" do+ visit("/")++ expect(page).to have_css(+ ".sidebar-section-chat-channels .sidebar-section-link-#{private_channel_1.slug} .sidebar-section-link-prefix svg.prefix-badge.d-icon-lock",+ )+ end+ end++ context "when the channel has an emoji in the title" do+ fab!(:channel_1) { Fabricate(:chat_channel, name: "test :heart:") }++ before { channel_1.add(current_user) }++ it "unescapes the emoji" do+ visit("/")++ expect(page).to have_css(+ ".sidebar-section-chat-channels .sidebar-section-link-#{channel_1.slug} .emoji",+ )+ end+ end++ context "when the channel is muted" do+ fab!(:channel_2) { Fabricate(:chat_channel) }++ before do+ Fabricate(+ :user_chat_channel_membership,+ user: current_user,+ chat_channel: channel_2,+ muted: true,+ )+ end++ it "has a muted class" do+ visit("/")++ expect(page).to have_css(+ ".sidebar-section-chat-channels .sidebar-section-link-#{channel_2.slug}.sidebar-section-link--muted",+ )+ end+ end++ context "when channel description contains malicious content" do+ before { channel_1.update!(description: "<script>alert('hello')</script>") }++ it "escapes the title attribute using it" do+ visit("/")++ expect(+ page.find(".sidebar-section-chat-channels .sidebar-section-link-#{channel_1.slug}")[+ "title"+ ],+ ).to eq("<script>alert('hello')</script>")+ end+ end+ end++ context "when displaying the direct message channels section" do+ context "when the channel has two participants" do+ fab!(:other_user) { Fabricate(:user) }+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user, other_user]) }++ it "displays other user avatar in prefix when two participants" do+ visit("/")++ expect(+ page.find(+ ".sidebar-section-chat-dms a.sidebar-section-link:nth-child(1) .sidebar-section-link-prefix img",+ )[+ "src"+ ],+ ).to include(other_user.username)+ end++ it "displays other user username as link text" do+ visit("/")++ expect(+ page.find(".sidebar-section-chat-dms a.sidebar-section-link:nth-child(1)"),+ ).to have_content(other_user.username)+ end++ context "when other user has status" do+ before do+ SiteSetting.enable_user_status = true+ other_user.set_status!("online", "heart")+ end++ it "displays the status" do+ visit("/")++ expect(+ page.find(".sidebar-section-chat-dms a.sidebar-section-link:nth-child(1)"),+ ).to have_css(".user-status")+ end+ end+ end++ context "when channel has more than 2 participants" do+ fab!(:user_1) { Fabricate(:user) }+ fab!(:user_2) { Fabricate(:user) }+ fab!(:dm_channel_1) do+ Fabricate(:direct_message_channel, users: [current_user, user_1, user_2])+ end++ it "displays all participants names" do+ expect(+ page.find(+ ".sidebar-section-chat-dms a.sidebar-section-link:nth-child(1) .sidebar-section-link-content-text",+ ),+ ).to have_content("#{user_1.username}, #{user_2.username}")+ end+ end++ context "when username contains malicious content" do+ fab!(:other_user) { Fabricate(:user) }+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user, other_user]) }++ before do+ other_user.username = "<script>alert('hello')</script>"+ other_user.save!(validate: false)+ end++ it "escapes the title attribute using it" do+ visit("/")++ expect(page.find(".sidebar-section-chat-dms .channel-#{dm_channel_1.id}")["title"]).to eq(+ "Chat with @<script>alert('hello')</script>",+ )+ end+ end+ end+enddiff --git a/plugins/chat/spec/system/sidebars_spec.rb b/plugins/chat/spec/system/sidebars_spec.rbindex 808974d8748..81a0f12ddd5 100644--- a/plugins/chat/spec/system/sidebars_spec.rb+++ b/plugins/chat/spec/system/sidebars_spec.rb@@ -15,16 +15,21 @@ RSpec.describe "Navigation", type: :system, js: true doSiteSetting.navigation_menu = "legacy"end+ it "uses chat (not core) sidebar" do+ visit("/chat")++ expect(page).to have_css(".channels-list")+ expect(page).to have_no_css("#d-sidebar")+ end+context "when sidebar is enabled as the navigation menu" do- before do- SiteSetting.navigation_menu = "sidebar"- end+ before { SiteSetting.navigation_menu = "sidebar" }it "uses core sidebar" dovisit("/chat")expect(page).to have_css("#d-sidebar")- expect(page).to_not have_css(".channels-list")+ expect(page).to have_no_css(".channels-list")endcontext "when visiting on mobile" do@@ -32,24 +37,17 @@ RSpec.describe "Navigation", type: :system, js: true dovisit("/?mobile_view=1")chat_page.visit_channel(category_channel_2)- expect(page).to_not have_css("#d-sidebar")+ expect(page).to have_no_css("#d-sidebar")endendend- it "uses chat sidebar" do- visit("/chat")-- expect(page).to have_css(".channels-list")- expect(page).to_not have_css("#d-sidebar")- end-context "when visiting on mobile" doit "has no sidebar" dovisit("/?mobile_view=1")chat_page.visit_channel(category_channel_2)- expect(page).to_not have_css(".channels-list")+ expect(page).to have_no_css(".channels-list")endendenddiff --git a/plugins/chat/spec/system/silenced_user_spec.rb b/plugins/chat/spec/system/silenced_user_spec.rbnew file mode 100644index 00000000000..50a73ee1497--- /dev/null+++ b/plugins/chat/spec/system/silenced_user_spec.rb@@ -0,0 +1,44 @@+# frozen_string_literal: true++RSpec.describe "Silenced user", type: :system, js: true do+ fab!(:channel_1) { Fabricate(:category_channel) }++ let(:chat) { PageObjects::Pages::Chat.new }+ let(:channel) { PageObjects::Pages::ChatChannel.new }++ before { chat_system_bootstrap }++ context "when user is silenced" do+ fab!(:silenced_user) { Fabricate(:user) }++ before do+ UserSilencer.silence(silenced_user)+ channel_1.add(silenced_user)+ sign_in(silenced_user)+ chat.visit_channel(channel_1)+ end++ it "disables the composer" do+ chat.visit_channel(channel_1)++ expect(page).to have_field(+ placeholder: I18n.t("js.chat.placeholder_silenced"),+ disabled: true,+ )+ end++ it "removes the send button" do+ chat.visit_channel(channel_1)++ expect(page).to have_css(".send-btn[disabled]")+ end++ it "prevents reactions" do+ message_1 = Fabricate(:chat_message, chat_channel: channel_1)+ chat.visit_channel(channel_1)+ channel.hover_message(message_1)++ expect(page).to have_no_css(".chat-message-actions")+ end+ end+enddiff --git a/plugins/chat/spec/system/unfollow_dm_channel_spec.rb b/plugins/chat/spec/system/unfollow_dm_channel_spec.rbnew file mode 100644index 00000000000..c69255a10cc--- /dev/null+++ b/plugins/chat/spec/system/unfollow_dm_channel_spec.rb@@ -0,0 +1,38 @@+# frozen_string_literal: true++RSpec.describe "Unfollow dm channel", type: :system, js: true do+ fab!(:current_user) { Fabricate(:user) }+ fab!(:other_user) { Fabricate(:user) }+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user, other_user]) }++ let!(:chat_page) { PageObjects::Pages::Chat.new }+ let!(:chat_channel_page) { PageObjects::Pages::ChatChannel.new }++ before do+ SiteSetting.navigation_menu = "sidebar"+ chat_system_bootstrap+ sign_in(current_user)+ end++ def create_message(text: "this is fine", channel:, creator: Fabricate(:user))+ using_session(creator.username) do+ sign_in(creator)+ chat_page.visit_channel(channel)+ chat_channel_page.send_message(text)+ expect(chat_channel_page).to have_message(text: text)+ end+ end++ context "when receiving a message after unfollowing" do+ it "correctly shows the channel" do+ find(".channel-#{dm_channel_1.id}").hover+ find(".channel-#{dm_channel_1.id} .sidebar-section-link-hover").click++ expect(page).to have_no_css(".channel-#{dm_channel_1.id}")++ create_message(channel: dm_channel_1, creator: other_user)++ expect(page).to have_css(".channel-#{dm_channel_1.id} .urgent")+ end+ end+enddiff --git a/plugins/chat/spec/system/user_card_spec.rb b/plugins/chat/spec/system/user_card_spec.rbnew file mode 100644index 00000000000..07427ed79dc--- /dev/null+++ b/plugins/chat/spec/system/user_card_spec.rb@@ -0,0 +1,76 @@+# frozen_string_literal: true++RSpec.describe "User card", type: :system, js: true do+ fab!(:current_user) { Fabricate(:user) }+ fab!(:topic_1) { Fabricate(:topic) }++ let(:chat) { PageObjects::Pages::Chat.new }++ before { chat_system_bootstrap }++ shared_examples "not showing chat button" do+ it "doesn’t show the chat buttton" do+ expect(page).to have_no_css(".user-card-chat-btn")+ end+ end++ shared_examples "showing chat button" do+ it "shows the chat buttton" do+ expect(page).to have_css(".user-card-chat-btn")+ end+ end++ context "when user" do+ context "when chat disabled" do+ before do+ SiteSetting.chat_enabled = false+ sign_in(current_user)+ end++ context "when showing user card" do+ before do+ visit("/")+ find("[data-user-card='#{topic_1.user.username}'").click+ end++ include_examples "not showing chat button"+ end+ end++ context "when chat enabled" do+ before { sign_in(current_user) }++ context "when showing user card" do+ before do+ visit("/")+ find("[data-user-card='#{topic_1.user.username}'").click+ end++ include_examples "showing chat button"++ context "when clicking chat button" do+ before { find(".user-card-chat-btn").click }++ it "opens correct channel" do+ # at this point the ChatChannel is not created yet+ expect(page).to have_css(".chat-drawer.is-expanded")+ expect(page).to have_css(+ ".chat-drawer.is-expanded[data-chat-channel-id='#{ChatChannel.last.id}']",+ )+ end+ end+ end+ end+ end++ context "when anonymous" do+ context "when showing user card" do+ before do+ visit("/")+ find("[data-user-card='#{topic_1.user.username}'").click+ end++ include_examples "not showing chat button"+ end+ end+enddiff --git a/plugins/chat/spec/system/user_chat_preferences_spec.rb b/plugins/chat/spec/system/user_chat_preferences_spec.rbnew file mode 100644index 00000000000..51e5d217d8c--- /dev/null+++ b/plugins/chat/spec/system/user_chat_preferences_spec.rb@@ -0,0 +1,34 @@+# frozen_string_literal: true++RSpec.describe "User chat preferences", type: :system, js: true do+ fab!(:current_user) { Fabricate(:user) }++ let(:chat) { PageObjects::Pages::Chat.new }++ before do+ chat_system_bootstrap+ sign_in(current_user)+ end++ context "when chat disabled" do+ before do+ SiteSetting.chat_enabled = false+ sign_in(current_user)+ end++ it "shows a not found page" do+ visit("/u/#{current_user.username}/preferences/chat")++ expect(page).to have_content(I18n.t("page_not_found.title"))+ end+ end++ it "can select chat sound" do+ visit("/u/#{current_user.username}/preferences/chat")+ find("#user_chat_sounds .select-kit-header[data-value]").click+ find("[data-value='bell']").click+ find(".save-changes").click++ expect(page).to have_css("#user_chat_sounds .select-kit-header[data-value='bell']")+ end+enddiff --git a/plugins/chat/spec/system/user_menu_notifications/sidebar_spec.rb b/plugins/chat/spec/system/user_menu_notifications/sidebar_spec.rbnew file mode 100644index 00000000000..4b997a4092c--- /dev/null+++ b/plugins/chat/spec/system/user_menu_notifications/sidebar_spec.rb@@ -0,0 +1,185 @@+# frozen_string_literal: true++RSpec.describe "User menu notifications | sidebar", type: :system, js: true do+ fab!(:current_user) { Fabricate(:user) }++ let(:chat) { PageObjects::Pages::Chat.new }+ let(:channel) { PageObjects::Pages::ChatChannel.new }++ before do+ SiteSetting.navigation_menu = "sidebar"+ chat_system_bootstrap+ sign_in(current_user)+ end++ shared_examples "chat not available" do+ it "doesn’t show the chat tab" do+ visit("/")+ find(".header-dropdown-toggle.current-user").click++ expect(page).to have_no_css("#user-menu-button-chat-notifications")+ end+ end++ context "when chat is disabled" do+ before { SiteSetting.chat_enabled = false }++ include_examples "chat not available"+ end++ context "when user has chat disabled" do+ before { current_user.user_option.update!(chat_enabled: false) }++ include_examples "chat not available"+ end++ context "when mentioning" do+ fab!(:other_user) { Fabricate(:user) }++ context "when dm channel" do+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user, other_user]) }++ before { Jobs.run_immediately! }++ context "when @username" do+ it "shows a mention notification" do+ message =+ Chat::ChatMessageCreator.create(+ chat_channel: dm_channel_1,+ user: other_user,+ content: "this is fine @#{current_user.username}",+ ).chat_message++ visit("/")++ find(".header-dropdown-toggle.current-user").click+ within("#user-menu-button-chat-notifications") do |panel|+ expect(panel).to have_content(1)+ panel.click+ end+ expect(find("#quick-access-chat-notifications")).to have_link(+ I18n.t("js.notifications.popup.direct_message_chat_mention.direct"),+ href: "/chat/channel/#{dm_channel_1.id}/#{other_user.username}?messageId=#{message.id}",+ )+ end+ end+ end++ context "when category channel" do+ fab!(:channel_1) { Fabricate(:chat_channel) }++ before do+ channel_1.add(current_user)+ channel_1.add(other_user)+ Jobs.run_immediately!+ end++ context "when group mention" do+ fab!(:group) { Fabricate(:group, mentionable_level: Group::ALIAS_LEVELS[:everyone]) }++ before { group.add(current_user) }++ it "shows a group mention notification" do+ message =+ Chat::ChatMessageCreator.create(+ chat_channel: channel_1,+ user: other_user,+ content: "this is fine @#{group.name}",+ ).chat_message++ visit("/")++ find(".header-dropdown-toggle.current-user").click+ within("#user-menu-button-chat-notifications") do |panel|+ expect(panel).to have_content(1)+ panel.click+ end+ expect(find("#quick-access-chat-notifications")).to have_link(+ I18n.t(+ "js.notifications.popup.chat_mention.other_plain",+ identifier: "@#{group.name}",+ channel: channel_1.name,+ ),+ href: "/chat/channel/#{channel_1.id}/#{channel_1.slug}?messageId=#{message.id}",+ )+ end+ end++ context "when @username" do+ it "shows a mention notification" do+ message =+ Chat::ChatMessageCreator.create(+ chat_channel: channel_1,+ user: other_user,+ content: "this is fine @#{current_user.username}",+ ).chat_message++ visit("/")++ find(".header-dropdown-toggle.current-user").click+ within("#user-menu-button-chat-notifications") do |panel|+ expect(panel).to have_content(1)+ panel.click+ end++ expect(find("#quick-access-chat-notifications")).to have_link(+ I18n.t("js.notifications.popup.chat_mention.direct", channel: channel_1.name),+ href: "/chat/channel/#{channel_1.id}/#{channel_1.slug}?messageId=#{message.id}",+ )+ end+ end++ context "when @all" do+ it "shows a mention notification" do+ message =+ Chat::ChatMessageCreator.create(+ chat_channel: channel_1,+ user: other_user,+ content: "this is fine @all",+ ).chat_message++ visit("/")++ find(".header-dropdown-toggle.current-user").click+ within("#user-menu-button-chat-notifications") do |panel|+ expect(panel).to have_content(1)+ panel.click+ end+ expect(find("#quick-access-chat-notifications")).to have_link(+ I18n.t(+ "js.notifications.popup.chat_mention.other_plain",+ identifier: "@all",+ channel: channel_1.name,+ ),+ href: "/chat/channel/#{channel_1.id}/#{channel_1.slug}?messageId=#{message.id}",+ )+ end+ end+ end+ end++ context "when inviting a user" do+ fab!(:channel_1) { Fabricate(:chat_channel) }+ fab!(:other_user) { Fabricate(:user) }++ before do+ other_user = Fabricate(:user)+ channel_1.add(current_user)+ end++ it "shows an invitation notification" do+ chat.visit_channel(channel_1)+ find(".chat-composer-input").fill_in(with: "this is fine @#{other_user.username}")+ Sidekiq::Testing.inline! do+ find(".send-btn").click+ find(".invite-link").click+ end++ sign_in(other_user)+ find(".header-dropdown-toggle.current-user").click++ expect(find("#user-menu-button-chat-notifications")).to have_content(1)+ expect(find("#quick-access-all-notifications")).to have_css(".chat-invitation.unread")+ end+ end+enddiff --git a/plugins/chat/spec/system/user_status/sidebar_spec.rb b/plugins/chat/spec/system/user_status/sidebar_spec.rbnew file mode 100644index 00000000000..e29a3d19b81--- /dev/null+++ b/plugins/chat/spec/system/user_status/sidebar_spec.rb@@ -0,0 +1,44 @@+# frozen_string_literal: true++RSpec.describe "User status | sidebar", type: :system, js: true do+ fab!(:current_user) { Fabricate(:user) }+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user]) }++ let(:chat) { PageObjects::Pages::Chat.new }+ let(:channel) { PageObjects::Pages::ChatChannel.new }++ before do+ SiteSetting.navigation_menu = "sidebar"+ SiteSetting.enable_user_status = true+ chat_system_bootstrap+ current_user.set_status!("online", "heart")+ sign_in(current_user)+ Jobs.run_immediately!+ end++ it "shows user status" do+ visit("/")++ expect(find(".user-status .emoji")["title"]).to eq("online")+ expect(find(".user-status .emoji")["src"]).to include("heart")+ end++ context "when changing status" do+ it "updates status" do+ visit("/")+ current_user.set_status!("offline", "tooth")++ expect(page).to have_css('.user-status .emoji[title="offline"]')+ expect(find(".user-status .emoji")["src"]).to include("tooth")+ end+ end++ context "when removing status" do+ it "removes status" do+ visit("/")+ current_user.clear_status!++ expect(page).to have_no_css(".user-status")+ end+ end+enddiff --git a/plugins/chat/spec/system/visit_channel_spec.rb b/plugins/chat/spec/system/visit_channel_spec.rbnew file mode 100644index 00000000000..942491022dd--- /dev/null+++ b/plugins/chat/spec/system/visit_channel_spec.rb@@ -0,0 +1,185 @@+# frozen_string_literal: true++RSpec.describe "Visit channel", type: :system, js: true do+ fab!(:category) { Fabricate(:category) }+ fab!(:topic) { Fabricate(:topic) }+ fab!(:post) { Fabricate(:post, topic: topic) }+ fab!(:current_user) { Fabricate(:user) }+ fab!(:category_channel_1) { Fabricate(:category_channel) }+ fab!(:private_category_channel_1) { Fabricate(:private_category_channel) }+ fab!(:dm_channel_1) { Fabricate(:direct_message_channel, users: [current_user]) }+ fab!(:inaccessible_dm_channel_1) { Fabricate(:direct_message_channel) }++ let(:chat) { PageObjects::Pages::Chat.new }++ before { chat_system_bootstrap }++ context "when chat disabled" do+ before do+ SiteSetting.chat_enabled = false+ sign_in(current_user)+ end++ it "shows a not found page" do+ chat.visit_channel(category_channel_1)++ expect(page).to have_content(I18n.t("page_not_found.title"))+ end+ end++ context "when chat enabled" do+ context "when anonymous" do+ it "redirects to homepage" do+ chat.visit_channel(category_channel_1)++ expect(page).to have_current_path("/latest")+ end+ end++ context "when regular user" do+ before { sign_in(current_user) }++ context "when chat is disabled" do+ before { current_user.user_option.update!(chat_enabled: false) }++ it "redirects to homepage" do+ chat.visit_channel(category_channel_1)++ expect(page).to have_current_path("/latest")+ end+ end++ context "when current user is not allowed to chat" do+ before { SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:staff] }++ it "redirects homepage" do+ chat.visit_channel(category_channel_1)++ expect(page).to have_current_path("/latest")+ end+ end++ context "when channel is not found" do+ it "shows a not found page" do+ visit("/chat/channel/999/-")++ expect(page).to have_current_path("/404")+ end+ end++ context "when channel is not accessible" do+ context "when category channel" do+ it "shows a forbidden page" do+ chat.visit_channel(private_category_channel_1)++ expect(page).to have_content(I18n.t("js.errors.reasons.forbidden"))+ end+ end++ context "when direct message channel" do+ it "shows a forbidden page" do+ chat.visit_channel(inaccessible_dm_channel_1)++ expect(page).to have_content(I18n.t("js.errors.reasons.forbidden"))+ end+ end+ end++ context "when current user is not member of the channel" do+ context "when category channel" do+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: category_channel_1) }++ it "allows to join it" do+ chat.visit_channel(category_channel_1)++ expect(page).to have_content(I18n.t("js.chat.channel_settings.join_channel"))+ end++ it "shows a preview of the channel" do+ chat.visit_channel(category_channel_1)++ expect(page).to have_content(category_channel_1.name)+ expect(chat).to have_message(message_1)+ end+ end++ context "when direct message channel" do+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: dm_channel_1) }++ before { dm_channel_1.membership_for(current_user).destroy! }++ it "allows to join it" do+ chat.visit_channel(dm_channel_1)++ expect(page).to have_content(I18n.t("js.chat.channel_settings.join_channel"))+ end++ it "shows a preview of the channel" do+ chat.visit_channel(dm_channel_1)++ expect(chat).to have_message(message_1)+ end+ end+ end++ context "when current user is member of the channel" do+ context "when category channel" do+ fab!(:message_1) { Fabricate(:chat_message, chat_channel: category_channel_1) }++ before { category_channel_1.add(current_user) }++ it "doesn’t ask to join it" do+ chat.visit_channel(category_channel_1)++ expect(page).to have_no_content(I18n.t("js.chat.channel_settings.join_channel"))+ end++ it "shows a preview of the channel" do+ chat.visit_channel(category_channel_1)++ expect(page).to have_content(category_channel_1.name)+ expect(chat).to have_message(message_1)+ end++ context "when URL doesn’t contain slug" do+ it "redirects to correct URL" do+ visit("/chat/channel/#{category_channel_1.id}/-")++ expect(page).to have_current_path(+ "/chat/channel/#{category_channel_1.id}/#{category_channel_1.slug}",+ )+ end+ end+ end++ context "when direct message channel" do+ fab!(:message_1) do+ Fabricate(:chat_message, chat_channel: dm_channel_1, user: current_user)+ end++ it "doesn’t ask to join it" do+ chat.visit_channel(dm_channel_1)++ expect(page).to have_no_content(I18n.t("js.chat.channel_settings.join_channel"))+ end++ it "shows a preview of the channel" do+ chat.visit_channel(dm_channel_1)++ expect(chat).to have_message(message_1)+ end++ context "when URL doesn’t contain slug" do+ it "redirects to correct URL" do+ visit("/chat/channel/#{dm_channel_1.id}/-")++ expect(page).to have_current_path(+ "/chat/channel/#{dm_channel_1.id}/#{Slug.for(dm_channel_1.title(current_user))}",+ )+ end+ end+ end+ end+ end+ end+enddiff --git a/plugins/chat/test/javascripts/acceptance/chat-browse-test.js b/plugins/chat/test/javascripts/acceptance/chat-browse-test.jsdeleted file mode 100644index 0b8e2bd8bdf..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-browse-test.js+++ /dev/null@@ -1,132 +0,0 @@-import {- acceptance,- query,- queryAll,-} from "discourse/tests/helpers/qunit-helpers";-import { click, currentURL, fillIn, visit } from "@ember/test-helpers";-import { test } from "qunit";-import I18n from "I18n";-import fabricators from "../helpers/fabricators";-import { isEmpty } from "@ember/utils";--acceptance("Discourse Chat - browse channels", function (needs) {- needs.user({ has_chat_enabled: true, can_chat: true });-- needs.settings({ chat_enabled: true });-- needs.pretender((server, helper) => {- // we don't need anything in the sidebar for this test- server.get("/chat/chat_channels.json", () => {- return helper.response({- public_channels: [],- direct_message_channels: [],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- });- });-- server.get("/chat/api/chat_channels.json", (request) => {- const params = request.queryParams;-- if (!isEmpty(params.filter)) {- if (params.filter === "foo") {- return helper.response([fabricators.chatChannel()]);- } else {- return helper.response([]);- }- }-- const channels = [];- if (isEmpty(params.status) || params.status === "open") {- channels.push(fabricators.chatChannel());- channels.push(fabricators.chatChannel());- }-- if (params.status === "closed" || isEmpty(params.status)) {- channels.push(fabricators.chatChannel({ status: "closed" }));- }-- if (params.status === "archived" || isEmpty(params.status)) {- channels.push(fabricators.chatChannel({ status: "archived" }));- }-- return helper.response(channels);- });- });-- test("Defaults to open filter", async function (assert) {- await visit("/chat/browse");- assert.equal(currentURL(), "/chat/browse/open");- });-- test("All filter", async function (assert) {- await visit("/chat/browse");- await click(".chat-browse-view__filter-link.-all");-- assert.equal(currentURL(), "/chat/browse/all");- assert.equal(queryAll(".chat-channel-card").length, 4);- });-- test("Open filter", async function (assert) {- await visit("/chat/browse");- await click(".chat-browse-view__filter-link.-open");-- assert.equal(currentURL(), "/chat/browse/open");- assert.equal(queryAll(".chat-channel-card").length, 2);- });-- test("Closed filter", async function (assert) {- await visit("/chat/browse");- await click(".chat-browse-view__filter-link.-closed");-- assert.equal(currentURL(), "/chat/browse/closed");- assert.equal(queryAll(".chat-channel-card").length, 1);- });-- test("Archived filter", async function (assert) {- this.siteSettings.chat_allow_archiving_channels = true;-- await visit("/chat/browse");- await click(".chat-browse-view__filter-link.-archived");-- assert.equal(currentURL(), "/chat/browse/archived");- assert.equal(queryAll(".chat-channel-card").length, 1);- });-- test("Filtering results", async function (assert) {- await visit("/chat/browse");-- assert.equal(queryAll(".chat-channel-card").length, 2);-- await fillIn(".dc-filter-input", "foo");-- assert.equal(queryAll(".chat-channel-card").length, 1);- });-- test("No results", async function (assert) {- await visit("/chat/browse");- await fillIn(".dc-filter-input", "bar");-- assert.equal(- query(".empty-state-title").innerText.trim(),- I18n.t("chat.empty_state.title")- );- });-- test("Archiving channels is not allowed", async function (assert) {- this.siteSettings.chat_allow_archiving_channels = false;-- await visit("/chat/browse");-- assert.equal(- queryAll(".chat-browse-view__filter-link.-archived").length,- 0- );- this.siteSettings.chat_allow_archiving_channels = true;- });-});diff --git a/plugins/chat/test/javascripts/acceptance/chat-channel-info-test.js b/plugins/chat/test/javascripts/acceptance/chat-channel-info-test.jsdeleted file mode 100644index 0fea5fa2845..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-channel-info-test.js+++ /dev/null@@ -1,71 +0,0 @@-import { acceptance } from "discourse/tests/helpers/qunit-helpers";-import { click, visit } from "@ember/test-helpers";-import { test } from "qunit";-import { ORIGINS } from "discourse/plugins/chat/discourse/services/chat-channel-info-route-origin-manager";-import { getOwner } from "discourse-common/lib/get-owner";-import fabricators from "../helpers/fabricators";--acceptance("Discourse Chat - chat channel info", function (needs) {- needs.user({ has_chat_enabled: true, can_chat: true });-- needs.settings({ chat_enabled: true });-- needs.pretender((server, helper) => {- const channel = fabricators.chatChannel();- server.get("/chat/chat_channels.json", () => {- return helper.response({- public_channels: [],- direct_message_channels: [],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- });- });- server.get("/chat/chat_channels/:id.json", () => {- return helper.response(channel);- });- server.get("/chat/api/chat_channels.json", () =>- helper.response([channel])- );- server.get("/chat/api/chat_channels/:id/memberships.json", () =>- helper.response([])- );- server.get("/chat/:id/messages.json", () =>- helper.response({ chat_messages: [], meta: {} })- );- });-- needs.hooks.beforeEach(function () {- this.manager = getOwner(this).lookup(- "service:chat-channel-info-route-origin-manager"- );- });-- needs.hooks.afterEach(function () {- this.manager.origin = null;- });-- test("Direct visit sets origin as channel", async function (assert) {- await visit("/chat/channel/1/my-category-title/info");-- assert.strictEqual(this.manager.origin, ORIGINS.channel);- });-- test("Visit from browse sets origin as browse", async function (assert) {- await visit("/chat/browse/open");- await click(".chat-channel-card__setting");-- assert.strictEqual(this.manager.origin, ORIGINS.browse);- });-- test("Visit from channel sets origin as channel", async function (assert) {- await visit("/chat/channel/1/my-category-title");- await visit("/chat/channel/1/my-category-title/info");-- assert.strictEqual(this.manager.origin, ORIGINS.channel);- });-});diff --git a/plugins/chat/test/javascripts/acceptance/chat-channel-slug-test.js b/plugins/chat/test/javascripts/acceptance/chat-channel-slug-test.jsdeleted file mode 100644index a171b0e9036..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-channel-slug-test.js+++ /dev/null@@ -1,24 +0,0 @@-import { acceptance } from "discourse/tests/helpers/qunit-helpers";-import { currentURL, visit } from "@ember/test-helpers";-import { test } from "qunit";-import { chatChannels } from "discourse/plugins/chat/chat-fixtures";--acceptance("Discourse Chat - chat channel slug", function (needs) {- needs.user({ has_chat_enabled: true, can_chat: true });-- needs.settings({ chat_enabled: true });-- needs.pretender((server, helper) => {- server.get("/chat/chat_channels.json", () => helper.response(chatChannels));- server.get("/chat/:id/messages.json", () =>- helper.response({ chat_messages: [], meta: {} })- );- });-- test("Replacing title param", async function (assert) {- await visit("/chat");- await visit("/chat/channel/11/-");-- assert.equal(currentURL(), "/chat/channel/11/another-category");- });-});diff --git a/plugins/chat/test/javascripts/acceptance/chat-channels-list-test.js b/plugins/chat/test/javascripts/acceptance/chat-channels-list-test.jsdeleted file mode 100644index 2d3790a6baf..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-channels-list-test.js+++ /dev/null@@ -1,62 +0,0 @@-import {- acceptance,- exists,- updateCurrentUser,-} from "discourse/tests/helpers/qunit-helpers";-import { test } from "qunit";-import { visit } from "@ember/test-helpers";-import { directMessageChannels } from "discourse/plugins/chat/chat-fixtures";-import { cloneJSON } from "discourse-common/lib/object";--acceptance(- "Discourse Chat - Chat Channels list - no joinable public channels",- function (needs) {- needs.user({ has_chat_enabled: true, has_joinable_public_channels: false });-- needs.settings({- chat_enabled: true,- navigation_menu: "legacy",- });-- needs.pretender((server, helper) => {- server.get("/chat/chat_channels.json", () => {- return helper.response({- public_channels: [],- direct_message_channels: cloneJSON(directMessageChannels).mapBy(- "chat_channel"- ),- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- });- });-- server.get("/chat/:id/messages.json", () => {- return helper.response({- chat_messages: [],- meta: { can_chat: true },- });- });- });-- test("Public chat channels section visibility", async function (assert) {- await visit("/chat");-- assert.ok(- exists(".public-channels-section"),- "it shows the section for staff"- );-- updateCurrentUser({ admin: false, moderator: false });-- assert.notOk(- exists(".public-channels-section"),- "it doesn’t show the section for regular user"- );- });- }-);diff --git a/plugins/chat/test/javascripts/acceptance/chat-composer-test.js b/plugins/chat/test/javascripts/acceptance/chat-composer-test.jsindex 4b671cb5ed4..40f6d2386d5 100644--- a/plugins/chat/test/javascripts/acceptance/chat-composer-test.js+++ b/plugins/chat/test/javascripts/acceptance/chat-composer-test.js@@ -4,14 +4,8 @@ import {publishToMessageBus,query,} from "discourse/tests/helpers/qunit-helpers";-import {- click,- fillIn,- settled,- triggerKeyEvent,- visit,-} from "@ember/test-helpers";-import { skip, test } from "qunit";+import { click, fillIn, settled, visit } from "@ember/test-helpers";+import { skip } from "qunit";import {baseChatPretenders,chatChannelPretender,@@ -50,7 +44,7 @@ acceptance("Discourse Chat - Composer", function (needs) {});});- test("when pasting html in composer", async function (assert) {+ skip("when pasting html in composer", async function (assert) {await visit("/chat/channel/11/another-category");const clipboardEvent = new Event("paste", { bubbles: true });@@ -71,62 +65,6 @@ acceptance("Discourse Chat - Composer", function (needs) {assert.equal(document.querySelector(".chat-composer-input").value, "Foo");});-- test("when selecting an emoji from the picker", async function (assert) {- const emojiReactionStore = this.container.lookup(- "service:chat-emoji-reaction-store"- );-- assert.deepEqual(- emojiReactionStore.favorites,- this.siteSettings.default_emoji_reactions.split("|")- );-- await visit("/chat/channel/11/-");- await click(".chat-composer-dropdown__trigger-btn");- await click(".chat-composer-dropdown__action-btn.emoji");- await click(`[data-emoji="grinning"]`);-- assert.deepEqual(- emojiReactionStore.favorites,- ["grinning"].concat(this.siteSettings.default_emoji_reactions.split("|")),- "it tracks the emoji"- );- });-- skip("when selecting an emoji from the autocomplete", async function (assert) {- const emojiReactionStore = this.container.lookup(- "service:chat-emoji-reaction-store"- );-- assert.deepEqual(- emojiReactionStore.favorites,- this.siteSettings.default_emoji_reactions.split("|")- );-- await visit("/chat/channel/11/-");- await fillIn(".chat-composer-input", "test :grinni");- await triggerKeyEvent(".chat-composer-input", "keyup", "ArrowDown"); // necessary to show the menu- await click(".autocomplete.ac-emoji ul li:first-child a");-- assert.deepEqual(- emojiReactionStore.favorites,- ["grinning"].concat(this.siteSettings.default_emoji_reactions.split("|")),- "it tracks the emoji"- );- });-- test("JIT warnings for group mentions", async function (assert) {- await visit("/chat/channel/11/-");- await fillIn(".chat-composer-input", `@${GROUP_NAME}`);-- assert.equal(- query(".chat-mention-warnings .chat-mention-warnings-list__simple li")- .innerText,- `@${GROUP_NAME} doesn't allow mentions`,- "displays a warning when the group is unreachable"- );- });});let sendAttempt = 0;@@ -157,7 +95,7 @@ acceptance("Discourse Chat - Composer - unreliable network", function (needs) {sendAttempt = 0;});- test("Sending a message with unreliable network", async function (assert) {+ skip("Sending a message with unreliable network", async function (assert) {await visit("/chat/channel/11/-");await fillIn(".chat-composer-input", "network-error-message");await click(".send-btn");@@ -194,7 +132,7 @@ acceptance("Discourse Chat - Composer - unreliable network", function (needs) {);});- test("Draft with unreliable network", async function (assert) {+ skip("Draft with unreliable network", async function (assert) {await visit("/chat/channel/11/-");this.chatService.set("isNetworkUnreliable", true);await settled();diff --git a/plugins/chat/test/javascripts/acceptance/chat-flagging-test.js b/plugins/chat/test/javascripts/acceptance/chat-flagging-test.jsdeleted file mode 100644index 63cbd5bf330..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-flagging-test.js+++ /dev/null@@ -1,96 +0,0 @@-import selectKit from "discourse/tests/helpers/select-kit-helper";-import {- acceptance,- exists,- loggedInUser,- publishToMessageBus,- query,-} from "discourse/tests/helpers/qunit-helpers";-import {- chatChannels,- generateChatView,-} from "discourse/plugins/chat/chat-fixtures";-import { test } from "qunit";-import { click, triggerEvent, visit } from "@ember/test-helpers";--acceptance("Discourse Chat - Flagging test", function (needs) {- let defaultChatView;- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 100,- can_chat: true,- has_chat_enabled: true,- });- needs.pretender((server, helper) => {- server.get("/chat/chat_channels.json", () => helper.response(chatChannels));- server.get("/chat/9/messages.json", () => {- return helper.response(- generateChatView(loggedInUser(), {- can_flag: false,- })- );- });- server.get("/chat/75/messages.json", () => {- defaultChatView = generateChatView(loggedInUser());- return helper.response(defaultChatView);- });- server.post("/uploads/lookup-urls", () => {- return helper.response([]);- });- server.put("/chat/flag", () => {- return helper.response({ success: true });- });- });- needs.settings({- chat_enabled: true,- });-- test("Flagging in public channel works", async function (assert) {- await visit("/chat/channel/75/site");-- assert.notOk(exists(".chat-live-pane .chat-message .chat-message-flagged"));- await triggerEvent(".chat-message-container", "mouseenter");-- const moreButtons = selectKit(- ".chat-message-actions-container .more-buttons"- );- await moreButtons.expand();-- const content = moreButtons.displayedContent();- assert.ok(content.find((row) => row.id === "flag"));-- await moreButtons.selectRowByValue("flag");-- await click(".controls.spam input");- await click(".modal-footer button");-- await publishToMessageBus("/chat/75", {- type: "self_flagged",- chat_message_id: defaultChatView.chat_messages[0].id,- user_flag_status: 0,- });- await publishToMessageBus("/chat/75", {- type: "flag",- chat_message_id: defaultChatView.chat_messages[0].id,- reviewable_id: 1,- });-- const reviewableLink = query(- `.chat-message-container[data-id='${defaultChatView.chat_messages[0].id}'] .chat-message-info__flag a`- );- assert.ok(reviewableLink.href.endsWith("/review/1"));- });-- test("Flag button isn't present for DM channel", async function (assert) {- await visit("/chat/channel/9/@hawk");- await triggerEvent(".chat-message-container", "mouseenter");-- const moreButtons = selectKit(".chat-message-actions .more-buttons");- await moreButtons.expand();-- const content = moreButtons.displayedContent();- assert.notOk(content.find((row) => row.id === "flag"));- });-});diff --git a/plugins/chat/test/javascripts/acceptance/chat-keyboard-shortcuts-test.js b/plugins/chat/test/javascripts/acceptance/chat-keyboard-shortcuts-test.jsdeleted file mode 100644index 9d1c144bcf4..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-keyboard-shortcuts-test.js+++ /dev/null@@ -1,290 +0,0 @@-import showModal from "discourse/lib/show-modal";-import {- acceptance,- exists,- loggedInUser,- query,- queryAll,-} from "discourse/tests/helpers/qunit-helpers";-import {- click,- currentURL,- fillIn,- focus,- settled,- triggerKeyEvent,- visit,-} from "@ember/test-helpers";-import {- chatChannels,- generateChatView,-} from "discourse/plugins/chat/chat-fixtures";-import ChatChannel from "discourse/plugins/chat/discourse/models/chat-channel";-import { KEY_MODIFIER } from "discourse/plugins/chat/discourse/initializers/chat-keyboard-shortcuts";-import { test } from "qunit";--const MODIFIER_OPTIONS =- KEY_MODIFIER === "meta" ? { metaKey: true } : { ctrlKey: true };--acceptance("Discourse Chat - Keyboard shortcuts", function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });-- needs.pretender((server, helper) => {- // allows to create a staged message- server.post("/chat/:id.json", () =>- helper.response({- errors: [""],- })- );- server.get("/chat/chat_channels.json", () => helper.response(chatChannels));- server.get("/chat/:chatChannelId/messages.json", () =>- helper.response(generateChatView(loggedInUser()))- );- server.post("/uploads/lookup-urls", () => {- return helper.response([]);- });- server.post("/chat/drafts", () => {- return helper.response([]);- });-- server.get("/chat/chat_channels/search", () => {- return helper.response({- public_channels: [ChatChannel.create({ id: 3, title: "seventeen" })],- direct_message_channels: [- ChatChannel.create({- id: 4,- users: [{ id: 10, username: "someone" }],- }),- ],- users: [- { id: 11, username: "smoothies" },- { id: 12, username: "server" },- ],- });- });- });-- needs.settings({- chat_enabled: true,- });-- needs.hooks.beforeEach(function () {- Object.defineProperty(this, "chatService", {- get: () => this.container.lookup("service:chat"),- });- });-- test("channel selector opens channel in float", async function (assert) {- await visit("/latest");- await showModal("chat-channel-selector-modal");- await settled();-- assert.ok(exists("#chat-channel-selector-modal-inner"));-- // All channels should show because the input is blank- assert.equal(- queryAll("#chat-channel-selector-modal-inner .chat-channel-selection-row")- .length,- 9- );-- // Freaking keyup event isn't triggered by fillIn...- // Next line manually keyup's "r" to make the keyup event run.- // fillIn is needed for `this.filter` but triggerKeyEvent is needed to fire the JS event.- await fillIn("#chat-channel-selector-input", "s");- await triggerKeyEvent("#chat-channel-selector-input", "keyup", "R");-- // Only 4 channels match this filter now!- assert.equal(- queryAll("#chat-channel-selector-modal-inner .chat-channel-selection-row")- .length,- 4- );-- await triggerKeyEvent(document.body, "keyup", "Enter");-- assert.ok(exists(".chat-drawer.is-expanded"));- assert.notOk(exists("#chat-channel-selector-modal-inner"));- assert.equal(currentURL(), "/latest");- });-- test("the current chat channel does not show in the channel selector list", async function (assert) {- await visit("/chat/channel/75/@hawk");- await showModal("chat-channel-selector-modal");- await settled();-- // All channels minus 1- assert.equal(- queryAll("#chat-channel-selector-modal-inner .chat-channel-selection-row")- .length,- 8- );- assert.notOk(- exists(- "#chat-channel-selector-modal-inner .chat-channel-selection-row.chat-channel-9"- )- );- });-- test("switching channel with alt+arrow keys in full page chat", async function (assert) {- this.container.lookup("service:chat").set("chatWindowFullPage", true);- await visit("/chat/channel/75/@hawk");- await triggerKeyEvent(document.body, "keydown", "ArrowDown", {- altKey: true,- });- assert.equal(currentURL(), "/chat/channel/76/eviltrout-markvanlan");- await triggerKeyEvent(document.body, "keydown", "ArrowDown", {- altKey: true,- });- assert.equal(currentURL(), "/chat/channel/11/another-category");- await triggerKeyEvent(document.body, "keydown", "ArrowDown", {- altKey: true,- });- assert.equal(currentURL(), "/chat/channel/7/bug");- await triggerKeyEvent(document.body, "keydown", "ArrowUp", {- altKey: true,- });- assert.equal(currentURL(), "/chat/channel/11/another-category");- await triggerKeyEvent(document.body, "keydown", "ArrowUp", {- altKey: true,- });- assert.equal(currentURL(), "/chat/channel/76/eviltrout-markvanlan");- await triggerKeyEvent(document.body, "keydown", "ArrowUp", {- altKey: true,- });- assert.equal(currentURL(), "/chat/channel/75/hawk");- });-- test("switching channel with alt+arrow keys in float", async function (assert) {- await visit("/latest");- await click(".header-dropdown-toggle.open-chat");- await click('.chat-channel-row[data-chat-channel-id="4"]');-- assert.ok(exists(`.chat-drawer.is-expanded[data-chat-channel-id="4"]`));-- await triggerKeyEvent(document.body, "keydown", "ArrowDown", {- altKey: true,- });-- assert.ok(exists(`.chat-drawer.is-expanded[data-chat-channel-id="10`));-- await triggerKeyEvent(document.body, "keydown", "ArrowUp", {- altKey: true,- });- assert.ok(exists(`.chat-drawer.is-expanded[data-chat-channel-id="4"]`));- });-- test("simple composer formatting shortcuts", async function (assert) {- await visit("/latest");- await click(".header-dropdown-toggle.open-chat");- await click(".chat-channel-row");-- const composerInput = query(".chat-composer-input");- await fillIn(composerInput, "test text");- await focus(composerInput);- composerInput.selectionStart = 0;- composerInput.selectionEnd = 9;- await triggerKeyEvent(composerInput, "keydown", "B", MODIFIER_OPTIONS);-- assert.strictEqual(- composerInput.value,- "**test text**",- "selection should get the bold markdown"- );- await fillIn(composerInput, "test text");- await focus(composerInput);- composerInput.selectionStart = 0;- composerInput.selectionEnd = 9;- await triggerKeyEvent(composerInput, "keydown", "I", MODIFIER_OPTIONS);-- assert.strictEqual(- composerInput.value,- "_test text_",- "selection should get the italic markdown"- );- await fillIn(composerInput, "test text");- await focus(composerInput);- composerInput.selectionStart = 0;- composerInput.selectionEnd = 9;- await triggerKeyEvent(composerInput, "keydown", "E", MODIFIER_OPTIONS);-- assert.strictEqual(- composerInput.value,- "`test text`",- "selection should get the code markdown"- );- });-- test("editing last non staged message", async function (assert) {- const stagedMessageText = "This is a test";- await visit("/latest");-- await click(".header-dropdown-toggle.open-chat");- await click(".chat-channel-row");- await fillIn(".chat-composer-input", stagedMessageText);- await click(".chat-composer-inline-button");- await triggerKeyEvent(".chat-composer-input", "keydown", "ArrowUp");-- assert.notEqual(- query(".chat-composer-input").value.trim(),- stagedMessageText- );- });-- test("insert link shortcut", async function (assert) {- await visit("/latest");-- await click(".header-dropdown-toggle.open-chat");- await click(".chat-channel-row");-- await focus(".chat-composer-input");- await fillIn(".chat-composer-input", "This is a link to ");- await triggerKeyEvent(- ".chat-composer-input",- "keydown",- "L",- MODIFIER_OPTIONS- );- assert.ok(exists(".insert-link.modal-body"), "hyperlink modal visible");-- await fillIn(".modal-body .link-url", "google.com");- await fillIn(".modal-body .link-text", "Google");- await click(".modal-footer button.btn-primary");-- assert.strictEqual(- query(".chat-composer-input").value,- "This is a link to [Google](https://google.com)",- "adds link with url and text, prepends 'https://'"- );-- assert.ok(- !exists(".insert-link.modal-body"),- "modal dismissed after submitting link"- );- });-- test("Pressing Escape when full page is opened", async function (assert) {- await visit("/chat/channel/75/@hawk");- const composerInput = query(".chat-composer-input");- await focus(composerInput);- await triggerKeyEvent(composerInput, "keydown", "Escape");-- assert.equal(- currentURL(),- "/chat/channel/75/hawk",- "it doesn’t close full page chat"- );-- assert.ok(- exists(".chat-message-container[data-id='177']"),- "it doesn’t remove channel content"- );- });-});diff --git a/plugins/chat/test/javascripts/acceptance/chat-live-pane-collapse-test.js b/plugins/chat/test/javascripts/acceptance/chat-live-pane-collapse-test.jsindex 948b2b20f62..3874fb8b3a8 100644--- a/plugins/chat/test/javascripts/acceptance/chat-live-pane-collapse-test.js+++ b/plugins/chat/test/javascripts/acceptance/chat-live-pane-collapse-test.js@@ -4,7 +4,7 @@ import {exists,visible,} from "discourse/tests/helpers/qunit-helpers";-import { test } from "qunit";+import { skip } from "qunit";acceptance("Discourse Chat - Chat live pane collapse", function (needs) {needs.user({@@ -106,7 +106,7 @@ acceptance("Discourse Chat - Chat live pane collapse", function (needs) {);});- test("can collapse and expand youtube chat", async function (assert) {+ skip("can collapse and expand youtube chat", async function (assert) {const youtubeContainer = ".chat-message-container[data-id='1'] .lazyYT";const expandImage =".chat-message-container[data-id='1'] .chat-message-collapser-closed";@@ -132,7 +132,7 @@ acceptance("Discourse Chat - Chat live pane collapse", function (needs) {assert.notOk(exists(expandImage), "the close arrow is hidden again");});- test("lightbox shows up before and after expand and collapse", async function (assert) {+ skip("lightbox shows up before and after expand and collapse", async function (assert) {const lightboxImage = ".mfp-img";const image = ".chat-message-container[data-id='2'] .chat-img-upload";const expandImage =diff --git a/plugins/chat/test/javascripts/acceptance/chat-live-pane-mobile-test.js b/plugins/chat/test/javascripts/acceptance/chat-live-pane-mobile-test.jsdeleted file mode 100644index e07872abd88..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-live-pane-mobile-test.js+++ /dev/null@@ -1,93 +0,0 @@-import { click, visit } from "@ember/test-helpers";-import { acceptance, exists } from "discourse/tests/helpers/qunit-helpers";-import { test } from "qunit";--acceptance("Discourse Chat - Chat live pane mobile", function (needs) {- needs.mobileView();- needs.user({- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- });- needs.pretender((server, helper) => {- server.get("/chat/:chatChannelId/messages.json", () =>- helper.response({- meta: {- can_flag: true,- user_silenced: true,- },- chat_messages: [- {- id: 1,- message: "hi",- cooked: "<p>hi</p>",- excerpt: "hi",- created_at: "2021-07-20T08:14:16.950Z",- flag_count: 0,- user: {- avatar_template:- "/letter_avatar_proxy/v4/letter/t/a9a28c/{size}.png",- id: 1,- name: "Tomtom",- username: "tomtom",- },- },- {- id: 2,- message: "hi",- cooked: "<p>hi</p>",- excerpt: "hi",- created_at: "2021-07-20T08:14:16.950Z",- flag_count: 0,- user: {- avatar_template:- "/letter_avatar_proxy/v4/letter/t/a9a28c/{size}.png",- id: 1,- name: "Tomtom",- username: "tomtom",- },- },- ],- })- );-- server.get("/chat/chat_channels.json", () =>- helper.response({- public_channels: [],- direct_message_channels: [],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- })- );-- server.get("/chat/chat_channels/:chatChannelId", () =>- helper.response({ id: 1, title: "something" })- );- });-- test("touching message", async function (assert) {- await visit("/chat/channel/1/cat");-- const messageExists = (id) => {- return exists(- `.chat-message-container[data-id='${id}'] .chat-message-selected`- );- };-- assert.notOk(messageExists(1));- assert.notOk(messageExists(2));-- await click(".chat-message-container[data-id='1']");-- assert.notOk(messageExists(1), "it doesn’t select the touched message");- });-});diff --git a/plugins/chat/test/javascripts/acceptance/chat-live-pane-silenced-user-test.js b/plugins/chat/test/javascripts/acceptance/chat-live-pane-silenced-user-test.jsdeleted file mode 100644index 6b15f565438..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-live-pane-silenced-user-test.js+++ /dev/null@@ -1,93 +0,0 @@-import { visit } from "@ember/test-helpers";-import {- acceptance,- exists,- query,-} from "discourse/tests/helpers/qunit-helpers";-import { test } from "qunit";--acceptance("Discourse Chat - Chat live pane", function (needs) {- needs.user({- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- navigation_menu: "legacy",- });- needs.pretender((server, helper) => {- server.get("/chat/:chatChannelId/messages.json", () =>- helper.response({- meta: {- can_flag: true,- user_silenced: true,- },- chat_messages: [- {- id: 1,- message: "hi",- cooked: "<p>hi</p>",- excerpt: "hi",- created_at: "2021-07-20T08:14:16.950Z",- flag_count: 0,- user: {- avatar_template:- "/letter_avatar_proxy/v4/letter/t/a9a28c/{size}.png",- id: 1,- name: "Tomtom",- username: "tomtom",- },- reactions: {- heart: {- count: 1,- reacted: false,- users: [{ id: 99, username: "im-penar" }],- },- },- },- ],- })- );-- server.get("/chat/chat_channels.json", () =>- helper.response({- public_channels: [- {- id: 1,- title: "something",- current_user_membership: { following: true },- message_bus_last_ids: {- new_mentions: 0,- new_messages: 0,- },- },- ],- direct_message_channels: [],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- })- );-- server.get("/chat/chat_channels/:chatChannelId", () =>- helper.response({- id: 1,- title: "something",- current_user_membership: { following: true },- })- );- });-- test("Textarea and message interactions are disabled when user is silenced", async function (assert) {- await visit("/chat/channel/1/cat");- assert.equal(query(".chat-composer-input").disabled, true);- assert.notOk(exists(".chat-message-actions-container"));- assert.notOk(exists(".chat-message-react-btn"));- });-});diff --git a/plugins/chat/test/javascripts/acceptance/chat-live-pane-test.js b/plugins/chat/test/javascripts/acceptance/chat-live-pane-test.jsindex 16d31f06195..acbf425896d 100644--- a/plugins/chat/test/javascripts/acceptance/chat-live-pane-test.js+++ b/plugins/chat/test/javascripts/acceptance/chat-live-pane-test.js@@ -1,190 +1,6 @@-import { click, fillIn, tap, triggerEvent, visit } from "@ember/test-helpers";-import {- acceptance,- exists,- loggedInUser,- publishToMessageBus,- query,-} from "discourse/tests/helpers/qunit-helpers";-import { test } from "qunit";-import { generateChatView } from "discourse/plugins/chat/chat-fixtures";--function buildMessage(messageId) {- return {- id: messageId,- message: "hi",- cooked: "<p>hi</p>",- excerpt: "hi",- created_at: "2021-07-20T08:14:16.950Z",- flag_count: 0,- user: {- avatar_template: "/letter_avatar_proxy/v4/letter/t/a9a28c/{size}.png",- id: 1,- name: "Tomtom",- username: "tomtom",- },- };-}--acceptance(- "Discourse Chat - Chat live pane - viewing old messages",- function (needs) {- needs.user({- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- navigation_menu: "legacy",- });-- let loadAllMessages = false;-- needs.hooks.beforeEach(() => {- loadAllMessages = false;- });-- needs.pretender((server, helper) => {- const firstPageMessages = [];-- for (let i = 0; i < 50; i++) {- firstPageMessages.push(buildMessage(i + 1));- }-- server.get("/chat/:chatChannelId/messages.json", () => {- if (loadAllMessages) {- const updatedPage = [...firstPageMessages];- updatedPage.shift();- updatedPage.shift();- updatedPage.push(buildMessage(51));- updatedPage.push(buildMessage(52));-- return helper.response({- meta: {- can_load_more_future: false,- },- chat_messages: updatedPage,- });- } else {- return helper.response({- meta: {- can_flag: true,- user_silenced: false,- can_load_more_future: true,- },- chat_messages: firstPageMessages,- });- }- });-- server.get("/chat/chat_channels.json", () =>- helper.response({- public_channels: [- {- id: 1,- title: "something",- current_user_membership: { following: true },- message_bus_last_ids: {- new_mentions: 0,- new_messages: 0,- },- },- ],- direct_message_channels: [],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- })- );-- server.get("/chat/chat_channels/:chatChannelId", () =>- helper.response({ id: 1, title: "something" })- );-- server.post("/chat/drafts", () => {- return helper.response([]);- });-- server.post("/chat/:chatChannelId.json", () => {- return helper.response({ success: "OK" });- });- });-- test("doesn't create a gap in history by adding new messages", async function (assert) {- await visit("/chat/channel/1/cat");-- await publishToMessageBus("/chat/1", {- type: "sent",- chat_message: {- id: 51,- cooked: "<p>hello!</p>",- user: {- id: 2,- },- },- });-- assert.notOk(exists(`.chat-message-container[data-id='${51}']`));- });-- test("It continues to handle other message types", async function (assert) {- await visit("/chat/channel/1/cat");-- await publishToMessageBus("/chat/1", {- action: "add",- user: { id: 77, username: "notTomtom" },- emoji: "cat",- type: "reaction",- chat_message_id: 1,- });-- assert.ok(exists(`.chat-message-reaction[data-emoji-name="cat"]`));- });-- test("Sending a new message when there are still unloaded ones will fetch them", async function (assert) {- await visit("/chat/channel/1/cat");-- assert.notOk(exists(`.chat-message-container[data-id='${51}']`));-- loadAllMessages = true;- const composerInput = query(".chat-composer-input");- await fillIn(composerInput, "test text");- await click(".send-btn");-- assert.ok(exists(`.chat-message-container[data-id='${51}']`));- assert.ok(exists(`.chat-message-container[data-id='${52}']`));- });-- test("Clicking the arrow button jumps to the bottom of the channel", async function (assert) {- await visit("/chat/channel/1/cat");-- assert.notOk(exists(`.chat-message-container[data-id='${51}']`));- const scrollerEl = document.querySelector(".chat-messages-scroll");- scrollerEl.scrollTop = -500; // Scroll up a bit- const initialPosition = scrollerEl.scrollTop;- await triggerEvent(".chat-messages-scroll", "scroll", {- forceShowScrollToBottom: true,- });-- loadAllMessages = true;- await click(".chat-scroll-to-bottom");-- assert.ok(exists(`.chat-message-container[data-id='${51}']`));- assert.ok(exists(`.chat-message-container[data-id='${52}']`));-- assert.ok(- scrollerEl.scrollTop > initialPosition,- "Scrolled to the bottom"- );- });- }-);+import { click, visit } from "@ember/test-helpers";+import { acceptance, exists } from "discourse/tests/helpers/qunit-helpers";+import { skip } from "qunit";acceptance("Discourse Chat - Chat live pane - handling 429 errors",@@ -238,7 +54,7 @@ acceptance(});});- test("Handles 429 errors by displaying an alert", async function (assert) {+ skip("Handles 429 errors by displaying an alert", async function (assert) {await visit("/chat/channel/1/cat");assert.ok(exists(".dialog-content"), "We displayed a 429 error");@@ -246,105 +62,3 @@ acceptance(});});--acceptance(- "Discourse Chat - Chat live pane - handling 404 errors",- function (needs) {- needs.user({- username: "eviltrout",- id: 1,- has_chat_enabled: true,- });-- needs.settings({ chat_enabled: true });-- needs.pretender((server, helper) => {- server.get("/chat/:chatChannelId/messages.json", () => {- return helper.response(404);- });-- server.get("/chat/chat_channels.json", () =>- helper.response({- public_channels: [],- direct_message_channels: [],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- })- );-- server.get("/chat/chat_channels/:chatChannelId", () =>- helper.response({ id: 1, title: "something" })- );-- server.get("/chat/lookup/:messageId.json", () => {- return helper.response(404);- });- });-- test("Handles 404 errors by displaying an alert", async function (assert) {- await visit("/chat/channel/1/cat");-- assert.ok(exists(".dialog-content"), "it displays a 404 error");- await click(".dialog-footer .btn-primary");- });-- test("Handles 404 errors with unexisting messageId", async function (assert) {- await visit("/chat/channel/1/cat?messageId=2");-- assert.ok(exists(".dialog-content"), "it displays a 404 error");- await click(".dialog-footer .btn-primary");- });- }-);--acceptance(- "Discourse Chat - Chat live pane (mobile) - actions menu",- function (needs) {- needs.user({ has_chat_enabled: true });-- needs.settings({ chat_enabled: true });-- needs.mobileView();-- needs.pretender((server, helper) => {- server.get("/chat/:chatChannelId/messages.json", () =>- helper.response(generateChatView(loggedInUser()))- );-- server.get("/chat/chat_channels.json", () =>- helper.response({- public_channels: [],- direct_message_channels: [],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- })- );-- server.get("/chat/chat_channels/:chatChannelId", () =>- helper.response({ id: 1, title: "something" })- );- });-- test("when expanding and collapsing the actions menu", async function (assert) {- await visit("/chat/channel/1/cat");- const message = query(".chat-message-container");- await tap(message);-- assert.ok(exists(".chat-message-actions-backdrop"));-- await tap(".collapse-area");-- assert.notOk(exists(".chat-message-actions-backdrop"));- });- }-);diff --git a/plugins/chat/test/javascripts/acceptance/chat-message-bookmarking-test.js b/plugins/chat/test/javascripts/acceptance/chat-message-bookmarking-test.jsdeleted file mode 100644index eb4a2510910..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-message-bookmarking-test.js+++ /dev/null@@ -1,165 +0,0 @@-import { test } from "qunit";-import { click, fillIn, tap, triggerEvent, visit } from "@ember/test-helpers";-import {- acceptance,- exists,- loggedInUser,- query,-} from "discourse/tests/helpers/qunit-helpers";-import {- chatChannels,- generateChatView,-} from "discourse/plugins/chat/chat-fixtures";--function setupPretenders(server, helper) {- server.get("/chat/chat_channels.json", () => helper.response(chatChannels));- server.get("/chat/:chat_channel_id/messages.json", () =>- helper.response(generateChatView(loggedInUser()))- );- server.post("/uploads/lookup-urls", () => {- return helper.response([]);- });-}--acceptance("Discourse Chat | bookmarking | desktop", function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });-- needs.settings({- chat_enabled: true,- });-- needs.pretender((server, helper) => {- setupPretenders(server, helper);- server.post("/bookmarks", () => helper.response({ id: 1, success: "OK" }));- });-- test("can bookmark a message with reminder from the quick actions menu", async function (assert) {- await visit("/chat/channel/4/public-category");- assert.ok(exists(".chat-message-container"));- const message = query(".chat-message-container");-- await triggerEvent(message, "mouseenter");- await click(".chat-message-actions .bookmark-btn");- assert.ok(- exists("#bookmark-reminder-modal"),- "it shows the bookmark modal"- );- await fillIn("input#bookmark-name", "Check this out later");- await click("#tap_tile_next_month");- assert.ok(- message.querySelector(- ".chat-message-info__bookmark .d-icon-discourse-bookmark-clock"- ),- "the message should be bookmarked and show the icon on the message info"- );- assert.ok(- ".chat-message-actions .bookmark-btn .d-icon-discourse-bookmark-clock",- "the message actions icon shows the reminder icon"- );- });-- test("can bookmark a message without reminder from the quick actions menu", async function (assert) {- await visit("/chat/channel/4/public-category");- assert.ok(exists(".chat-message-container"));- const message = query(".chat-message-container");-- await triggerEvent(message, "mouseenter");- await click(".chat-message-actions .bookmark-btn");- assert.ok(- exists("#bookmark-reminder-modal"),- "it shows the bookmark modal"- );- await fillIn("input#bookmark-name", "Check this out later");- await click("#tap_tile_none");- assert.ok(- exists(".chat-message-info__bookmark .d-icon-bookmark"),- "the message should be bookmarked and show the icon on the message info"- );- assert.ok(- exists(".chat-message-actions .bookmark-btn .d-icon-bookmark"),- "the message actions icon shows the bookmark icon"- );- });-});--acceptance("Discourse Chat | bookmarking | mobile", function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });-- needs.settings({- chat_enabled: true,- });-- needs.pretender((server, helper) => {- setupPretenders(server, helper);- server.post("/bookmarks", () => helper.response({ id: 1, success: "OK" }));- });-- needs.mobileView();-- test("can bookmark a message with reminder from the mobile long press menu", async function (assert) {- await visit("/chat/channel/4/public-category");- assert.ok(exists(".chat-message-container"));- const message = query(".chat-message-container");-- await tap(message);- await click(".main-actions .bookmark-btn");-- assert.ok(- exists("#bookmark-reminder-modal"),- "it shows the bookmark modal"- );- await fillIn("input#bookmark-name", "Check this out later");- await click("#tap_tile_next_month");- assert.ok(- message.querySelector(- ".chat-message-info__bookmark .d-icon-discourse-bookmark-clock"- ),- "the message should be bookmarked and show the icon on the message info"- );-- await tap(message);- assert.ok(- exists(".main-actions .bookmark-btn .d-icon-discourse-bookmark-clock"),- "the message actions icon shows the reminder icon"- );- });-- test("can bookmark a message without reminder from the quick actions menu", async function (assert) {- await visit("/chat/channel/4/public-category");- assert.ok(exists(".chat-message-container"));- const message = query(".chat-message-container");-- await tap(message);- await click(".main-actions .bookmark-btn");- assert.ok(- exists("#bookmark-reminder-modal"),- "it shows the bookmark modal"- );- await fillIn("input#bookmark-name", "Check this out later");- await click("#tap_tile_none");- assert.ok(- message.querySelector(".chat-message-info__bookmark .d-icon-bookmark"),- "the message should be bookmarked and show the icon on the message info"- );-- await tap(message);- assert.ok(- exists(".main-actions .bookmark-btn .d-icon-bookmark"),- "the message actions icon shows the bookmark icon"- );- });-});diff --git a/plugins/chat/test/javascripts/acceptance/chat-message-test.js b/plugins/chat/test/javascripts/acceptance/chat-message-test.jsdeleted file mode 100644index 776fd607f93..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-message-test.js+++ /dev/null@@ -1,99 +0,0 @@-import {- acceptance,- loggedInUser,-} from "discourse/tests/helpers/qunit-helpers";-import { click, triggerEvent, visit } from "@ember/test-helpers";-import { test } from "qunit";-import {- chatChannels,- generateChatView,-} from "discourse/plugins/chat/chat-fixtures";--function setupPretenders(server, helper) {- server.get("/chat/chat_channels.json", () => helper.response(chatChannels));- server.get("/chat/:chat_channel_id/messages.json", () =>- helper.response(generateChatView(loggedInUser()))- );- server.get("/chat/emojis.json", () =>- helper.response({ favorites: [{ name: "grinning" }] })- );- server.put("/chat/:id/react/:message_id.json", helper.response);-}--acceptance("Discourse Chat - Chat Message", function (needs) {- needs.user({ has_chat_enabled: true });- needs.settings({ chat_enabled: true });- needs.pretender((server, helper) => setupPretenders(server, helper));-- test("when reacting to a message using inline reaction", async function (assert) {- const emojiReactionStore = this.container.lookup(- "service:chat-emoji-reaction-store"- );-- assert.deepEqual(- emojiReactionStore.favorites,- this.siteSettings.default_emoji_reactions.split("|")- );-- await visit("/chat/channel/4/public-category");- await click(- `.chat-message-container[data-id="176"] .chat-message-reaction[data-emoji-name="heart"]`- );-- assert.deepEqual(- emojiReactionStore.favorites,- ["heart"].concat(- this.siteSettings.default_emoji_reactions- .split("|")- .filter((r) => r !== "heart")- ),- "it tracks the emoji"- );-- await click(- `.chat-message-container[data-id="176"] .chat-message-reaction[data-emoji-name="heart"]`- );-- assert.deepEqual(- emojiReactionStore.favorites,- ["heart"].concat(- this.siteSettings.default_emoji_reactions- .split("|")- .filter((r) => r !== "heart")- ),- "it doesn’t untrack when removing the reaction"- );- });-- test("when reacting to a message using emoji picker reaction", async function (assert) {- const emojiReactionStore = this.container.lookup(- "service:chat-emoji-reaction-store"- );-- assert.deepEqual(- emojiReactionStore.favorites,- this.siteSettings.default_emoji_reactions.split("|")- );-- await visit("/chat/channel/4/public-category");- await triggerEvent(".chat-message-container[data-id='176']", "mouseenter");- await click(".chat-message-actions-container .react-btn");- await click(`[data-emoji="grinning"]`);-- assert.deepEqual(- emojiReactionStore.favorites,- ["grinning"].concat(this.siteSettings.default_emoji_reactions.split("|")),- "it tracks the emoji"- );-- await click(- `.chat-message-container[data-id="176"] .chat-message-reaction[data-emoji-name="grinning"]`- );-- assert.deepEqual(- emojiReactionStore.favorites,- ["grinning"].concat(this.siteSettings.default_emoji_reactions.split("|")),- "it doesn’t untrack when removing the reaction"- );- });-});diff --git a/plugins/chat/test/javascripts/acceptance/chat-move-message-to-channel-test.js b/plugins/chat/test/javascripts/acceptance/chat-move-message-to-channel-test.jsdeleted file mode 100644index 1d0db0ad4fa..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-move-message-to-channel-test.js+++ /dev/null@@ -1,183 +0,0 @@-import { test } from "qunit";-import { click, currentURL, triggerEvent, visit } from "@ember/test-helpers";-import {- acceptance,- exists,- loggedInUser,- query,-} from "discourse/tests/helpers/qunit-helpers";-import {- chatChannels,- generateChatView,-} from "discourse/plugins/chat/chat-fixtures";-import selectKit from "discourse/tests/helpers/select-kit-helper";--function setupPretenders(server, helper) {- server.get("/chat/chat_channels.json", () => helper.response(chatChannels));- server.post("/uploads/lookup-urls", () => {- return helper.response([]);- });- server.put("/chat/4/move_messages_to_channel.json", () => {- return helper.response({- destination_channel_id: 11,- destination_channel_title: "Coolest thing you have seen today",- first_moved_message_id: 174,- });- });- server.get("/chat/:chat_channel_id/messages.json", () =>- helper.response(generateChatView(loggedInUser()))- );- server.get("/chat/lookup/:messageId.json", () =>- helper.response(generateChatView(loggedInUser()))- );-}--acceptance(- "Discourse Chat | moving messages to a channel | staff user",- function (needs) {- needs.user({- admin: true,- moderator: true,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });-- needs.settings({- chat_enabled: true,- });-- needs.pretender((server, helper) => {- setupPretenders(server, helper);- });-- test("opens a modal for destination channel selection then redirects to the moved messages when done", async function (assert) {- await visit("/chat/channel/4/public-category");- assert.ok(exists(".chat-message-container"));- const firstMessage = query(".chat-message-container");- await triggerEvent(firstMessage, "mouseenter");- const dropdown = selectKit(".chat-message-actions .more-buttons");- await dropdown.expand();- await dropdown.selectRowByValue("selectMessage");-- assert.ok(firstMessage.classList.contains("selecting-messages"));- const moveToChannelBtn = query(- ".chat-live-pane #chat-move-to-channel-btn"- );- assert.equal(- moveToChannelBtn.disabled,- false,- "button is enabled as a message is selected"- );-- await click(firstMessage.querySelector("input[type='checkbox']"));- assert.equal(- moveToChannelBtn.disabled,- true,- "button is disabled when no messages are selected"- );-- await click(firstMessage.querySelector("input[type='checkbox']"));- await click("#chat-move-to-channel-btn");- const modalConfirmMoveButton = query(- "#chat-confirm-move-messages-to-channel"- );- assert.ok(- modalConfirmMoveButton.disabled,- "cannot confirm move until channel is selected"- );- const channelChooser = selectKit(".chat-move-message-channel-chooser");- await channelChooser.expand();- assert.notOk(- channelChooser.rowByValue("4").exists(),- "the source channel is not in the destination channel selector"- );-- await channelChooser.selectRowByValue("11");- await click(modalConfirmMoveButton);-- assert.strictEqual(- currentURL(),- "/chat/channel/11/another-category",- "it goes to the destination channel after the move"- );- });-- test("does not allow moving messages from a direct message channel", async function (assert) {- await visit("/chat/channel/75/@hawk");- assert.ok(exists(".chat-message-container"));- const firstMessage = query(".chat-message-container");- await triggerEvent(firstMessage, "mouseenter");- const dropdown = selectKit(".chat-message-actions .more-buttons");- await dropdown.expand();- await dropdown.selectRowByValue("selectMessage");- assert.ok(firstMessage.classList.contains("selecting-messages"));- assert.notOk(- exists(".chat-live-pane #chat-move-to-channel-btn"),- "the move to channel button is not shown in direct message channels"- );- });- }-);--acceptance(- "Discourse Chat | moving messages to a channel | non-staff user",- function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });-- needs.settings({- chat_enabled: true,- });-- needs.pretender((server, helper) => {- setupPretenders(server, helper);- server.get("/chat/11/messages.json", () => {- return helper.response(- generateChatView(loggedInUser(), { can_moderate: true })- );- });- });-- test("non-staff users cannot see the move to channel button", async function (assert) {- await visit("/chat/channel/4/public-category");- assert.ok(exists(".chat-message-container"));- const firstMessage = query(".chat-message-container");- await triggerEvent(firstMessage, "mouseenter");- const dropdown = selectKit(".chat-message-actions .more-buttons");- await dropdown.expand();- await dropdown.selectRowByValue("selectMessage");-- assert.ok(firstMessage.classList.contains("selecting-messages"));- assert.notOk(- exists(".chat-live-pane #chat-move-to-channel-btn"),- "non-staff users cannot see the move to channel button"- );- });-- test("non-staff users can see the move to channel button if they can_moderate the channel", async function (assert) {- await visit("/chat/channel/11/another-category");- assert.ok(exists(".chat-message-container"));- const firstMessage = query(".chat-message-container");- await triggerEvent(firstMessage, "mouseenter");- const dropdown = selectKit(- `.chat-message-actions-container[data-id="${firstMessage.dataset.id}"] .more-buttons`- );- await dropdown.expand();- await dropdown.selectRowByValue("selectMessage");-- assert.ok(firstMessage.classList.contains("selecting-messages"));- assert.ok(- exists(".chat-live-pane #chat-move-to-channel-btn"),- "non-staff users can see the move to channel button if can_moderate"- );- });- }-);diff --git a/plugins/chat/test/javascripts/acceptance/chat-preferences-test.js b/plugins/chat/test/javascripts/acceptance/chat-preferences-test.jsdeleted file mode 100644index 80ed0d4a880..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-preferences-test.js+++ /dev/null@@ -1,34 +0,0 @@-import { acceptance } from "discourse/tests/helpers/qunit-helpers";-import { visit } from "@ember/test-helpers";-import { test } from "qunit";-import { chatChannels } from "discourse/plugins/chat/chat-fixtures";-import selectKit from "discourse/tests/helpers/select-kit-helper";-import { CHAT_SOUNDS } from "discourse/plugins/chat/discourse/services/chat-audio-manager";--function preferencesPretender(server, helper) {- server.get("/u/eviltrout/activity.json", () => helper.response({}));- server.get("/chat/chat_channels.json", () => helper.response(chatChannels));-}--acceptance("Discourse Chat | User Preferences", function (needs) {- needs.user({ can_chat: true, has_chat_enabled: true });- needs.settings({ chat_enabled: true });- needs.pretender(preferencesPretender);-- test("when user has no chat sound set", async function (assert) {- const sounds = Object.keys(CHAT_SOUNDS);- await visit("/u/eviltrout/preferences/chat");- const dropdown = selectKit("#user_chat_sounds");-- assert.strictEqual(dropdown.header().value(), null, "it displays no sound");-- await dropdown.expand();- await dropdown.selectRowByValue(sounds[1]);-- assert.strictEqual(- dropdown.header().value(),- sounds[1],- "it selects the sound"- );- });-});diff --git a/plugins/chat/test/javascripts/acceptance/chat-quoting-test.js b/plugins/chat/test/javascripts/acceptance/chat-quoting-test.jsdeleted file mode 100644index 63569a12ad0..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-quoting-test.js+++ /dev/null@@ -1,183 +0,0 @@-import { skip, test } from "qunit";-import {- click,- currentURL,- tap,- triggerEvent,- visit,-} from "@ember/test-helpers";-import {- acceptance,- exists,- loggedInUser,- query,- visible,-} from "discourse/tests/helpers/qunit-helpers";-import {- chatChannels,- generateChatView,-} from "discourse/plugins/chat/chat-fixtures";-import selectKit from "discourse/tests/helpers/select-kit-helper";--const quoteResponse = {- markdown: `[chat quote="martin-chat;3875498;2022-02-04T01:12:15Z" channel="The Beam Discussions" channelId="1234"]- an extremely insightful response :)- [/chat]`,-};--function setupPretenders(server, helper) {- server.get("/chat/chat_channels.json", () => helper.response(chatChannels));- server.post(`/chat/4/quote.json`, () => helper.response(quoteResponse));- server.post(`/chat/7/quote.json`, () => helper.response(quoteResponse));- server.get("/chat/:chat_channel_id/messages.json", () =>- helper.response(generateChatView(loggedInUser()))- );- server.post("/uploads/lookup-urls", () => {- return helper.response([]);- });-}--acceptance("Discourse Chat | Copying messages", function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });-- needs.settings({- chat_enabled: true,- });-- needs.pretender((server, helper) => {- setupPretenders(server, helper);- });-- test("it copies the quote and shows a message", async function (assert) {- await visit("/chat/channel/7/Bug");- assert.ok(exists(".chat-message-container"));-- const firstMessage = query(".chat-message-container");- await triggerEvent(firstMessage, "mouseenter");- const dropdown = selectKit(- `.chat-message-actions-container[data-id="${firstMessage.dataset.id}"] .more-buttons`- );- await dropdown.expand();- await dropdown.selectRowByValue("selectMessage");- assert.ok(firstMessage.classList.contains("selecting-messages"));-- const copyButton = query(".chat-live-pane #chat-copy-btn");- assert.equal(- copyButton.disabled,- false,- "button is enabled as a message is selected"- );-- await click(firstMessage.querySelector("input[type='checkbox']"));- assert.equal(- copyButton.disabled,- true,- "button is disabled when no messages are selected"- );-- await click(firstMessage.querySelector("input[type='checkbox']"));- await click("#chat-copy-btn");- assert.ok(exists(".chat-selection-message"), "shows the message");- });-});--acceptance("Discourse Chat | Quoting in composer", async function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });-- needs.settings({- chat_enabled: true,- });-- needs.pretender((server, helper) => {- setupPretenders(server, helper);- });-- skip("it opens the composer for the topic and pastes in the quote", async function (assert) {- await visit("/t/internationalization-localization/280");-- await click(".header-dropdown-toggle.open-chat");- assert.ok(visible(".chat-drawer-container"), "chat drawer is open");- assert.ok(exists(".chat-message-container"));-- const firstMessage = query(".chat-message-container");- await triggerEvent(firstMessage, "mouseenter");- const dropdown = selectKit(".chat-message-container .more-buttons");- await dropdown.expand();- await dropdown.selectRowByValue("selectMessage");- assert.ok(firstMessage.classList.contains("selecting-messages"));-- await click("#chat-quote-btn");- assert.ok(exists("#reply-control.composer-action-reply"));- assert.strictEqual(- query(".composer-action-title .action-title").innerText,- "Internationalization / localization"- );- assert.strictEqual(- query("textarea.d-editor-input").value,- quoteResponse.markdown- );- });-});--acceptance("Discourse Chat | Quoting on mobile", async function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });-- needs.settings({- chat_enabled: true,- });-- needs.pretender((server, helper) => {- setupPretenders(server, helper);- });-- needs.mobileView();-- skip("it opens the chatable, opens the composer, and pastes the markdown in", async function (assert) {- await visit("/chat/channel/7/Bug");- assert.ok(exists(".chat-message-container"));-- const firstMessage = query(".chat-message-container");- await tap(firstMessage);- await click(".chat-message-action-item[data-id='selectMessage'] button");- assert.ok(firstMessage.classList.contains("selecting-messages"));-- await click("#chat-quote-btn");-- assert.equal(currentURL(), "/c/bug/1", "navigates to the chatable url");- assert.ok(- exists("#reply-control.composer-action-createTopic"),- "the composer opens"- );- assert.strictEqual(- query("textarea.d-editor-input").value,- quoteResponse.markdown,- "the composer has the markdown"- );- assert.strictEqual(- selectKit(".category-chooser").header().value(),- "1",- "it fills category selector with the right category"- );- });-});diff --git a/plugins/chat/test/javascripts/acceptance/chat-sidebar-user-status-test.js b/plugins/chat/test/javascripts/acceptance/chat-sidebar-user-status-test.jsdeleted file mode 100644index 698b6a9cda8..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-sidebar-user-status-test.js+++ /dev/null@@ -1,127 +0,0 @@-import {- acceptance,- exists,- publishToMessageBus,- query,-} from "discourse/tests/helpers/qunit-helpers";-import { test } from "qunit";-import { visit } from "@ember/test-helpers";--acceptance("Discourse Chat - Sidebar - User Status", function (needs) {- const directMessageUserId = 1;- const status = { description: "off to dentist", emoji: "tooth" };-- needs.user({ has_chat_enabled: true });-- needs.settings({- chat_enabled: true,- navigation_menu: "sidebar",- });-- needs.pretender((server, helper) => {- const directMessageChannel = {- chatable: {- users: [- {- id: directMessageUserId,- username: "user1",- avatar_template:- "/letter_avatar_proxy/v4/letter/t/f9ae1b/{size}.png",- status,- },- ],- },- chatable_type: "DirectMessage",- title: "@user1",- message_bus_last_ids: {- new_mentions: 0,- new_messages: 0,- },- };-- server.get("/chat/chat_channels.json", () => {- return helper.response({- public_channels: [],- direct_message_channels: [directMessageChannel],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- });- });- });-- test("Shows user status", async function (assert) {- await visit("/");-- const statusEmoji = query(- ".sidebar-sections .sidebar-section-link-content-text .emoji"- );- assert.ok(statusEmoji, "status is shown");- assert.ok(- statusEmoji.src.includes(status.emoji),- "status emoji is correct"- );- assert.equal(- statusEmoji.title,- status.description,- "status description is correct"- );- });-- test("Status gets updated after receiving a message bus update", async function (assert) {- await visit("/");-- let statusEmoji = query(- ".sidebar-sections .sidebar-section-link-content-text .emoji"- );- assert.ok(statusEmoji, "old status is shown");- assert.ok(- statusEmoji.src.includes(status.emoji),- "old status emoji is correct"- );- assert.equal(- statusEmoji.title,- status.description,- "old status description is correct"- );-- const newStatus = { description: "surfing", emoji: "surfer" };- await publishToMessageBus(`/user-status`, {- [directMessageUserId]: newStatus,- });-- statusEmoji = query(- ".sidebar-sections .sidebar-section-link-content-text .emoji"- );- assert.ok(statusEmoji, "new status is shown");- assert.ok(- statusEmoji.src.includes(newStatus.emoji),- "new status emoji is correct"- );- assert.equal(- statusEmoji.title,- newStatus.description,- "new status description is correct"- );- });-- test("Status disappears after receiving a message bus update", async function (assert) {- await visit("/");-- let statusEmoji = query(- ".sidebar-sections .sidebar-section-link-content-text .emoji"- );- assert.ok(statusEmoji, "old status is shown");-- await publishToMessageBus(`/user-status`, { [directMessageUserId]: null });-- assert.notOk(- exists(".sidebar-sections .sidebar-section-link-content-text .emoji"),- "status has disappeared"- );- });-});diff --git a/plugins/chat/test/javascripts/acceptance/chat-status-test.js b/plugins/chat/test/javascripts/acceptance/chat-status-test.jsdeleted file mode 100644index e805d5eeb93..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-status-test.js+++ /dev/null@@ -1,111 +0,0 @@-import { visit } from "@ember/test-helpers";-import { cloneJSON } from "discourse-common/lib/object";-import {- chatChannels,- generateChatView,-} from "discourse/plugins/chat/chat-fixtures";-import {- acceptance,- exists,- loggedInUser,- publishToMessageBus,- query,-} from "discourse/tests/helpers/qunit-helpers";-import I18n from "I18n";-import { test } from "qunit";--const baseChatPretenders = (server, helper) => {- server.get("/chat/:chatChannelId/messages.json", () =>- helper.response(generateChatView(loggedInUser()))- );- server.post("/chat/:chatChannelId.json", () => {- return helper.response({ success: "OK" });- });- server.get("/chat/lookup/:messageId.json", () =>- helper.response(generateChatView(loggedInUser()))- );- server.post("/uploads/lookup-urls", () => {- return helper.response([]);- });- server.get("/chat/chat_channels.json", () => {- let copy = cloneJSON(chatChannels);- let modifiedChannel = copy.public_channels.find((pc) => pc.id === 4);- modifiedChannel.current_user_membership.unread_count = 2;- return helper.response(copy);- });-- // this is only fetched on channel-status change; when expanding on- // this test we may want to introduce some counter to track when- // this is fetched if we want to return different statuses- server.get("/chat/chat_channels/4", () => {- let channel = cloneJSON(- chatChannels.public_channels.find((pc) => pc.id === 4)- );- channel.status = "archived";- return helper.response(channel);- });-};--acceptance(- "Discourse Chat - Respond to /chat/channel-status archive message",- function (needs) {- needs.user({- admin: true,- moderator: true,- username: "tomtom",- id: 1,- can_chat: true,- has_chat_enabled: true,- });-- needs.settings({- chat_enabled: true,- chat_allow_archiving_channels: true,- navigation_menu: "legacy",- });-- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- });-- test("it clears any unread messages in the sidebar for the archived channel", async function (assert) {- await visit("/chat/channel/4/public-category");- assert.ok(- exists(- '.chat-channel-row[data-chat-channel-id="4"] .chat-channel-unread-indicator'- ),- "unread indicator shows for channel"- );-- await publishToMessageBus("/chat/channel-status", {- chat_channel_id: 4,- status: "archived",- });- assert.notOk(- exists(- '.chat-channel-row[data-chat-channel-id="4"] .chat-channel-unread-indicator'- ),- "unread indicator should not show after archive status change"- );- });-- test("it changes the channel status in the header to archived", async function (assert) {- await visit("/chat/channel/4/Topic");-- assert.notOk(- exists(".chat-channel-title-with-status .chat-channel-status"),- "channel status does not show if the channel is open"- );-- await publishToMessageBus("/chat/channel-status", {- chat_channel_id: 4,- status: "archived",- });- assert.strictEqual(- query(".chat-channel-status").innerText.trim(),- I18n.t("chat.channel_status.archived_header"),- "channel status changes to archived"- );- });- }-);diff --git a/plugins/chat/test/javascripts/acceptance/chat-test.js b/plugins/chat/test/javascripts/acceptance/chat-test.jsdeleted file mode 100644index 3c1ba477524..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-test.js+++ /dev/null@@ -1,1794 +0,0 @@-import { withPluginApi } from "discourse/lib/plugin-api";-import {- acceptance,- exists,- loggedInUser,- publishToMessageBus,- query,- queryAll,- updateCurrentUser,- visible,-} from "discourse/tests/helpers/qunit-helpers";-import {- click,- currentURL,- fillIn,- focus,- settled,- triggerEvent,- triggerKeyEvent,- visit,-} from "@ember/test-helpers";-import { skip, test } from "qunit";-import {- chatChannels,- messageContents,-} from "discourse/plugins/chat/chat-fixtures";-import Session from "discourse/models/session";-import { cloneJSON } from "discourse-common/lib/object";-import {- joinChannel,- leaveChannel,- presentUserIds,-} from "discourse/tests/helpers/presence-pretender";-import User from "discourse/models/user";-import selectKit from "discourse/tests/helpers/select-kit-helper";-import sinon from "sinon";-import * as ajaxModule from "discourse/lib/ajax";-import I18n from "I18n";-import { CHANNEL_STATUSES } from "discourse/plugins/chat/discourse/models/chat-channel";-import fabricators from "../helpers/fabricators";-import {- baseChatPretenders,- chatChannelPretender,- directMessageChannelPretender,-} from "../helpers/chat-pretenders";--acceptance("Discourse Chat - anonymouse 🐭 user", function (needs) {- needs.settings({- chat_enabled: true,- });-- test("doesn't error for anonymous users", async function (assert) {- await visit("");- assert.ok(true, "no errors on homepage");- });-});--acceptance("Discourse Chat - without unread", function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- navigation_menu: "legacy",- chat_enabled: true,- });- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- directMessageChannelPretender(server, helper);- chatChannelPretender(server, helper);- const hawkAsJson = {- username: "hawk",- id: 2,- name: "hawk",- avatar_template: "/letter_avatar_proxy/v4/letter/t/41988e/{size}.png",- };- server.get("/u/search/users", () => {- return helper.response({- users: [hawkAsJson],- });- });- server.get("/chat/emojis.json", () =>- helper.response({ favorites: [{ name: "grinning" }] })- );-- server.put("/chat/:chat_channel_id/react/:messageId.json", helper.response);-- server.put("/chat/:chat_channel_id/invite", helper.response);- server.post("/chat/direct_messages/create.json", () => {- return helper.response({- chat_channel: {- chat_channels: [],- chatable: { users: [hawkAsJson] },- chatable_id: 16,- chatable_type: "DirectMessage",- chatable_url: null,- id: 75,- title: "@hawk",- last_message_sent_at: "2021-11-08T21:26:05.710Z",- current_user_membership: {- last_read_message_id: null,- unread_count: 0,- unread_mentions: 0,- },- },- });- });- server.post("/chat/chat_channels/:chatChannelId/unfollow.json", () => {- return helper.response({ current_user_membership: { following: false } });- });- server.get("/chat/direct_messages.json", () => {- return helper.response({- chat_channel: {- id: 75,- title: "hawk",- chatable_type: "DirectMessage",- last_message_sent_at: "2021-07-20T08:14:16.950Z",- chatable: {- users: [{ username: "hawk" }],- },- },- });- });- server.get("/u/hawk/card.json", () => {- return helper.response({});- });- });- needs.hooks.beforeEach(function () {- Object.defineProperty(this, "chatService", {- get: () => this.container.lookup("service:chat"),- });- Object.defineProperty(this, "appEvents", {- get: () => this.container.lookup("service:appEvents"),- });- Session.current().highlightJsPath =- "/assets/highlightjs/highlight-test-bundle.min.js";- });-- // TODO: needs a future change to how we handle URLS to be possible- skip("Clicking mention notification from outside chat opens the float", async function (assert) {- await visit("/t/internationalization-localization/280");- await click(".header-dropdown-toggle.current-user");- await click("#quick-access-notifications .chat-mention");- assert.ok(visible(".chat-drawer-container"), "drawer is open");- assert.ok(query(".chat-drawer-container").classList.contains("channel-9"));- });-- test("notifications for current user and here/all are highlighted", async function (assert) {- updateCurrentUser({ username: "osama" });- await visit("/chat/channel/11/another-category");- // 177 is message id from fixture- const highlighted = [];- const notHighlighted = [];- query(".chat-message-container[data-id='177']")- .querySelectorAll(".mention.highlighted")- .forEach((node) => {- highlighted.push(node.textContent.trim());- });- query(".chat-message-container[data-id='177']")- .querySelectorAll(".mention:not(.highlighted)")- .forEach((node) => {- notHighlighted.push(node.textContent.trim());- });- assert.equal(highlighted.length, 2, "2 mentions are highlighted");- assert.equal(notHighlighted.length, 1, "1 mention is regular mention");- assert.ok(highlighted.includes("@here"), "@here mention is highlighted");- assert.ok(highlighted.includes("@osama"), "@osama mention is highlighted");- assert.ok(- notHighlighted.includes("@mark"),- "@mark mention is not highlighted"- );- });-- test("Chat messages are populated when a channel is entered and images are rendered", async function (assert) {- await visit("/chat/channel/11/another-category");- const messages = queryAll(".chat-message .chat-message-text");- assert.equal(messages[0].innerText.trim(), messageContents[0]);-- assert.ok(messages[1].querySelector("a.chat-other-upload"));-- assert.equal(- messages[2].innerText.trim().split("\n")[0],- messageContents[2]- );- assert.ok(messages[2].querySelector("img.chat-img-upload"));- });-- test("Reply-to line is hidden when reply-to message is directly above", async function (assert) {- await visit("/chat/channel/11/another-category");- const messages = queryAll(".chat-message-container");- assert.notOk(messages[1].querySelector(".chat-reply__excerpt"));- });-- test("Reply-to line is present when reply-to message is not directly above", async function (assert) {- await visit("/chat/channel/11/another-category");- const messages = queryAll(".chat-message-container");- const replyTo = messages[2].querySelector(".chat-reply__excerpt");- assert.ok(replyTo);- assert.equal(replyTo.innerText.trim(), messageContents[0]);- });-- test("Unfollowing a direct message channel transitions to another channel", async function (assert) {- await visit("/chat/channel/75/@hawk");- await click(- '.chat-channel-row[data-chat-channel-id="75"] .toggle-channel-membership-button.-leave'- );-- assert.ok(/^\/chat\/channel\/4/.test(currentURL()));- });-- test("Admin only controls are present", async function (assert) {- await visit("/chat/channel/11/another-category");- await triggerEvent(".chat-message-container[data-id='174']", "mouseenter");-- const currentUserDropdown = selectKit(- ".chat-message-actions-container[data-id='174'] .more-buttons"- );- await currentUserDropdown.expand();-- assert.notOk(- currentUserDropdown.rowByValue("rebakeMessage").exists(),- "it doesn’t show the rebake button for non staff"- );-- updateCurrentUser({ admin: true, moderator: true });- await visit("/chat");-- await triggerEvent(".chat-message-container[data-id='174']", "mouseenter");- await currentUserDropdown.expand();-- assert.ok(- currentUserDropdown.rowByValue("rebakeMessage").exists(),- "it shows the rebake button"- );- });-- test("Message controls are present and correct for permissions", async function (assert) {- await visit("/chat/channel/11/another-category");- await triggerEvent(".chat-message-container[data-id='174']", "mouseenter");-- // User created this message- assert.ok(- ".chat-message-actions-container[data-id='174'] .reply-btn",- "it shows the reply button"- );-- const currentUserDropdown = selectKit(- ".chat-message-actions-container[data-id='174'] .more-buttons"- );- await currentUserDropdown.expand();-- assert.ok(- currentUserDropdown.rowByValue("copyLinkToMessage").exists(),- "it shows the link to button"- );-- assert.notOk(- currentUserDropdown.rowByValue("rebakeMessage").exists(),- "it doesn’t show the rebake button to a regular user"- );-- assert.ok(- currentUserDropdown.rowByValue("edit").exists(),- "it shows the edit button"- );-- assert.notOk(- currentUserDropdown.rowByValue("flag").exists(),- "it hides the flag button"- );-- assert.ok(- currentUserDropdown.rowByValue("deleteMessage").exists(),- "it shows the delete button"- );-- // User _didn't_ create this message- await triggerEvent(".chat-message-container[data-id='175']", "mouseenter");- assert.ok(- ".chat-message-actions-container[data-id='175'] .reply-btn",- "it shows the reply button"- );- const notCurrentUserDropdown = selectKit(- ".chat-message-actions-container[data-id='175'] .more-buttons"- );- await notCurrentUserDropdown.expand();-- assert.ok(- notCurrentUserDropdown.rowByValue("copyLinkToMessage").exists(),- "it shows the link to button"- );-- assert.notOk(- notCurrentUserDropdown.rowByValue("edit").exists(),- "it hides the edit button"- );-- assert.notOk(- notCurrentUserDropdown.rowByValue("deleteMessage").exists(),- "it hides the delete button"- );- });-- test("pressing the reply button adds the indicator to the composer", async function (assert) {- await visit("/chat/channel/11/another-category");- await triggerEvent(".chat-message-container[data-id='174']", "mouseenter");- await click(".reply-btn");- assert.ok(- exists(".chat-composer-message-details .d-icon-reply"),- "Reply icon is present"- );- assert.equal(- query(- ".chat-composer-message-details .chat-reply__username"- ).innerText.trim(),- "markvanlan"- );- });-- test("pressing the edit button fills the composer and indicates edit", async function (assert) {- await visit("/chat/channel/11/another-category");- await triggerEvent(".chat-message-container[data-id='174']", "mouseenter");-- const dropdown = selectKit(".more-buttons");- await dropdown.expand();- await dropdown.selectRowByValue("edit");-- assert.ok(- exists(".chat-composer-message-details .d-icon-pencil-alt"),- "Edit icon is present"- );- assert.equal(- query(- ".chat-composer-message-details .chat-reply__username"- ).innerText.trim(),- "markvanlan"- );-- assert.equal(- query(".chat-composer-input").value.trim(),- messageContents[0]- );- });-- test("Reply-to is stored in draft", async function (assert) {- await visit("/latest");- await click(".header-dropdown-toggle.open-chat");- await click(".chat-channel-row");- await settled();-- await click(".chat-drawer-header__return-to-channels-btn");- await click('.chat-channel-row[data-chat-channel-id="9"]');- await triggerEvent(".chat-message-container[data-id='174']", "mouseenter");- await click(".chat-message-actions-container[data-id='174'] .reply-btn");- // Reply-to line is present- assert.ok(exists(".chat-composer-message-details .chat-reply"));- await click(".chat-drawer-header__return-to-channels-btn");- await click('.chat-channel-row[data-chat-channel-id="11"]');- // Reply-to line is gone since switching channels- assert.notOk(exists(".chat-composer-message-details .chat-reply"));- // Now click on reply btn and cancel it on channel 7-- await triggerEvent(".chat-message-container[data-id='174']", "mouseenter");- await click(".chat-message-actions-container[data-id='174'] .reply-btn");- await click(".cancel-message-action");-- // Go back to channel 9 and check that reply-to is present- await click(".chat-drawer-header__return-to-channels-btn");- await click('.chat-channel-row[data-chat-channel-id="9"]');- // Now reply-to should be back and loaded from draft- assert.ok(exists(".chat-composer-message-details .chat-reply"));-- // Go back one for time to channel 7 and make sure reply-to is gone- await click(".chat-drawer-header__return-to-channels-btn");- await click('.chat-channel-row[data-chat-channel-id="11"]');- assert.notOk(exists(".chat-composer-message-details .chat-reply"));- });-- test("Sending a message", async function (assert) {- await visit("/chat/channel/11/another-category");- const messageContent = "Here's a message";- const composerInput = query(".chat-composer-input");- assert.deepEqual(- presentUserIds("/chat-reply/11"),- [],- "is not present before typing"- );- await fillIn(composerInput, messageContent);- assert.deepEqual(- presentUserIds("/chat-reply/11"),- [User.current().id],- "is present after typing"- );- await focus(composerInput);-- await triggerKeyEvent(composerInput, "keydown", "Enter");-- assert.equal(document.activeElement, composerInput);-- assert.equal(composerInput.innerText.trim(), "", "composer input cleared");-- assert.deepEqual(- presentUserIds("/chat-reply/11"),- [],- "stops being present after sending message"- );-- let messages = queryAll(".chat-message");- let lastMessage = messages[messages.length - 1];-- // Message is staged, without an ID- assert.ok(lastMessage.classList.contains("chat-message-staged"));-- // Last message was from a different user; full meta data is shown- assert.ok(- lastMessage.querySelector(".chat-user-avatar"),- "Avatar is present"- );- assert.ok(- lastMessage.querySelector(".chat-message-info__username__name"),- "Username is present"- );- assert.equal(- lastMessage.querySelector(".chat-message-text").innerText.trim(),- this.siteSettings.enable_markdown_typographer- ? "Here’s a message"- : messageContent- );-- await publishToMessageBus("/chat/11", {- type: "sent",- stagedId: 1,- chat_message: {- id: 202,- user: {- id: 1,- },- cooked: messageContent + " some extra cooked stuff",- },- });-- assert.equal(- lastMessage.closest(".chat-message-container").dataset.id,- 202- );- assert.notOk(lastMessage.classList.contains("chat-message-staged"));-- assert.equal(- lastMessage.querySelector(".chat-message-text").innerText.trim(),- messageContent + " some extra cooked stuff",- "last message is updated with the cooked content of the message"- );-- const nextMessageContent = "What up what up!";- await fillIn(composerInput, nextMessageContent);- await focus(composerInput);- await triggerKeyEvent(composerInput, "keydown", "Enter");-- messages = queryAll(".chat-message");- lastMessage = messages[messages.length - 1];-- // We just sent a message so avatar/username will not be present for the last message- assert.notOk(- lastMessage.querySelector(".chat-user-avatar"),- "Avatar is not shown"- );- assert.notOk(- lastMessage.querySelector(".full-name"),- "Username is not shown"- );- assert.equal(- lastMessage.querySelector(".chat-message-text").innerText.trim(),- nextMessageContent- );- });-- test("cooked processing messages are handled properly", async function (assert) {- await visit("/chat/channel/11/another-category");-- const cooked = "<h1>hello there</h1>";- await publishToMessageBus(`/chat/11`, {- type: "processed",- chat_message: {- cooked,- id: 175,- },- });-- assert.ok(- query(- ".chat-message-container[data-id='175'] .chat-message-text"- ).innerHTML.includes(cooked)- );- });-- test("Code highlighting in a message", async function (assert) {- await visit("/chat/channel/11/another-category");- const messageContent = `Here's a message with code highlighting--\`\`\`ruby-Widget.triangulate(arg: "test")-\`\`\``;- const composerInput = query(".chat-composer-input");- await fillIn(composerInput, messageContent);- await focus(composerInput);- await triggerKeyEvent(composerInput, "keydown", "Enter");-- await publishToMessageBus("/chat/11", {- type: "sent",- stagedId: 1,- chat_message: {- id: 202,- cooked: `<pre><code class="lang-ruby">Widget.triangulate(arg: "test")- </code></pre>`,- user: {- id: 1,- },- },- });-- const messages = queryAll(".chat-message");- const lastMessage = messages[messages.length - 1];- assert.equal(- lastMessage.closest(".chat-message-container").dataset.id,- 202- );- assert.ok(- exists(- ".chat-message-container[data-id='202'] .chat-message-text code.lang-ruby.hljs"- ),- "chat message code block has been highlighted as ruby code"- );- });-- test("Drafts are saved and reloaded", async function (assert) {- await visit("/chat/channel/11/another-category");- await fillIn(".chat-composer-input", "Hi people");-- await visit("/chat/channel/75/@hawk");- assert.equal(query(".chat-composer-input").value.trim(), "");- await fillIn(".chat-composer-input", "What up what up");-- await visit("/chat/channel/11/another-category");- assert.equal(query(".chat-composer-input").value.trim(), "Hi people");- await fillIn(".chat-composer-input", "");-- await visit("/chat/channel/75/@hawk");- assert.equal(query(".chat-composer-input").value.trim(), "What up what up");-- // Send a message- const composerTextarea = query(".chat-composer-input");- await focus(composerTextarea);- await triggerKeyEvent(composerTextarea, "keydown", "Enter");-- assert.equal(query(".chat-composer-input").value.trim(), "");-- // Navigate away and back to make sure input didn't re-fill- await visit("/chat/channel/11/another-category");- await visit("/chat/channel/75/@hawk");- assert.equal(query(".chat-composer-input").value.trim(), "");- });-- test("Pressing escape cancels editing", async function (assert) {- await visit("/chat/channel/11/another-category");- await triggerEvent(".chat-message-container[data-id='174']", "mouseenter");-- const dropdown = selectKit(".more-buttons");- await dropdown.expand();- await dropdown.selectRowByValue("edit");-- assert.ok(exists(".chat-composer-message-details"));- await triggerKeyEvent(".chat-composer", "keydown", "Escape");-- // chat-composer-message-details will be gone as no message is being edited- assert.notOk(exists(".chat-composer .chat-composer-message-details"));- });-- test("Unread indicator increments for public channels when messages come in", async function (assert) {- await visit("/t/internationalization-localization/280");- assert.notOk(- exists(".header-dropdown-toggle.open-chat .chat-channel-unread-indicator")- );-- await publishToMessageBus("/chat/9/new-messages", {- message_id: 201,- user_id: 2,- });-- assert.ok(- exists(".header-dropdown-toggle.open-chat .chat-channel-unread-indicator")- );- });-- test("Unread count increments for direct message channels when messages come in", async function (assert) {- await visit("/t/internationalization-localization/280");- assert.notOk(- exists(- ".header-dropdown-toggle.open-chat .chat-channel-unread-indicator.urgent .number"- )- );-- await publishToMessageBus("/chat/75/new-messages", {- message_id: 201,- user_id: 2,- });- assert.ok(- exists(- ".header-dropdown-toggle.open-chat .chat-channel-unread-indicator.urgent .number"- )- );- assert.equal(- query(- ".header-dropdown-toggle.open-chat .chat-channel-unread-indicator.urgent .number"- ).innerText.trim(),- 1- );- });-- test("Unread DM count overrides the public unread indicator", async function (assert) {- await visit("/t/internationalization-localization/280");- await publishToMessageBus("/chat/9/new-messages", {- message_id: 201,- user_id: 2,- });- await publishToMessageBus("/chat/75/new-messages", {- message_id: 202,- user_id: 2,- });- assert.ok(- exists(- ".header-dropdown-toggle.open-chat .chat-channel-unread-indicator.urgent .number"- )- );- assert.notOk(- exists(- ".header-dropdown-toggle.open-chat .chat-channel-unread-indicator:not(.urgent)"- )- );- });-- test("Mentions in public channels show the unread urgent indicator", async function (assert) {- await visit("/t/internationalization-localization/280");- await publishToMessageBus("/chat/9/new-mentions", {- message_id: 201,- });- assert.ok(- exists(- ".header-dropdown-toggle.open-chat .chat-channel-unread-indicator.urgent .number"- )- );- assert.notOk(- exists(- ".header-dropdown-toggle.open-chat .chat-channel-unread-indicator:not(.urgent)"- )- );- });-- test("message selection and live pane buttons for regular user", async function (assert) {- updateCurrentUser({ admin: false, moderator: false });- await visit("/chat/channel/11/another-category");-- const firstMessage = query(".chat-message-container");- await triggerEvent(firstMessage, "mouseenter");- const dropdown = selectKit(- `.chat-message-actions-container[data-id="${firstMessage.dataset.id}"] .more-buttons`- );- await dropdown.expand();- await dropdown.selectRowByValue("selectMessage");-- assert.ok(firstMessage.classList.contains("selecting-messages"));- assert.ok(exists("#chat-quote-btn"));- });-- test("message selection is not present for regular user", async function (assert) {- updateCurrentUser({ admin: false, moderator: false });- await visit("/chat/channel/11/another-category");- assert.notOk(- exists(- ".chat-message-container .chat-message-actions-container .select-btn"- )- );- });-- test("creating a new direct message channel works", async function (assert) {- await visit("/chat/channel/11/another-category");- await click(".open-draft-channel-page-btn");- await fillIn(".filter-usernames", "hawk");- await click("li.user[data-username='hawk']");-- assert.notOk(- query(".join-channel-btn"),- "Join channel button is not present"- );- const enabledComposer = document.querySelector(".chat-composer-input");- assert.ok(!enabledComposer.disabled);- assert.equal(- enabledComposer.placeholder,- I18n.t("chat.placeholder_start_conversation", { usernames: "hawk" })- );- });-- test("creating a new direct message channel from popup chat works", async function (assert) {- await visit("/chat");- await click(".open-draft-channel-page-btn");- await fillIn(".filter-usernames", "hawk");- await click('.chat-user-avatar-container[data-user-card="hawk"]');- assert.ok(query(".selected-user").innerText, "hawk");- });-- test("Reacting works with no existing reactions", async function (assert) {- await visit("/chat/channel/11/another-category");- const message = query(".chat-message-container");- await triggerEvent(message, "mouseenter");- assert.notOk(message.querySelector(".chat-message-reaction-list"));- await click(".chat-message-actions .react-btn");- await click(`.chat-emoji-picker .emoji[alt="grinning"]`);-- assert.ok(message.querySelector(".chat-message-reaction-list"));- const reaction = message.querySelector(- ".chat-message-reaction-list .chat-message-reaction.reacted"- );- assert.ok(reaction);- assert.equal(reaction.querySelector(".count").innerText.trim(), 1);- });-- test("Reacting works with existing reactions", async function (assert) {- await visit("/chat/channel/11/another-category");- const messages = queryAll(".chat-message-container");-- // First 2 messages have no reactions; make sure the list isn't rendered- assert.notOk(messages[0].querySelector(".chat-message-reaction-list"));- assert.notOk(messages[1].querySelector(".chat-message-reaction-list"));-- const lastMessage = messages[2];- assert.ok(lastMessage.querySelector(".chat-message-reaction-list"));- assert.equal(- lastMessage.querySelectorAll(".chat-message-reaction.reacted").length,- 2- );- assert.equal(- lastMessage.querySelectorAll(".chat-message-reaction:not(.reacted)")- .length,- 1- );-- // React with a heart and make sure the count increments and class is added- const heartReaction = lastMessage.querySelector(- `.chat-message-reaction[data-emoji-name="heart"]`- );- assert.equal(heartReaction.innerText.trim(), "1");- await click(heartReaction);- assert.equal(heartReaction.innerText.trim(), "2");- assert.ok(heartReaction.classList.contains("reacted"));-- await publishToMessageBus("/chat/11", {- action: "add",- user: { id: 1, username: "eviltrout" },- emoji: "heart",- type: "reaction",- chat_message_id: 176,- });-- // Click again make sure count goes down- await click(heartReaction);- assert.equal(heartReaction.innerText.trim(), "1");- assert.notOk(heartReaction.classList.contains("reacted"));-- // Message from another user coming in!- await publishToMessageBus("/chat/11", {- action: "add",- user: { id: 77, username: "rando" },- emoji: "sneezing_face",- type: "reaction",- chat_message_id: 176,- });- const sneezingFaceReaction = lastMessage.querySelector(- `.chat-message-reaction[data-emoji-name="sneezing_face"]`- );- assert.ok(sneezingFaceReaction);- assert.equal(sneezingFaceReaction.innerText.trim(), "1");- assert.notOk(sneezingFaceReaction.classList.contains("reacted"));- await click(sneezingFaceReaction);- assert.equal(sneezingFaceReaction.innerText.trim(), "2");- assert.ok(sneezingFaceReaction.classList.contains("reacted"));- });-- test("Reacting and unreacting works on newly created chat messages", async function (assert) {- await visit("/chat/channel/11/another-category");- const composerInput = query(".chat-composer-input");- await fillIn(composerInput, "hellloooo");- await focus(composerInput);- await triggerKeyEvent(composerInput, "keydown", "Enter");-- const messages = queryAll(".chat-message-container");- const lastMessage = messages[messages.length - 1];- await publishToMessageBus("/chat/11", {- type: "sent",- stagedId: 1,- chat_message: {- id: 202,- user: {- id: 1,- },- cooked: "<p>hellloooo</p>",- },- });-- assert.deepEqual(lastMessage.dataset.id, "202");- await triggerEvent(lastMessage, "mouseenter");- await click(- `.chat-message-actions-container[data-id="${lastMessage.dataset.id}"] .react-btn`- );- await click(`.emoji[alt="grinning"]`);-- const reaction = lastMessage.querySelector(- `.chat-message-reaction.reacted[data-emoji-name="grinning"]`- );-- await publishToMessageBus("/chat/11", {- action: "add",- user: { id: 1, username: "eviltrout" },- emoji: "grinning",- type: "reaction",- chat_message_id: 202,- });- await click(reaction);-- assert.notOk(- lastMessage.querySelector(- `.chat-message-reaction.reacted[data-emoji-name="grinning"]`- )- );- });-- test("mention warning is rendered", async function (assert) {- await visit("/chat/channel/11/another-category");- await publishToMessageBus("/chat/11", {- type: "mention_warning",- cannot_see: [{ id: 75, username: "hawk" }],- without_membership: [- { id: 76, username: "eviltrout" },- { id: 77, username: "sam" },- ],- chat_message_id: 176,- });-- assert.ok(- exists(- ".chat-message-container[data-id='176'] .chat-message-mention-warning"- )- );-- assert.ok(- query(- ".chat-message-container[data-id='176'] .chat-message-mention-warning .cannot-see"- ).innerText.includes("hawk")- );-- const withoutMembershipText = query(- ".chat-message-container[data-id='176'] .chat-message-mention-warning .without-membership"- ).innerText;- assert.ok(withoutMembershipText.includes("eviltrout"));- assert.ok(withoutMembershipText.includes("1 other"));-- await click(- ".chat-message-container[data-id='176'] .chat-message-mention-warning .invite-link"- );- assert.notOk(- exists(- ".chat-message-container[data-id='176'] .chat-message-mention-warning"- )- );- });-- test("It displays a separator between days", async function (assert) {- await visit("/chat/channel/11/another-category");- assert.equal(- query(".first-daily-message").innerText.trim(),- "July 22, 2021"- );- });-- test("pressing keys focuses composer in full page chat", async function (assert) {- await visit("/chat/channel/11/another-category");-- document.activeElement.blur();- await triggerKeyEvent(document.body, "keydown", 65); // 65 is `a` keycode- let composer = query(".chat-composer-input");- assert.equal(composer.value, "a");- assert.equal(document.activeElement, composer);-- document.activeElement.blur();- await triggerKeyEvent(document.body, "keydown", 65);- assert.equal(composer.value, "aa");- assert.equal(document.activeElement, composer);-- document.activeElement.blur();- await triggerKeyEvent(document.body, "keydown", "?", { shiftKey: true });- assert.notEqual(- document.activeElement,- composer,- "? is a special case and should not focus"- );-- document.activeElement.blur();- await triggerKeyEvent(document.body, "keydown", "Enter");- assert.notEqual(- document.activeElement,- composer,- "enter is a special case and should not focus"- );- });-- test("changing channel resets message selection", async function (assert) {- await visit("/chat/channel/11/another-category");- await triggerEvent(".chat-message-container", "mouseenter");- const dropdown = selectKit(".chat-message-actions .more-buttons");- await dropdown.expand();- await dropdown.selectRowByValue("selectMessage");- await click("#chat-copy-btn");- await click('.chat-channel-row[data-chat-channel-id="9"]');-- assert.notOk(exists("#chat-copy-btn"));- });-});--acceptance(- "Discourse Chat - Acceptance Test with unread public channel messages",- function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- });- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- directMessageChannelPretender(server, helper);- chatChannelPretender(server, helper, [- { id: 11, unread_count: 2, muted: false },- ]);- });- needs.hooks.beforeEach(function () {- Object.defineProperty(this, "chatService", {- get: () => this.container.lookup("service:chat"),- });- });-- test("Expand button takes you to full page chat on the correct channel", async function (assert) {- await visit("/t/internationalization-localization/280");- await click(".header-dropdown-toggle.open-chat");- await click(".chat-drawer-header__full-screen-btn");-- assert.equal(currentURL(), `/chat/channel/11/another-category`);- });-- test("Unread header indicator is present", async function (assert) {- await visit("/t/internationalization-localization/280");-- assert.ok(- exists(- ".header-dropdown-toggle.open-chat .chat-channel-unread-indicator"- ),- "Unread indicator present in header"- );- });- }-);--acceptance(- "Discourse Chat - Acceptance Test show/hide close fullscreen chat button",- function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- });- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- chatChannelPretender(server, helper, [- { id: 9, unread_count: 2, muted: false },- ]);- });- needs.hooks.beforeEach(function () {- Object.defineProperty(this, "chatService", {- get: () => this.container.lookup("service:chat"),- });- });-- test("Close fullscreen chat button present", async function (assert) {- await visit("/chat/channel/11/another-category");- assert.ok(exists(".open-drawer-btn"));- });- }-);--acceptance(- "Discourse Chat - Expand and collapse drawer (chat-drawer)",- function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- });- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- chatChannelPretender(server, helper, [- { id: 9, unread_count: 2, muted: false },- ]);-- server.get("/chat/api/chat_channels/:id/memberships.json", () => {- return helper.response([]);- });- });- needs.hooks.beforeEach(function () {- Object.defineProperty(this, "chatService", {- get: () => this.container.lookup("service:chat"),- });- });-- test("drawer can be collapsed and expanded", async function (assert) {- await visit("/t/internationalization-localization/280");- await click(".header-dropdown-toggle.open-chat");- assert.ok(- visible(".chat-drawer-header__top-line--expanded"),- "drawer is expanded"- );- await click(".chat-drawer-header__expand-btn");- assert.ok(- visible(".chat-drawer-header__top-line--collapsed"),- "drawer is collapsed"- );- await click(".chat-drawer-header__expand-btn");- assert.ok(- visible(".chat-drawer-header__top-line--expanded"),- "drawer is expanded"- );- });-- test("drawer title links to channel info when expanded", async function (assert) {- await visit("/t/internationalization-localization/280");- await click(".header-dropdown-toggle.open-chat");- assert.ok(- visible(".chat-drawer-header__top-line--expanded"),- "drawer is expanded"- );- await click('.chat-channel-row[data-chat-channel-id="9"]');- await click(".chat-drawer-header__title");- assert.equal(currentURL(), `/chat/channel/9/site/info/members`);- });-- test("drawer title expands the drawer when collapsed", async function (assert) {- await visit("/t/internationalization-localization/280");- await click(".header-dropdown-toggle.open-chat");- await click(".chat-channel-row");-- assert.ok(- visible(".chat-drawer-header__top-line--expanded"),- "drawer is expanded"- );-- await click(".chat-drawer-header__expand-btn");-- assert.ok(- visible(".chat-drawer-header__top-line--collapsed"),- "drawer is collapsed"- );-- await click(".chat-drawer-header__title");-- assert.ok(- visible(".chat-drawer-header__top-line--expanded"),- "drawer is expanded"- );- });- }-);--acceptance(- "Discourse Chat - Acceptance Test with unread DMs and public channel messages",- function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- });- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- directMessageChannelPretender(server, helper);- // chat channel with ID 75 is direct message channel.- chatChannelPretender(server, helper, [- { id: 9, unread_count: 2, muted: false },- { id: 75, unread_count: 2, muted: false },- ]);- });- needs.hooks.beforeEach(function () {- Object.defineProperty(this, "chatService", {- get: () => this.container.lookup("service:chat"),- });- });-- test("Unread indicator doesn't show when user is in do not disturb", async function (assert) {- let now = new Date();- let later = new Date();- later.setTime(now.getTime() + 600000);- updateCurrentUser({ do_not_disturb_until: later.toUTCString() });- await visit("/t/internationalization-localization/280");- assert.notOk(- exists(- ".header-dropdown-toggle.open-chat .chat-unread-urgent-indicator"- )- );- });-- test("drawer open to DM channel with unread messages with sidebar off", async function (assert) {- await visit("/t/internationalization-localization/280");- await click(".header-dropdown-toggle.open-chat");- await click('.chat-channel-row[data-chat-channel-id="75"]');- const chatContainer = query(".chat-drawer");- assert.strictEqual(chatContainer.dataset.chatChannelId, "75");- });-- test("Chat full page open to DM channel with unread messages with sidebar on", async function (assert) {- this.chatService.set("sidebarActive", true);- this.owner.lookup("service:chat-state-manager").prefersFullPage();- await visit("/t/internationalization-localization/280");- await click(".header-dropdown-toggle.open-chat");-- assert.equal(currentURL(), `/chat/channel/75/hawk`);- });- }-);--acceptance(- "Discourse Chat - chat channel settings and creation",- function (needs) {- needs.user({- admin: true,- moderator: true,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });-- needs.settings({- chat_enabled: true,- });-- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- chatChannelPretender(server, helper);-- const channel = {- chatable: {},- chatable_id: 88,- chatable_type: "Category",- chatable_url: null,- id: 88,- title: "Something",- last_message_sent_at: "2021-11-08T21:26:05.710Z",- current_user_membership: {- last_read_message_id: null,- unread_count: 0,- unread_mentions: 0,- },- };-- server.get("/chat/api/chat_channels.json", () => {- return helper.response([fabricators.chatChannel()]);- });-- server.get("/chat/chat_channels/:id.json", () => {- return helper.response(channel);- });-- server.put("/chat/chat_channels", () => {- return helper.response({- chat_channel: channel,- });- });- });-- test("Create channel modal", async function (assert) {- await visit("/chat/browse");- await click(".new-channel-btn");-- assert.strictEqual(currentURL(), "/chat/browse/open");-- let categories = selectKit(".create-channel-modal .category-chooser");- await categories.expand();- await categories.selectRowByValue("6"); // Category 6 is "support"- assert.strictEqual(- query(".create-channel-modal .create-channel-name-input").value.trim(),- "support"- );- assert.notOk(query(".create-channel-modal .btn.create").disabled);-- await click(".create-channel-modal .btn.create");- assert.strictEqual(currentURL(), "/chat/channel/88/something");- });- }-);--acceptance("Discourse Chat - chat preferences", function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- });- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- directMessageChannelPretender(server, helper);- chatChannelPretender(server, helper);- });- needs.hooks.beforeEach(function () {- Object.defineProperty(this, "chatService", {- get: () => this.container.lookup("service:chat"),- });- });-- test("Chat preferences route takes user to homepage when can_chat is false", async function (assert) {- updateCurrentUser({ can_chat: false });- await visit("/u/eviltrout/preferences/chat");- assert.equal(currentURL(), "/latest");- });-- test("There are all 5 settings shown", async function (assert) {- this.chatService.set("sidebarActive", true);- await visit("/u/eviltrout/preferences/chat");- assert.equal(currentURL(), "/u/eviltrout/preferences/chat");- assert.equal(queryAll(".chat-setting").length, 5);- });-- test("The user can save the settings", async function (assert) {- updateCurrentUser({ has_chat_enabled: false });- const spy = sinon.spy(ajaxModule, "ajax");- await visit("/u/eviltrout/preferences/chat");- await click("#user_chat_enabled");- await click("#user_chat_only_push_notifications");- await click("#user_chat_ignore_channel_wide_mention");- await selectKit("#user_chat_sounds").expand();- await selectKit("#user_chat_sounds").selectRowByValue("bell");- await selectKit("#user_chat_email_frequency").expand();- await selectKit("#user_chat_email_frequency").selectRowByValue("never");-- await click(".save-changes");-- assert.ok(- spy.calledWithMatch("/u/eviltrout.json", {- data: {- chat_enabled: true,- chat_sound: "bell",- only_chat_push_notifications: true,- ignore_channel_wide_mention: true,- chat_email_frequency: "never",- },- type: "PUT",- }),- "is able to save the chat preferences for the user"- );- });-});--acceptance("Discourse Chat - plugin API", function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- });- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- directMessageChannelPretender(server, helper);- chatChannelPretender(server, helper);- });-- test("defines a decorateChatMessage plugin API", async function (assert) {- withPluginApi("1.1.0", (api) => {- api.decorateChatMessage((message) => {- message.innerText = "test";- });- });-- await visit("/chat/channel/75/@hawk");-- assert.equal(- document.querySelector('.chat-message-container[data-id="177"]')- .innerText,- "test"- );- });-});--acceptance("Discourse Chat - image uploads", function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- chat_allow_uploads: true,- });- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- directMessageChannelPretender(server, helper);- chatChannelPretender(server, helper);-- server.post(- "/uploads.json",- () => {- return helper.response({- extension: "jpeg",- filesize: 126177,- height: 800,- human_filesize: "123 KB",- id: 202,- original_filename: "avatar.PNG.jpg",- retain_hours: null,- short_path: "/images/avatar.png",- short_url: "upload://yoj8pf9DdIeHRRULyw7i57GAYdz.jpeg",- thumbnail_height: 320,- thumbnail_width: 690,- url: "/images/avatar.png",- width: 1920,- });- },- 500 // this delay is important to slow down the uploads a bit so we can click elements in the UI like the cancel button- );- });-- test("uploading files in chat works", async function (assert) {- await visit("/t/internationalization-localization/280");- await click(".header-dropdown-toggle.open-chat");- await click(".chat-channel-row");-- assert.ok(exists(".chat-drawer.is-expanded"), "drawer is open");-- const appEvents = loggedInUser().appEvents;- const done = assert.async();-- appEvents.on(- "upload-mixin:chat-composer-uploader:all-uploads-complete",- async () => {- await settled();- assert.ok(- exists(".preview .preview-img"),- "the chat upload preview should show"- );- assert.notOk(- exists(".bottom-data .uploading"),- "the chat upload preview should no longer say it is uploading"- );- assert.strictEqual(- queryAll(".chat-composer-input").val(),- "",- "the chat composer does not get the upload markdown when the upload is complete"- );- done();- }- );-- appEvents.on(- "upload-mixin:chat-composer-uploader:upload-started",- async () => {- await settled();- assert.ok(- exists(".chat-upload"),- "the chat upload preview should show"- );- assert.ok(- exists(".bottom-data .uploading"),- "the chat upload preview should say it is uploading"- );- assert.strictEqual(- queryAll(".chat-composer-input").val(),- "",- "the chat composer does not get an uploading... placeholder"- );- }- );-- const image = createFile("avatar.png");- appEvents.trigger("upload-mixin:chat-composer-uploader:add-files", image);- });-- test("uploading files in composer does not insert placeholder text into chat composer", async function (assert) {- await visit("/t/internationalization-localization/280");-- await click("#topic-footer-buttons .btn.create");- assert.ok(exists(".d-editor-input"), "the composer input is visible");-- this.container.lookup("service:chat").set("sidebarActive", false);- await click(".header-dropdown-toggle.open-chat");- await click(".chat-channel-row");- assert.ok(visible(".chat-drawer-container"), "drawer is open");-- const appEvents = loggedInUser().appEvents;- const done = assert.async();- await fillIn(".d-editor-input", "The image:\n");-- appEvents.on("composer:all-uploads-complete", async () => {- await settled();- assert.strictEqual(- query(".d-editor-input").value,- "The image:\n\n",- "the topic composer gets the completed image markdown"- );- assert.strictEqual(- query(".chat-composer-input").value,- "",- "the chat composer does not get the completed image markdown"- );- done();- });-- appEvents.on("composer:upload-started", () => {- assert.strictEqual(- query(".d-editor-input").value,- "The image:\n[Uploading: avatar.png...]()\n",- "the topic composer gets the placeholder image markdown"- );- assert.strictEqual(- query(".chat-composer-input").value,- "",- "the chat composer does not get the placeholder image markdown"- );- });-- const image = createFile("avatar.png");- appEvents.trigger("composer:add-files", image);- });-});--acceptance(- "Discourse Chat - image uploads - uploads not allowed",- function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- chat_allow_uploads: false,- discourse_local_dates_enabled: false,- });- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- directMessageChannelPretender(server, helper);- chatChannelPretender(server, helper);- });-- test("uploads are not allowed in public channels", async function (assert) {- await visit("/chat/channel/4/public-category");- await click(".chat-composer-dropdown__trigger-btn");-- assert.notOk(- exists(".chat-composer-dropdown__item.chat-upload-btn"),- "composer dropdown should not be visible because uploads are not enabled and no other buttons are rendered"- );- });-- test("uploads are not allowed in direct message channels", async function (assert) {- await visit("/chat/channel/75/@hawk");- await click(".chat-composer-dropdown__trigger-btn");-- assert.notOk(- exists(".chat-composer-dropdown__item.chat-upload-btn"),- "composer dropdown should not be visible because uploads are not enabled and no other buttons are rendered"- );- });- }-);--acceptance("Discourse Chat - Insert Date", function (needs) {- needs.user({- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- discourse_local_dates_enabled: true,- });- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- chatChannelPretender(server, helper);- });-- test("can use local date modal", async function (assert) {- await visit("/chat/channel/4/public-category");- await click(".chat-composer-dropdown__trigger-btn");- await click(".chat-composer-dropdown__action-btn.local-dates");-- assert.ok(exists(".discourse-local-dates-create-modal"));-- await click(".modal-footer .btn-primary");-- assert.ok(- query(".chat-composer-input").value.startsWith("[date"),- "inserts date in composer input"- );- });-});--acceptance(- "Discourse Chat - Channel Status - Read only channel",- function (needs) {- needs.user({- admin: true,- moderator: true,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- });- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- chatChannelPretender(server, helper);- server.get("/chat/chat_channels.json", () => {- const cloned = cloneJSON(chatChannels);- cloned.public_channels.find((chan) => chan.id === 7).status =- CHANNEL_STATUSES.readOnly;- return helper.response(cloned);- });- });-- test("read only channel composer is disabled", async function (assert) {- await visit("/chat/channel/5/public-category");- assert.strictEqual(query(".chat-composer-input").disabled, true);- });-- test("read only channel header status shows correct information", async function (assert) {- await visit("/chat/channel/5/public-category");- assert.strictEqual(- query(".chat-channel-status").innerText.trim(),- I18n.t("chat.channel_status.read_only_header")- );- });-- test("read only channels do not show the reply, react, delete, edit, restore, or rebuild options for messages", async function (assert) {- await visit("/chat/channel/5/public-category");- await triggerEvent(".chat-message-container", "mouseenter");- const dropdown = selectKit(".chat-message-actions .more-buttons");- await dropdown.expand();- assert.notOk(exists(".select-kit-row[data-value='edit']"));- assert.notOk(exists(".select-kit-row[data-value='deleteMessage']"));- assert.notOk(exists(".select-kit-row[data-value='rebakeMessage']"));- assert.notOk(exists(".reply-btn"));- assert.notOk(exists(".react-btn"));- });- }-);--acceptance(- "Discourse Chat - Channel Status - Closed channel (regular user)",- function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- });- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- chatChannelPretender(server, helper);- server.get("/chat/chat_channels.json", () => {- const cloned = cloneJSON(chatChannels);- cloned.public_channels.find((chan) => chan.id === 4).status =- CHANNEL_STATUSES.closed;- return helper.response(cloned);- });- });-- test("closed channel composer is disabled", async function (assert) {- await visit("/chat/channel/4/public-category");- assert.strictEqual(query(".chat-composer-input").disabled, true);- });-- test("closed channel header status shows correct information", async function (assert) {- await visit("/chat/channel/4/public-category");- assert.strictEqual(- query(".chat-channel-status").innerText.trim(),- I18n.t("chat.channel_status.closed_header")- );- });-- test("closed channels do not show the reply, react, delete, edit, restore, or rebuild options for messages", async function (assert) {- await visit("/chat/channel/4/public-category");-- await triggerEvent(".chat-message-container", "mouseenter");- const dropdown = selectKit(".chat-message-actions .more-buttons");- await dropdown.expand();-- assert.notOk(exists(".select-kit-row[data-value='edit']"));- assert.notOk(exists(".select-kit-row[data-value='deleteMessage']"));- assert.notOk(exists(".select-kit-row[data-value='rebakeMessage']"));- assert.notOk(exists(".reply-btn"));- assert.notOk(exists(".react-btn"));- });- }-);--acceptance(- "Discourse Chat - Channel Status - Closed channel (staff user)",- function (needs) {- needs.user({- admin: true,- moderator: true,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- });- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- chatChannelPretender(server, helper);- server.get("/chat/chat_channels.json", () => {- const cloned = cloneJSON(chatChannels);- cloned.public_channels.find((chan) => chan.id === 7).status =- CHANNEL_STATUSES.closed;- return helper.response(cloned);- });- });-- test("closed channel composer is enabled", async function (assert) {- await visit("/chat/channel/4/public-category");- assert.strictEqual(query(".chat-composer-input").disabled, false);- });-- test("closed channels show the reply, react, delete, edit, restore, or rebuild options for messages", async function (assert) {- await visit("/chat/channel/4/public-category");- await triggerEvent(".chat-message-container", "mouseenter");- const dropdown = selectKit(".chat-message-actions .more-buttons");- await dropdown.expand();- assert.ok(- exists(".select-kit-row[data-value='edit']"),- "the edit message button is shown"- );- assert.ok(- exists(".select-kit-row[data-value='deleteMessage']"),- "the delete message button is shown"- );- assert.ok(- exists(".select-kit-row[data-value='rebakeMessage']"),- "the rebake message button is shown"- );- assert.ok(exists(".reply-btn", "the reply button is shown"));- assert.ok(exists(".react-btn"), "the react button is shown");- });- }-);--acceptance("Discourse Chat - Channel Replying Indicator", function (needs) {- needs.user({- admin: true,- moderator: true,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- });- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- chatChannelPretender(server, helper);- server.get("/chat/chat_channels.json", () => {- const cloned = cloneJSON(chatChannels);- cloned.public_channels.find((chan) => chan.id === 7).status =- CHANNEL_STATUSES.closed;- return helper.response(cloned);- });- });-- test("indicator content when replying/not replying", async function (assert) {- const user = { id: 8, username: "bob" };- await visit("/chat/channel/4/public-category");- await joinChannel("/chat-reply/4", user);-- assert.equal(- query(".chat-replying-indicator__text").innerText,- I18n.t("chat.replying_indicator.single_user", {- username: user.username,- })- );-- await leaveChannel("/chat-reply/4", user);-- assert.notOk(exists(".chat-replying-indicator__text"));- });-});--acceptance("Discourse Chat - Direct Message Creator", function (needs) {- needs.user({- admin: true,- moderator: true,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.settings({- chat_enabled: true,- });- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- chatChannelPretender(server, helper);-- server.get("/u/search/users", () => {- return helper.response([]);- });- });-- test("Create a direct message", async function (assert) {- await visit("/latest");- await click(".header-dropdown-toggle.open-chat");-- assert.ok(- !exists(".open-draft-channel-page-btn.btn-floating"),- "mobile floating button should not exist on desktop"- );- await click(".btn.open-draft-channel-page-btn");- assert.ok(exists(".chat-draft"), "view changes to draft channel screen");- });-});--function createFile(name, type = "image/png") {- // the blob content doesn't matter at all, just want it to be random-ish- const file = new Blob([(Math.random() + 1).toString(36).substring(2)], {- type,- });- file.name = name;- return file;-}diff --git a/plugins/chat/test/javascripts/acceptance/chat-transcript-test.js b/plugins/chat/test/javascripts/acceptance/chat-transcript-test.jsdeleted file mode 100644index 98ff2a6b8b9..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-transcript-test.js+++ /dev/null@@ -1,597 +0,0 @@-import PrettyText, { buildOptions } from "pretty-text/pretty-text";-import { emojiUnescape } from "discourse/lib/text";-import I18n from "I18n";-import topicFixtures from "discourse/tests/fixtures/topic";-import { cloneJSON, deepMerge } from "discourse-common/lib/object";-import QUnit, { test } from "qunit";--import { click, fillIn, visit } from "@ember/test-helpers";-import { acceptance, query } from "discourse/tests/helpers/qunit-helpers";--const rawOpts = {- siteSettings: {- enable_emoji: true,- enable_emoji_shortcuts: true,- enable_mentions: true,- emoji_set: "twitter",- external_emoji_url: "",- highlighted_languages: "json|ruby|javascript",- default_code_lang: "auto",- enable_markdown_linkify: true,- markdown_linkify_tlds: "com",- chat_enabled: true,- },- getURL: (url) => url,-};--function cookMarkdown(input, opts) {- const merged = deepMerge({}, rawOpts, opts);- return new PrettyText(buildOptions(merged)).cook(input);-}--QUnit.assert.cookedChatTranscript = function (input, opts, expected, message) {- const actual = cookMarkdown(input, opts);- this.pushResult({- result: actual === expected,- actual,- expected,- message,- });-};--function generateTranscriptHTML(messageContent, opts) {- const channelDataAttr = opts.channel- ? ` data-channel-name=\"${opts.channel}\"`- : "";- const channelIdDataAttr = opts.channelId- ? ` data-channel-id=\"${opts.channelId}\"`- : "";- const reactDataAttr = opts.reactions- ? ` data-reactions=\"${opts.reactionsAttr}\"`- : "";-- let tabIndexHTML = opts.linkTabIndex ? ' tabindex="-1"' : "";-- let transcriptClasses = ["chat-transcript"];- if (opts.chained) {- transcriptClasses.push("chat-transcript-chained");- }-- const transcript = [];- transcript.push(- `<div class=\"${transcriptClasses.join(" ")}\" data-message-id=\"${- opts.messageId- }\" data-username=\"${opts.username}\" data-datetime=\"${- opts.datetime- }\"${reactDataAttr}${channelDataAttr}${channelIdDataAttr}>`- );-- if (opts.channel && opts.multiQuote) {- let originallySent = I18n.t("chat.quote.original_channel", {- channel: opts.channel,- channelLink: `/chat/channel/${opts.channelId}/-`,- });- if (opts.linkTabIndex) {- originallySent = originallySent.replace(">", tabIndexHTML + ">");- }- transcript.push(`<div class=\"chat-transcript-meta\">-${originallySent}</div>`);- }-- const dateTimeText = opts.showDateTimeText- ? moment- .tz(opts.datetime, opts.timezone)- .format(I18n.t("dates.long_no_year"))- : "";-- const innerDatetimeEl =- opts.noLink || !opts.channelId- ? `<span title=\"${opts.datetime}\">${dateTimeText}</span>`- : `<a href=\"/chat/channel/${opts.channelId}/-?messageId=${opts.messageId}\" title=\"${opts.datetime}\"${tabIndexHTML}>${dateTimeText}</a>`;- transcript.push(`<div class=\"chat-transcript-user\">-<div class=\"chat-transcript-user-avatar\"></div>-<div class=\"chat-transcript-username\">-${opts.username}</div>-<div class=\"chat-transcript-datetime\">-${innerDatetimeEl}</div>`);-- if (opts.channel && !opts.multiQuote) {- transcript.push(- `<a class=\"chat-transcript-channel\" href="/chat/channel/${opts.channelId}/-"${tabIndexHTML}>-#${opts.channel}</a></div>`- );- } else {- transcript.push("</div>");- }-- let messageHtml = `<div class=\"chat-transcript-messages\">\n${messageContent}`;-- if (opts.reactions) {- let reactionsHtml = [`<div class=\"chat-transcript-reactions\">\n`];- opts.reactions.forEach((react) => {- reactionsHtml.push(- `<div class=\"chat-transcript-reaction\">\n${emojiUnescape(- `:${react.emoji}:`,- { lazy: true }- ).replace(/'/g, '"')} ${react.usernames.length}</div>\n`- );- });- reactionsHtml.push(`</div>\n`);- messageHtml += reactionsHtml.join("");- }- transcript.push(`${messageHtml}</div>`);- transcript.push("</div>");- return transcript.join("\n");-}--// these are both set by the plugin with Site.markdown_additional_options which we can't really-// modify the response for here, source of truth are consts in ChatMessage::MARKDOWN_FEATURES-// and ChatMessage::MARKDOWN_IT_RULES-function buildAdditionalOptions() {- return {- chat: {- limited_pretty_text_features: [- "anchor",- "bbcode-block",- "bbcode-inline",- "code",- "category-hashtag",- "censored",- "discourse-local-dates",- "emoji",- "emojiShortcuts",- "inlineEmoji",- "html-img",- "mentions",- "onebox",- "text-post-process",- "upload-protocol",- "watched-words",- "table",- "spoiler-alert",- ],- limited_pretty_text_markdown_rules: [- "autolink",- "list",- "backticks",- "newline",- "code",- "fence",- "table",- "linkify",- "link",- "strikethrough",- "blockquote",- "emphasis",- ],- hashtag_configurations: {- "chat-composer": ["channel", "category", "tag"],- },- },- };-}--acceptance("Discourse Chat | chat-transcript", function (needs) {- let additionalOptions = buildAdditionalOptions();-- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: false,- has_chat_enabled: false,- timezone: "Australia/Brisbane",- });-- needs.settings({- emoji_set: "twitter",- });-- test("works with a minimal quote bbcode block", function (assert) {- assert.cookedChatTranscript(- `[chat quote="martin;2321;2022-01-25T05:40:39Z"]\nThis is a chat message.\n[/chat]`,- { additionalOptions },- generateTranscriptHTML("<p>This is a chat message.</p>", {- messageId: "2321",- username: "martin",- datetime: "2022-01-25T05:40:39Z",- timezone: "Australia/Brisbane",- }),- "renders the chat message with the required CSS classes and attributes"- );- });-- test("renders the channel name if provided with multiQuote", function (assert) {- assert.cookedChatTranscript(- `[chat quote="martin;2321;2022-01-25T05:40:39Z" channel="Cool Cats Club" channelId="1234" multiQuote="true"]\nThis is a chat message.\n[/chat]`,- { additionalOptions },- generateTranscriptHTML("<p>This is a chat message.</p>", {- messageId: "2321",- username: "martin",- datetime: "2022-01-25T05:40:39Z",- channel: "Cool Cats Club",- channelId: "1234",- multiQuote: true,- timezone: "Australia/Brisbane",- }),- "renders the chat transcript with the channel name included above the user and datetime"- );- });-- test("renders the channel name if provided without multiQuote", function (assert) {- assert.cookedChatTranscript(- `[chat quote="martin;2321;2022-01-25T05:40:39Z" channel="Cool Cats Club" channelId="1234"]\nThis is a chat message.\n[/chat]`,- { additionalOptions },- generateTranscriptHTML("<p>This is a chat message.</p>", {- messageId: "2321",- username: "martin",- datetime: "2022-01-25T05:40:39Z",- channel: "Cool Cats Club",- channelId: "1234",- timezone: "Australia/Brisbane",- }),- "renders the chat transcript with the channel name included next to the datetime"- );- });-- test("renders with the chained attribute for more compact quotes", function (assert) {- assert.cookedChatTranscript(- `[chat quote="martin;2321;2022-01-25T05:40:39Z" channel="Cool Cats Club" channelId="1234" multiQuote="true" chained="true"]\nThis is a chat message.\n[/chat]`,- { additionalOptions },- generateTranscriptHTML("<p>This is a chat message.</p>", {- messageId: "2321",- username: "martin",- datetime: "2022-01-25T05:40:39Z",- channel: "Cool Cats Club",- channelId: "1234",- multiQuote: true,- chained: true,- timezone: "Australia/Brisbane",- }),- "renders with the chained attribute"- );- });-- test("renders with the noLink attribute to remove the links to the individual messages from the datetimes", function (assert) {- assert.cookedChatTranscript(- `[chat quote="martin;2321;2022-01-25T05:40:39Z" channel="Cool Cats Club" channelId="1234" multiQuote="true" noLink="true"]\nThis is a chat message.\n[/chat]`,- { additionalOptions },- generateTranscriptHTML("<p>This is a chat message.</p>", {- messageId: "2321",- username: "martin",- datetime: "2022-01-25T05:40:39Z",- channel: "Cool Cats Club",- channelId: "1234",- multiQuote: true,- noLink: true,- timezone: "Australia/Brisbane",- }),- "renders with the noLink attribute"- );- });-- test("renders with the reactions attribute", function (assert) {- const reactionsAttr = "+1:martin;heart:martin,eviltrout";- assert.cookedChatTranscript(- `[chat quote="martin;2321;2022-01-25T05:40:39Z" channel="Cool Cats Club" channelId="1234" reactions="${reactionsAttr}"]\nThis is a chat message.\n[/chat]`,- { additionalOptions },- generateTranscriptHTML("<p>This is a chat message.</p>", {- messageId: "2321",- username: "martin",- datetime: "2022-01-25T05:40:39Z",- channel: "Cool Cats Club",- channelId: "1234",- timezone: "Australia/Brisbane",- reactionsAttr,- reactions: [- { emoji: "+1", usernames: ["martin"] },- { emoji: "heart", usernames: ["martin", "eviltrout"] },- ],- }),- "renders with the reaction data attribute and HTML"- );- });-- test("renders with minimal markdown rules inside the quote bbcode block, same as server-side chat messages", function (assert) {- assert.cookedChatTranscript(- `[chat quote="johnsmith;450;2021-04-25T05:40:39Z"]-[quote="martin, post:3, topic:6215"]-another cool reply-[/quote]-[/chat]`,- { additionalOptions },- generateTranscriptHTML(- `<p>[quote="martin, post:3, topic:6215"]<br>-another cool reply<br>-[/quote]</p>`,- {- messageId: "450",- username: "johnsmith",- datetime: "2021-04-25T05:40:39Z",- timezone: "Australia/Brisbane",- }- ),- "does not render the markdown feature that has been excluded"- );-- assert.cookedChatTranscript(- `[chat quote="martin;2321;2022-01-25T05:40:39Z"]\nThis ~~does work~~ with removed _rules_.\n\n* list item 1\n[/chat]`,- { additionalOptions },- generateTranscriptHTML(- `<p>This <s>does work</s> with removed <em>rules</em>.</p>-<ul>-<li>list item 1</li>-</ul>`,- {- messageId: "2321",- username: "martin",- datetime: "2022-01-25T05:40:39Z",- timezone: "Australia/Brisbane",- }- ),- "renders correctly when the rule has not been excluded"- );-- additionalOptions.chat.limited_pretty_text_markdown_rules = [- "autolink",- // "list",- "backticks",- "newline",- "code",- "fence",- "table",- "linkify",- "link",- // "strikethrough",- "blockquote",- // "emphasis",- ];-- assert.cookedChatTranscript(- `[chat quote="martin;2321;2022-01-25T05:40:39Z"]\nThis ~~does work~~ with removed _rules_.\n\n* list item 1\n[/chat]`,- { additionalOptions },- generateTranscriptHTML(- `<p>This ~~does work~~ with removed _rules_.</p>-<p>* list item 1</p>`,- {- messageId: "2321",- username: "martin",- datetime: "2022-01-25T05:40:39Z",- timezone: "Australia/Brisbane",- }- ),- "renders correctly with some obvious rules excluded (list/strikethrough/emphasis)"- );-- assert.cookedChatTranscript(- `[chat quote="martin;2321;2022-01-25T05:40:39Z"]\nhere is a message :P with category hashtag #test\n[/chat]`,- { additionalOptions },- generateTranscriptHTML(- `<p>here is a message <img src=\"/images/emoji/twitter/stuck_out_tongue.png?v=12\" title=\":stuck_out_tongue:\" class=\"emoji\" alt=\":stuck_out_tongue:\" loading=\"lazy\" width=\"20\" height=\"20\"> with category hashtag <span class=\"hashtag\">#test</span></p>`,- {- messageId: "2321",- username: "martin",- datetime: "2022-01-25T05:40:39Z",- timezone: "Australia/Brisbane",- }- ),- "renders correctly when the feature has not been excluded"- );-- additionalOptions.chat.limited_pretty_text_features = [- "anchor",- "bbcode-block",- "bbcode-inline",- "code",- // "category-hashtag",- "censored",- "discourse-local-dates",- "emoji",- // "emojiShortcuts",- "inlineEmoji",- "html-img",- "mentions",- "onebox",- "text-post-process",- "upload-protocolrouter.location.setURL",- "watched-words",- "table",- "spoiler-alert",- ];-- assert.cookedChatTranscript(- `[chat quote="martin;2321;2022-01-25T05:40:39Z"]\nhere is a message :P with category hashtag #test\n[/chat]`,- { additionalOptions },- generateTranscriptHTML(- `<p>here is a message :P with category hashtag #test</p>`,- {- messageId: "2321",- username: "martin",- datetime: "2022-01-25T05:40:39Z",- timezone: "Australia/Brisbane",- }- ),- "renders correctly with some obvious features excluded (category-hashtag, emojiShortcuts)"- );-- assert.cookedChatTranscript(- `This ~~does work~~ with removed _rules_.--* list item 1--here is a message :P with category hashtag #test--[chat quote="martin;2321;2022-01-25T05:40:39Z"]-This ~~does work~~ with removed _rules_.--* list item 1--here is a message :P with category hashtag #test-[/chat]`,- { additionalOptions },- `<p>This <s>does work</s> with removed <em>rules</em>.</p>-<ul>-<li>list item 1</li>-</ul>-<p>here is a message <img src=\"/images/emoji/twitter/stuck_out_tongue.png?v=12\" title=\":stuck_out_tongue:\" class=\"emoji\" alt=\":stuck_out_tongue:\" loading=\"lazy\" width=\"20\" height=\"20\"> with category hashtag <span class=\"hashtag\">#test</span></p>\n` +- generateTranscriptHTML(- `<p>This ~~does work~~ with removed _rules_.</p>-<p>* list item 1</p>-<p>here is a message :P with category hashtag #test</p>`,- {- messageId: "2321",- username: "martin",- datetime: "2022-01-25T05:40:39Z",- timezone: "Australia/Brisbane",- }- ),- "the rule changes do not apply outside the BBCode [chat] block"- );- });-});--acceptance(- "Discourse Chat | chat-transcript date decoration",- function (needs) {- let additionalOptions = buildAdditionalOptions();-- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- timezone: "Australia/Brisbane",- });- needs.settings({- chat_enabled: true,- });-- needs.pretender((server, helper) => {- server.get("/chat/chat_channels.json", () =>- helper.response({- public_channels: [],- direct_message_channels: [],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- })- );-- const topicResponse = cloneJSON(topicFixtures["/t/280/1.json"]);- const firstPost = topicResponse.post_stream.posts[0];- const postCooked = cookMarkdown(- `[chat quote="martin;2321;2022-01-25T05:40:39Z"]\nThis is a chat message.\n[/chat]`,- { additionalOptions }- );- firstPost.cooked += postCooked;-- server.get("/t/280.json", () => helper.response(topicResponse));- });-- test("chat transcript datetimes are formatted into the link with decorateCookedElement", async function (assert) {- await visit("/t/-/280");-- assert.strictEqual(- query(".chat-transcript-datetime span").innerText.trim(),- moment- .tz("2022-01-25T05:40:39Z", "Australia/Brisbane")- .format(I18n.t("dates.long_no_year")),- "it decorates the chat transcript datetime link with a formatted date"- );- });- }-);--acceptance(- "Discourse Chat - chat-transcript - Composer Oneboxes ",- function (needs) {- let additionalOptions = buildAdditionalOptions();- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- timezone: "Australia/Brisbane",- });- needs.settings({- chat_enabled: true,- enable_markdown_linkify: true,- max_oneboxes_per_post: 2,- });- needs.pretender((server, helper) => {- server.get("/chat/chat_channels.json", () =>- helper.response({- public_channels: [],- direct_message_channels: [],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- })- );-- const topicResponse = cloneJSON(topicFixtures["/t/280/1.json"]);- const firstPost = topicResponse.post_stream.posts[0];- const postCooked = cookMarkdown(- `[chat quote="martin;2321;2022-01-25T05:40:39Z"]\nThis is a chat message.\n[/chat]`,- { additionalOptions }- );- firstPost.cooked += postCooked;-- server.get("/t/280.json", () => helper.response(topicResponse));- });-- test("Preview should not error for oneboxes within [chat] bbcode", async function (assert) {- await visit("/t/internationalization-localization/280");- await click("#topic-footer-buttons .btn.create");-- await fillIn(- ".d-editor-input",- `-[chat quote="martin;2321;2022-01-25T05:40:39Z" channel="Cool Cats Club" channelId="1234" multiQuote="true"]-http://www.example.com/has-title.html-[/chat]`- );-- const rendered = generateTranscriptHTML(- '<p><aside class="onebox"><article class="onebox-body"><h3><a href="http://www.example.com/article.html" tabindex="-1">An interesting article</a></h3></article></aside></p>',- {- messageId: "2321",- username: "martin",- datetime: "2022-01-25T05:40:39Z",- channel: "Cool Cats Club",- channelId: "1234",- multiQuote: true,- linkTabIndex: true,- showDateTimeText: true,- timezone: "Australia/Brisbane",- }- );-- assert.strictEqual(- query(".d-editor-preview").innerHTML.trim(),- rendered.trim(),- "it renders correctly with the onebox inside the [chat] bbcode"- );-- const textarea = query("#reply-control .d-editor-input");- await fillIn(".d-editor-input", textarea.value + "\nA");- assert.ok(- query(".d-editor-preview").innerHTML.trim().includes("\n<p>A</p>"),- "it does not error with a opts.discourse.hoisted error in the markdown pipeline when typing more text"- );- });- }-);diff --git a/plugins/chat/test/javascripts/acceptance/chat-user-menu-notifications-test.js b/plugins/chat/test/javascripts/acceptance/chat-user-menu-notifications-test.jsdeleted file mode 100644index 866def7056f..00000000000--- a/plugins/chat/test/javascripts/acceptance/chat-user-menu-notifications-test.js+++ /dev/null@@ -1,252 +0,0 @@-import I18n from "I18n";-import { test } from "qunit";--import { click, visit } from "@ember/test-helpers";--import {- acceptance,- exists,- query,- queryAll,- updateCurrentUser,-} from "discourse/tests/helpers/qunit-helpers";--import {- baseChatPretenders,- chatChannelPretender,-} from "../helpers/chat-pretenders";--acceptance(- "Discourse Chat - experiment user menu notifications - user cannot chat",- function (needs) {- needs.user({ has_chat_enabled: false });- needs.settings({ chat_enabled: false });-- test("chat notifications tab is not displayed in user menu", async function (assert) {- await visit("/");- await click(".header-dropdown-toggle.current-user");-- assert.notOk(- exists("#user-menu-button-chat-notifications"),- "button for chat notifications tab is not displayed"- );- });- }-);--acceptance(- "Discourse Chat - experimental user menu notifications ",- function (needs) {- needs.user({ redesigned_user_menu_enabled: true, has_chat_enabled: true });- needs.settings({ chat_enabled: true });-- needs.pretender((server, helper) => {- baseChatPretenders(server, helper);- chatChannelPretender(server, helper);- });-- test("chat notifications tab", async function (assert) {- updateCurrentUser({- grouped_unread_notifications: {- 29: 3, // chat_mention notification type- 31: 1, // chat_invitation notification type- },- });-- await visit("/");- await click(".header-dropdown-toggle.current-user");-- assert.ok(- exists("#user-menu-button-chat-notifications"),- "button for chat notifications tab is displayed"- );-- assert.ok(- exists("#user-menu-button-chat-notifications .d-icon-comment"),- "displays the comment icon for chat notification tab button"- );-- assert.strictEqual(- query("#user-menu-button-chat-notifications .badge-notification")- .textContent,- "4",- "displays the right badge count for chat notifications tab button"- );- });-- test("chat mention notification link", async function (assert) {- await visit("/");- await click(".header-dropdown-toggle.current-user");-- const chatMentionNotificationLink = queryAll(".chat-mention a")[0];-- assert.strictEqual(- chatMentionNotificationLink.textContent- .trim()- .replace(/\n/g, "")- .replace(/\s+/, " "),- 'hawk mentioned you in "Site"',- "displays the right text for notification"- );-- assert.ok(- exists(chatMentionNotificationLink.querySelector(".d-icon-comment")),- "displays the right icon for the notification"- );-- assert.strictEqual(- chatMentionNotificationLink.title,- I18n.t("notifications.titles.chat_mention"),- "has the right title attribute for notification link"- );-- assert.ok(- chatMentionNotificationLink.href.endsWith(- "/chat/channel/9/site?messageId=174"- ),- "has the right href attribute for notification link"- );- });-- test("personal chat mention notification link", async function (assert) {- await visit("/");- await click(".header-dropdown-toggle.current-user");-- const personalChatMentionNotificationLink =- queryAll(".chat-mention a")[3];-- assert.strictEqual(- personalChatMentionNotificationLink.textContent- .trim()- .replace(/\n/g, "")- .replace(/\s+/, " "),- "hawk mentioned you in personal chat",- "displays the right text for notification"- );-- assert.ok(- exists(- personalChatMentionNotificationLink.querySelector(".d-icon-comment")- ),- "displays the right icon for the notification"- );-- assert.strictEqual(- personalChatMentionNotificationLink.title,- I18n.t("notifications.titles.chat_mention"),- "has the right title attribute for notification link"- );-- assert.ok(- personalChatMentionNotificationLink.href.endsWith(- "/chat/channel/9/site?messageId=174"- ),- "has the right href attribute for notification link"- );- });-- test("chat group mention notification link", async function (assert) {- await visit("/");- await click(".header-dropdown-toggle.current-user");-- const chatGroupMentionNotificationLink = queryAll(".chat-mention a")[1];-- assert.strictEqual(- chatGroupMentionNotificationLink.textContent- .trim()- .replace(/\n/g, "")- .replace(/\s+/, " "),- 'hawk mentioned @engineers in "Site"',- "displays the right text for notification"- );-- assert.ok(- exists(- chatGroupMentionNotificationLink.querySelector(".d-icon-comment")- ),- "displays the right icon for the notification"- );-- assert.strictEqual(- chatGroupMentionNotificationLink.title,- I18n.t("notifications.titles.chat_mention"),- "has the right title attribute for notification link"- );-- assert.ok(- chatGroupMentionNotificationLink.href.endsWith(- "/chat/channel/9/site?messageId=174"- ),- "has the right href attribute for notification link"- );- });-- test("chat all mention notification link", async function (assert) {- await visit("/");- await click(".header-dropdown-toggle.current-user");-- const chatAllMentionNotificationLink = queryAll(".chat-mention a")[2];-- assert.strictEqual(- chatAllMentionNotificationLink.textContent- .trim()- .replace(/\n/g, "")- .replace(/\s+/, " "),- 'hawk mentioned @all in "Site"',- "displays the right text for notification"- );-- assert.ok(- exists(chatAllMentionNotificationLink.querySelector(".d-icon-comment")),- "displays the right icon for the notification"- );-- assert.strictEqual(- chatAllMentionNotificationLink.title,- I18n.t("notifications.titles.chat_mention"),- "has the right title attribute for notification link"- );-- assert.ok(- chatAllMentionNotificationLink.href.endsWith(- "/chat/channel/9/site?messageId=174"- ),- "has the right href attribute for notification link"- );- });-- test("chat invite notification link", async function (assert) {- await visit("/");- await click(".header-dropdown-toggle.current-user");-- const chatInviteNotificationLink = queryAll(".chat-invitation a")[0];-- assert.strictEqual(- chatInviteNotificationLink.textContent- .trim()- .replace(/\n/g, "")- .replace(/\s+/, " "),- "hawk invited you to join a chat channel",- "displays the right text for notification"- );-- assert.ok(- exists(chatInviteNotificationLink.querySelector(".d-icon-link")),- "displays the right icon for the notification"- );-- assert.strictEqual(- chatInviteNotificationLink.title,- I18n.t("notifications.titles.chat_invitation"),- "has the right title attribute for notification link"- );-- assert.ok(- chatInviteNotificationLink.href.endsWith(- "/chat/channel/9/site?messageId=174"- ),- "has the right href attribute for notification link"- );- });- }-);diff --git a/plugins/chat/test/javascripts/acceptance/composer-hashtag-autocomplete-test.js b/plugins/chat/test/javascripts/acceptance/composer-hashtag-autocomplete-test.jsdeleted file mode 100644index d731a7c0f87..00000000000--- a/plugins/chat/test/javascripts/acceptance/composer-hashtag-autocomplete-test.js+++ /dev/null@@ -1,68 +0,0 @@-import { setCaretPosition } from "discourse/lib/utilities";-import {- acceptance,- exists,- query,- queryAll,-} from "discourse/tests/helpers/qunit-helpers";-import { skip } from "qunit";-import { chatChannelPretender } from "../helpers/chat-pretenders";-import { fillIn, settled, triggerKeyEvent, visit } from "@ember/test-helpers";--acceptance(- "Discourse Chat - Composer hashtag autocompletion",- function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 100,- can_chat: true,- has_chat_enabled: true,- });- needs.pretender((server, helper) => {- chatChannelPretender(server, helper);- server.get("/chat/:id/messages.json", () =>- helper.response({ chat_messages: [], meta: {} })- );- server.post("/chat/drafts", () => helper.response(500, {}));- server.get("/hashtags/search.json", () => {- return helper.response({- results: [- { type: "category", text: "Design", slug: "design", ref: "design" },- { type: "tag", text: "dev", slug: "dev", ref: "dev" },- { type: "tag", text: "design", slug: "design", ref: "design::tag" },- ],- });- });- });- needs.settings({- chat_enabled: true,- enable_experimental_hashtag_autocomplete: true,- });-- skip("using # in the chat composer shows category and tag autocomplete options", async function (assert) {- await visit("/chat/channel/11/-");- const composerInput = query(".chat-composer-input");- await fillIn(".chat-composer-input", "abc #");- await triggerKeyEvent(".chat-composer-input", "keydown", "#");- await fillIn(".chat-composer-input", "abc #");- await setCaretPosition(composerInput, 5);- await triggerKeyEvent(".chat-composer-input", "keyup", "#");- await triggerKeyEvent(".chat-composer-input", "keydown", "D");- await fillIn(".chat-composer-input", "abc #d");- await setCaretPosition(composerInput, 6);- await triggerKeyEvent(".chat-composer-input", "keyup", "D");- await settled();- assert.ok(- exists(".hashtag-autocomplete"),- "hashtag autocomplete menu appears"- );- assert.strictEqual(- queryAll(".hashtag-autocomplete__option").length,- 3,- "all options should be shown"- );- });- }-);diff --git a/plugins/chat/test/javascripts/acceptance/core-sidebar-test.js b/plugins/chat/test/javascripts/acceptance/core-sidebar-test.jsdeleted file mode 100644index 52d303dc2f3..00000000000--- a/plugins/chat/test/javascripts/acceptance/core-sidebar-test.js+++ /dev/null@@ -1,777 +0,0 @@-import {- acceptance,- exists,- query,- queryAll,-} from "discourse/tests/helpers/qunit-helpers";-import { test } from "qunit";-import { click, currentURL, settled, visit } from "@ember/test-helpers";-import { directMessageChannels } from "discourse/plugins/chat/chat-fixtures";-import { cloneJSON } from "discourse-common/lib/object";-import I18n from "I18n";-import { withPluginApi } from "discourse/lib/plugin-api";-import { emojiUnescape } from "discourse/lib/text";-import User from "discourse/models/user";--acceptance("Discourse Chat - Core Sidebar", function (needs) {- needs.user({ has_chat_enabled: true });-- needs.settings({- chat_enabled: true,- navigation_menu: "sidebar",- });-- needs.pretender((server, helper) => {- let directChannels = cloneJSON(directMessageChannels).mapBy("chat_channel");- directChannels[0].chatable.users = [directChannels[0].chatable.users[0]];- directChannels[0].current_user_membership.unread_count = 1;- directChannels.push({- chatable: {- users: [- {- id: 1,- username: "markvanlan",- avatar_template:- "/letter_avatar_proxy/v4/letter/t/f9ae1b/{size}.png",- },- {- id: 2,- username: "sam",- avatar_template:- "/letter_avatar_proxy/v4/letter/t/f9ae1b/{size}.png",- },- ],- },- chatable_id: 59,- chatable_type: "DirectMessage",- chatable_url: null,- id: 76,- title: "@sam",- last_message_sent_at: "2021-06-01T11:15:00.000Z",- current_user_membership: {- unread_count: 0,- muted: true,- following: true,- },- message_bus_last_ids: {- new_mentions: 0,- new_messages: 0,- },- });- directChannels.push({- chatable: {- users: [- {- id: 1,- username: "<script>markvanlan</script>",- avatar_template:- "/letter_avatar_proxy/v4/letter/t/f9ae1b/{size}.png",- },- {- id: 2,- username: "<script>sam</script>",- avatar_template:- "/letter_avatar_proxy/v4/letter/t/f9ae1b/{size}.png",- },- ],- },- chatable_type: "DirectMessage",- chatable_url: null,- id: 77,- title: "@<script>sam</script>",- last_message_sent_at: "2021-06-01T11:15:00.000Z",- current_user_membership: {- unread_count: 0,- muted: false,- following: true,- },- message_bus_last_ids: {- new_mentions: 0,- new_messages: 0,- },- });-- server.get("/chat/chat_channels.json", () => {- return helper.response({- public_channels: [- {- id: 1,- title: "dev :bug:",- chatable_type: "Category",- chatable: { slug: "dev", read_restricted: true },- last_message_sent_at: "2021-11-08T21:26:05.710Z",- current_user_membership: {- unread_count: 0,- unread_mentions: 0,- },- message_bus_last_ids: {- new_mentions: 0,- new_messages: 0,- },- },- {- id: 2,- title: "general",- chatable_type: "Category",- chatable: { slug: "general" },- last_message_sent_at: "2021-11-08T21:26:05.710Z",- current_user_membership: {- unread_count: 1,- unread_mentions: 0,- },- message_bus_last_ids: {- new_mentions: 0,- new_messages: 0,- },- },- {- id: 3,- title: "random",- description: "The channel for random <script>evil</script> things",- chatable_type: "Category",- chatable: { slug: "random" },- last_message_sent_at: "2021-11-08T21:26:05.710Z",- current_user_membership: {- muted: true,- unread_count: 1,- unread_mentions: 1,- },- message_bus_last_ids: {- new_mentions: 0,- new_messages: 0,- },- },- {- id: 4,- title: "<script>evil</script>",- chatable_type: "Category",- chatable: { slug: "random" },- last_message_sent_at: "2021-11-08T21:26:05.710Z",- current_user_membership: {- unread_count: 1,- unread_mentions: 1,- },- message_bus_last_ids: {- new_mentions: 0,- new_messages: 0,- },- },- ],- direct_message_channels: directChannels,- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- });- });-- server.get("/chat/1/messages.json", () =>- helper.response({- meta: {- can_chat: true,- user_silenced: false,- channel_message_bus_last_id: 0,- },- chat_messages: [],- })- );-- server.get("/u/search/users", () => {- return helper.response({- users: [- {- username: "hawk",- id: 2,- name: "hawk",- avatar_template:- "/letter_avatar_proxy/v4/letter/t/41988e/{size}.png",- },- ],- });- });-- server.get("/chat/75/messages.json", () =>- helper.response({- meta: { can_chat: true, user_silenced: false },- chat_messages: [],- })- );-- server.get("/chat/direct_messages.json", () => {- return helper.response({- chat_channel: {- id: 75,- title: "hawk",- chatable_type: "DirectMessage",- last_message_sent_at: "2021-07-20T08:14:16.950Z",- chatable: {- users: [{ username: "hawk" }],- },- },- });- });- });-- needs.hooks.beforeEach(function () {- withPluginApi("1.3.0", (api) => {- api.addUsernameSelectorDecorator((username) => {- if (username === "hawk") {- return `<span class="on-holiday">${emojiUnescape(- ":desert_island:"- )}</span>`;- }- });- });- });-- test("Public channels section", async function (assert) {- await visit("/");-- assert.strictEqual(- query(- ".sidebar-section-chat-channels .sidebar-section-header-text"- ).textContent.trim(),- I18n.t("chat.chat_channels"),- "displays correct channels section title"- );-- assert.ok(- exists(- ".sidebar-section-chat-channels .sidebar-section-link-dev-bug .sidebar-section-link-prefix svg.prefix-icon.d-icon-hashtag"- ),- "dev channel section link displays hash icon prefix"- );-- assert.ok(- exists(- ".sidebar-section-chat-channels .sidebar-section-link-dev-bug .sidebar-section-link-prefix svg.prefix-badge.d-icon-lock"- ),- "dev channel section link displays lock badge for restricted channel"- );-- assert.ok(- exists(- ".sidebar-section-chat-channels .sidebar-section-link-dev-bug .emoji"- ),- "unescapes emoji in channel title in the link"- );-- assert.strictEqual(- query(- ".sidebar-section-chat-channels .sidebar-section-link-dev-bug"- ).textContent.trim(),- "dev",- "dev channel section link displays channel title in the link"- );-- assert.ok(- query(- ".sidebar-section-chat-channels .sidebar-section-link-dev-bug"- ).href.endsWith("/chat/channel/1/dev-bug"),- "dev channel section link has the right href attribute"- );-- assert.notOk(- exists(- ".sidebar-section-chat-channels .sidebar-section-link-dev-bug .sidebar-section-link-suffix"- ),- "does not display new messages indicator"- );-- assert.ok(- exists(- ".sidebar-section-chat-channels .sidebar-section-link-general .sidebar-section-link-prefix svg.prefix-icon.d-icon-hashtag"- ),- "general channel section link displays hash icon prefix"- );-- assert.notOk(- exists(- ".sidebar-section-chat-channels .sidebar-section-link-general .sidebar-section-link-prefix svg.prefix-badge"- ),- "general channel section link does not display lock badge for public channel"- );-- assert.strictEqual(- query(- ".sidebar-section-chat-channels .sidebar-section-link-general"- ).textContent.trim(),- "general",- "general channel section link displays channel title in the link"- );-- assert.ok(- exists(- ".sidebar-section-chat-channels .sidebar-section-link-general .sidebar-section-link-suffix.unread"- ),- "general section link has new messages indicator"- );-- assert.ok(- exists(- ".sidebar-section-chat-channels .sidebar-section-link-random .sidebar-section-link-prefix svg.prefix-icon.d-icon-hashtag"- ),- "random channel section link displays hash icon prefix"- );-- assert.strictEqual(- query(- ".sidebar-section-chat-channels .sidebar-section-link-random"- ).textContent.trim(),- "random",- "random channel section link displays channel title in the link"- );-- assert.ok(- exists(- ".sidebar-section-chat-channels .sidebar-section-link-random .sidebar-section-link-suffix.urgent"- ),- "random section link has new messages mention indicator"- );- });-- test("sidebar section link when direct message channel is muted by user", async function (assert) {- await visit("/");-- assert.ok(- exists(- ".sidebar-section-chat-dms .sidebar-section-link-sam.sidebar-section-link--muted"- ),- "muted direct chat channel section link has right classname configured"- );- });-- test("sidebar section link when public channel is muted by user", async function (assert) {- await visit("/");-- assert.ok(- exists(- ".sidebar-section-chat-channels .sidebar-section-link-random.sidebar-section-link--muted"- ),- "muted random chat channel section link has right classname configured"- );- });-- test("Direct messages section", async function (assert) {- const chatService = this.container.lookup("service:chat");- chatService.directMessagesLimit = 2;- await visit("/");-- assert.strictEqual(- query(- ".sidebar-section-chat-dms .sidebar-section-header-text"- ).textContent.trim(),- I18n.t("chat.direct_messages.title"),- "displays correct direct messages section title"- );-- let directLinks = queryAll(- ".sidebar-section-chat-dms a.sidebar-section-link"- );-- assert.strictEqual(- directLinks[0]- .querySelector(".sidebar-section-link-prefix img")- .classList.contains("prefix-image"),- true,- "displays avatar in prefix when two participants"- );-- assert.strictEqual(- directLinks[0].textContent.trim(),- "hawk",- "displays user name in a link"- );-- assert.ok(- directLinks[0].querySelector(- ".sidebar-section-link-content-text .on-holiday img"- ),- "displays flair when user is on holiday"- );-- assert.strictEqual(- directLinks[0]- .querySelector(".sidebar-section-link-suffix")- .classList.contains("urgent"),- true,- "displays new messages indicator"- );-- assert.strictEqual(- directLinks[1]- .querySelector("span.sidebar-section-link-prefix")- .classList.contains("text"),- true,- "displays text in prefix when more than two participants"- );-- assert.strictEqual(- directLinks[1]- .querySelector(".sidebar-section-link-content-text")- .textContent.trim(),- "eviltrout, markvanlan",- "displays all participants name in a link"- );-- assert.ok(- !directLinks[1].querySelector(".sidebar-section-link-suffix"),- "does not display new messages indicator"- );- User.current().chat_channel_tracking_state[76].set("unread_count", 99);- chatService.reSortDirectMessageChannels();- chatService.appEvents.trigger("chat:user-tracking-state-changed");- await settled();-- directLinks = queryAll(".sidebar-section-chat-dms a.sidebar-section-link");- assert.strictEqual(- directLinks[0]- .querySelector(".sidebar-section-link-content-text")- .textContent.trim(),- "eviltrout, markvanlan",- "reorders private messages"- );-- assert.equal(- directLinks.length,- 2,- "limits number of displayed direct messages"- );- });-- test("Plugin sidebar is hidden", async function (assert) {- await visit("/chat/channel/1/dev");- assert.notOk(exists(".full-page-chat .channels-list"));- });-- test("Open a new direct conversation", async function (assert) {- await visit("/");- await click(".sidebar-section-chat-dms .sidebar-section-header-button");-- assert.ok(exists(".direct-message-creator"));- assert.ok(exists(".chat-drawer.is-expanded"));- assert.strictEqual(currentURL(), "/");- });-- test("Escaped channel description used as title when present", async function (assert) {- await visit("/");-- const randomChannel = queryAll(- ".sidebar-section-chat-channels .sidebar-section-link-wrapper .sidebar-section-link"- )[3];-- assert.strictEqual(- randomChannel.title,- "The channel for random <script>evil</script> things"- );- });-- test("Escapes public channel titles", async function (assert) {- await visit("/");-- const evilChannel = query(- ".sidebar-section-chat-channels .sidebar-section-link-wrapper .sidebar-section-link"- );-- assert.strictEqual(- evilChannel.title,- "<script>evil</script> chat"- );-- assert.ok(- evilChannel.className.includes(- "sidebar-section-link-ltscriptgtevilltscriptgt"- )- );-- assert.strictEqual(- evilChannel- .querySelector(".sidebar-section-link-content-text")- .innerHTML.trim(),- "<script>evil</script>"- );- });-- test("Escapes dm channel titles", async function (assert) {- await visit("/");-- const evilChannel = queryAll(- ".sidebar-section-chat-dms .sidebar-section-link-wrapper .sidebar-section-link"- )[3];-- assert.strictEqual(- evilChannel.title,- "Chat with @<script>sam</script>"- );-- assert.ok(- evilChannel.className.includes(- "sidebar-section-link-ltscriptgtsamltscriptgt"- )- );-- assert.strictEqual(- evilChannel- .querySelector(".sidebar-section-link-content-text")- .innerHTML.trim(),- "&lt;script&gt;sam&lt;/script&gt;"- );- });-});--acceptance("Discourse Chat - Plugin Sidebar", function (needs) {- needs.user({ has_chat_enabled: true });-- needs.settings({- chat_enabled: true,- navigation_menu: "legacy",- });-- needs.pretender((server, helper) => {- server.get("/chat/chat_channels.json", () => {- return helper.response({- public_channels: [- {- id: 1,- title: "dev :bug:",- chatable_type: "Category",- chatable: { slug: "dev", read_restricted: true },- last_message_sent_at: "2021-11-08T21:26:05.710Z",- current_user_membership: {- unread_count: 1,- unread_mentions: 1,- },- message_bus_last_ids: {- new_mentions: 0,- new_messages: 0,- },- },- {- id: 2,- title: "general",- chatable_type: "Category",- chatable: { slug: "general" },- last_message_sent_at: "2021-11-08T21:26:05.710Z",- current_user_membership: {- unread_count: 1,- unread_mentions: 1,- },- message_bus_last_ids: {- new_mentions: 0,- new_messages: 0,- },- },- {- id: 3,- title: "random",- chatable_type: "Category",- chatable: { slug: "random" },- last_message_sent_at: "2021-11-08T21:26:05.710Z",- current_user_membership: {- unread_count: 1,- unread_mentions: 1,- },- message_bus_last_ids: {- new_mentions: 0,- new_messages: 0,- },- },- ],- direct_message_channels: [],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- });- });-- server.get("/chat/1/messages.json", () =>- helper.response({- meta: { can_chat: true, user_silenced: false },- chat_messages: [],- })- );- });-- test("Plugin sidebar is visible", async function (assert) {- await visit("/chat/channel/1/dev");- assert.ok(exists(".full-page-chat .channels-list"));- });-});--acceptance(- "Discourse Chat - Core Sidebar - no joinable public channels, staff",- function (needs) {- needs.user({ has_chat_enabled: true, has_joinable_public_channels: false });-- needs.settings({- chat_enabled: true,- navigation_menu: "sidebar",- });-- needs.pretender((server, helper) => {- server.get("/chat/chat_channels.json", () => {- return helper.response({- public_channels: [],- direct_message_channels: [],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- });- });- });-- test("Chat channels section visibility", async function (assert) {- await visit("/");-- assert.ok(- exists(".sidebar-section-chat-channels"),- "it shows the section for staff"- );- });- }-);--acceptance(- "Discourse Chat - Core Sidebar - no joinable public channels, regular user",- function (needs) {- needs.user({- has_chat_enabled: true,- has_joinable_public_channels: false,- moderator: false,- admin: false,- });-- needs.settings({- chat_enabled: true,- navigation_menu: "sidebar",- });-- needs.pretender((server, helper) => {- server.get("/chat/chat_channels.json", () => {- return helper.response({- public_channels: [],- direct_message_channels: [],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- });- });- });-- test("Chat channels section visibility", async function (assert) {- await visit("/");-- assert.notOk(- exists(".sidebar-section-chat-channels"),- "it doesn’t show the section for regular user"- );- });- }-);--acceptance(- "Discourse Chat - Core Sidebar - regular user with no direct message channels who cannot send direct messages",- function (needs) {- needs.user({- has_chat_enabled: true,- moderator: false,- admin: false,- });-- needs.settings({- chat_enabled: true,- navigation_menu: "sidebar",- direct_message_enabled_groups: "13", // trust_level_3 auto group ID;- });-- needs.pretender((server, helper) => {- server.get("/chat/chat_channels.json", () => {- return helper.response({- public_channels: [],- direct_message_channels: [],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- });- });- });-- test("Direct message channels section visibility", async function (assert) {- await visit("/");-- assert.notOk(- exists(".sidebar-section-chat-dms"),- "it doesn’t show the section for regular user"- );- });- }-);--acceptance(- "Discourse Chat - Core Sidebar - regular user with existing direct message channels who cannot send direct messages",- function (needs) {- needs.user({- has_chat_enabled: true,- moderator: false,- admin: false,- });-- needs.settings({- chat_enabled: true,- navigation_menu: "sidebar",- direct_message_enabled_groups: "13", // trust_level_3 auto group ID;- });-- needs.pretender((server, helper) => {- let directChannels = cloneJSON(directMessageChannels).mapBy(- "chat_channel"- );- server.get("/chat/chat_channels.json", () => {- return helper.response({- public_channels: [],- direct_message_channels: directChannels,- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- });- });- });-- test("Direct message channels section visibility", async function (assert) {- await visit("/");-- assert.ok(- exists(".sidebar-section-chat-dms"),- "it does show the section for a regular user"- );-- assert.notOk(- exists(".sidebar-section-chat-dms .sidebar-section-header-button"),- "user cannot see the create DM channel button"- );- });- }-);diff --git a/plugins/chat/test/javascripts/acceptance/create-channel-test.js b/plugins/chat/test/javascripts/acceptance/create-channel-test.jsdeleted file mode 100644index 2a456ef1002..00000000000--- a/plugins/chat/test/javascripts/acceptance/create-channel-test.js+++ /dev/null@@ -1,186 +0,0 @@-import selectKit from "discourse/tests/helpers/select-kit-helper";-import { click, visit } from "@ember/test-helpers";-import { acceptance, query } from "discourse/tests/helpers/qunit-helpers";-import { test } from "qunit";--acceptance("Discourse Chat - Create channel modal", function (needs) {- const maliciousText = '"<script></script>';-- needs.user({- username: "tomtom",- id: 1,- can_chat: true,- has_chat_enabled: true,- });-- needs.settings({- chat_enabled: true,- });-- const catsCategory = {- id: 1,- name: "Cats",- slug: "cats",- permission: 1,- };-- needs.site({- categories: [- catsCategory,- {- id: 2,- name: maliciousText,- slug: maliciousText,- permission: 1,- },- {- id: 3,- name: "Kittens",- slug: "kittens",- permission: 1,- parentCategory: catsCategory,- },- ],- });-- needs.pretender((server, helper) => {- server.get("/chat/:chatChannelId/messages.json", () =>- helper.response({- meta: { can_chat: true, user_silenced: false },- chat_messages: [],- })- );-- server.get("/chat/chat_channels.json", () =>- helper.response({- public_channels: [],- direct_message_channels: [],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- })- );-- server.get("/chat/chat_channels/:chatChannelId", () =>- helper.response({ id: 1, title: "something" })- );-- server.get("/chat/api/chat_channels.json", () => helper.response([]));-- server.get(- "/chat/api/category-chatables/:categoryId/permissions.json",- (request) => {- if (request.params.categoryId === "2") {- return helper.response({- allowed_groups: ["@<script>evilgroup</script>"],- members_count: 2,- private: true,- });- } else {- return helper.response({- allowed_groups: ["@awesomeGroup"],- members_count: 2,- private: true,- });- }- }- );- });-- test("links to categories and selected category's security settings", async function (assert) {- await visit("/chat/browse");- await click(".new-channel-btn");-- assert.strictEqual(- query(".create-channel-hint a").innerText,- "category security settings"- );- assert.ok(query(".create-channel-hint a").href.includes("/categories"));-- let categories = selectKit(".create-channel-modal .category-chooser");- await categories.expand();- await categories.selectRowByName("Cats");-- assert.strictEqual(- query(".create-channel-hint a").innerText,- "security settings"- );- assert.ok(- query(".create-channel-hint a").href.includes("/c/cats/edit/security")- );- });-- test("links to selected category's security settings works with nested subcategories", async function (assert) {- await visit("/chat/browse");- await click(".new-channel-btn");-- assert.strictEqual(- query(".create-channel-hint a").innerText,- "category security settings"- );- assert.ok(query(".create-channel-hint a").href.includes("/categories"));-- let categories = selectKit(".create-channel-modal .category-chooser");- await categories.expand();- await categories.selectRowByName("Kittens");-- assert.strictEqual(- query(".create-channel-hint a").innerText,- "security settings"- );- assert.ok(- query(".create-channel-hint a").href.includes(- "/c/cats/kittens/edit/security"- )- );- });-- test("includes group names in the hint", async (assert) => {- await visit("/chat/browse");- await click(".new-channel-btn");-- assert.strictEqual(- query(".create-channel-hint a").innerText,- "category security settings"- );- assert.ok(query(".create-channel-hint a").href.includes("/categories"));-- let categories = selectKit(".create-channel-modal .category-chooser");- await categories.expand();- await categories.selectRowByName("Kittens");-- assert.strictEqual(- query(".create-channel-hint").innerHTML.trim(),- 'Users in @awesomeGroup will have access to this channel per the <a href="/c/cats/kittens/edit/security" target="_blank">security settings</a>'- );- });-- test("escapes group name/category slug in the hint", async (assert) => {- await visit("/chat/browse");- await click(".new-channel-btn");-- assert.strictEqual(- query(".create-channel-hint a").innerText,- "category security settings"- );- assert.ok(query(".create-channel-hint a").href.includes("/categories"));-- const categories = selectKit(".create-channel-modal .category-chooser");- await categories.expand();- await categories.selectRowByValue(2);-- assert.strictEqual(- query(".create-channel-hint").innerHTML.trim(),- 'Users in @<script>evilgroup</script> will have access to this channel per the <a href="/c/"<script></script>/edit/security" target="_blank">security settings</a>'- );- assert.ok(- query(".create-channel-hint a").href.includes(- "c/%22%3Cscript%3E%3C/script%3E/edit/security"- )- );- });-});diff --git a/plugins/chat/test/javascripts/acceptance/delete-chat-channel-modal-test.js b/plugins/chat/test/javascripts/acceptance/delete-chat-channel-modal-test.jsdeleted file mode 100644index 48c717c273e..00000000000--- a/plugins/chat/test/javascripts/acceptance/delete-chat-channel-modal-test.js+++ /dev/null@@ -1,49 +0,0 @@-import { acceptance } from "discourse/tests/helpers/qunit-helpers";-import { click, currentURL, fillIn, visit } from "@ember/test-helpers";-import { test } from "qunit";-import fabricators from "../helpers/fabricators";--acceptance("Discourse Chat - delete chat channel modal", function (needs) {- needs.user({ has_chat_enabled: true, can_chat: true });-- needs.settings({ chat_enabled: true });-- needs.pretender((server, helper) => {- server.get("/chat/chat_channels.json", () => {- return helper.response({- public_channels: [fabricators.chatChannel({ id: 2 })],- direct_message_channels: [],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- });- });-- server.get("/chat/chat_channels/:id", (request) => {- return helper.response(- fabricators.chatChannel({ id: request.params.id })- );- });-- server.get("/chat/:id/messages.json", () => {- return helper.response({ meta: {}, chat_messages: [] });- });-- server.delete("/chat/chat_channels/:id.json", () => {- return helper.response({});- });- });-- test("Redirection after deleting a channel", async function (assert) {- await visit("chat/channel/1/my-category-title/info/settings");- await click(".delete-btn");- await fillIn("#channel-delete-confirm-name", "My category title");- await click("#chat-confirm-delete-channel");-- assert.equal(currentURL(), "/chat/channel/2/my-category-title");- });-});diff --git a/plugins/chat/test/javascripts/acceptance/mobile-chat-test.js b/plugins/chat/test/javascripts/acceptance/mobile-chat-test.jsdeleted file mode 100644index e4e95fd44d5..00000000000--- a/plugins/chat/test/javascripts/acceptance/mobile-chat-test.js+++ /dev/null@@ -1,75 +0,0 @@-import {- acceptance,- exists,- loggedInUser,-} from "discourse/tests/helpers/qunit-helpers";-import { click, currentURL, visit } from "@ember/test-helpers";-import {- chatChannels,- generateChatView,-} from "discourse/plugins/chat/chat-fixtures";-import { test } from "qunit";--acceptance("Discourse Chat - Mobile test", function (needs) {- needs.user({ can_chat: true, has_chat_enabled: true });-- needs.mobileView();-- needs.pretender((server, helper) => {- server.get("/chat/chat_channels.json", () => helper.response(chatChannels));- server.get("/chat/:id/messages.json", () =>- helper.response(generateChatView(loggedInUser()))- );- server.get("/u/search/users", () => {- return helper.response([]);- });-- server.get("/chat/api/chat_channels.json", () => {- const channels = [];- return helper.response(channels);- });- });-- needs.settings({- chat_enabled: true,- });-- test("Chat index route shows channels list", async function (assert) {- await visit("/latest");- await click(".header-dropdown-toggle.open-chat");- assert.equal(currentURL(), "/chat");- assert.ok(exists(".channels-list"));- await click('.chat-channel-row[data-chat-channel-id="7"]');- assert.notOk(exists(".open-drawer-btn"));- });-- test("Chat new personal chat buttons", async function (assert) {- await visit("/chat");- await click(".open-draft-channel-page-btn.btn-floating");-- assert.strictEqual(- currentURL(),- "/chat/draft-channel",- "Clicking the floating + button opens the new chat screen"- );-- await click(".chat-draft-header__btn");-- assert.strictEqual(- currentURL(),- "/chat",- "Clicking the left arrow button returns to the channels list"- );- });-- test("Chat browse screen back button", async function (assert) {- await visit("/chat/browse");- await click(".chat-full-page-header__back-btn");-- assert.strictEqual(- currentURL(),- "/chat",- "Clicking the back button returns to the channels list"- );- });-});diff --git a/plugins/chat/test/javascripts/acceptance/user-card-chat-test.js b/plugins/chat/test/javascripts/acceptance/user-card-chat-test.jsdeleted file mode 100644index 284b410944f..00000000000--- a/plugins/chat/test/javascripts/acceptance/user-card-chat-test.js+++ /dev/null@@ -1,113 +0,0 @@-import userFixtures from "discourse/tests/fixtures/user-fixtures";-import { cloneJSON } from "discourse-common/lib/object";-import {- acceptance,- exists,- loggedInUser,-} from "discourse/tests/helpers/qunit-helpers";-import { click, visit } from "@ember/test-helpers";-import {- chatChannels,- directMessageChannels,- generateChatView,-} from "discourse/plugins/chat/chat-fixtures";-import { test } from "qunit";--acceptance("Discourse Chat - User card test", function (needs) {- needs.user({- admin: false,- moderator: false,- username: "eviltrout",- id: 1,- can_chat: true,- has_chat_enabled: true,- });- needs.pretender((server, helper) => {- server.post("/uploads/lookup-urls", () => {- return helper.response([]);- });- server.get("/chat/chat_channels.json", () => helper.response(chatChannels));- server.get("/chat/chat_channels/:channelId.json", () =>- helper.response(helper.response(directMessageChannels[0]))- );- server.get("/chat/:chatChannelId/messages.json", () =>- helper.response(generateChatView(loggedInUser()))- );- server.post("/chat/direct_messages/create.json", () => {- return helper.response({- chat_channel: {- chat_channels: [],- chatable: {- users: [- {- username: "hawk",- id: 2,- name: "hawk",- avatar_template:- "/letter_avatar_proxy/v3/letter/t/41988e/{size}.png",- },- ],- },- chatable_id: 16,- chatable_type: "DirectMessage",- chatable_url: null,- id: 75,- title: "@hawk",- last_message_sent_at: "2021-11-08T21:26:05.710Z",- current_user_membership: {- last_read_message_id: null,- unread_count: 0,- unread_mentions: 0,- },- },- });- });- let cardResponse = cloneJSON(userFixtures["/u/charlie/card.json"]);- cardResponse.user.can_chat_user = true;- server.get("/u/hawk/card.json", () => helper.response(cardResponse));- });- needs.settings({- chat_enabled: true,- });-- needs.hooks.beforeEach(function () {- Object.defineProperty(this, "chatService", {- get: () => this.container.lookup("service:chat"),- });- Object.defineProperty(this, "appEvents", {- get: () => this.container.lookup("service:appEvents"),- });- });-- test("user card has chat button that opens the correct channel", async function (assert) {- await visit("/");- await click(".header-dropdown-toggle.open-chat");- await click('.chat-channel-row[data-chat-channel-id="9"]');- await click("[data-user-card='hawk']");-- assert.ok(exists(".user-card-chat-btn"));-- await click(".user-card-chat-btn");-- assert.ok(exists(`.chat-drawer.is-expanded[data-chat-channel-id="75"]`));- });-});--acceptance(- "Discourse Chat - Anon user viewing user card test",- function (needs) {- needs.settings({- chat_enabled: true,- });-- test("user card has no chat button", async function (assert) {- await visit("/t/internationalization-localization/280");- await click('a[data-user-card="charlie"]');-- assert.notOk(- exists(".user-card-chat-btn"),- "anon user should not be able to chat with anyone via the user card"- );- });- }-);diff --git a/plugins/chat/test/javascripts/components/chat-channel-about-view-test.js b/plugins/chat/test/javascripts/components/chat-channel-about-view-test.jsdeleted file mode 100644index 60daa3adb9b..00000000000--- a/plugins/chat/test/javascripts/components/chat-channel-about-view-test.js+++ /dev/null@@ -1,149 +0,0 @@-import { setupRenderingTest } from "discourse/tests/helpers/component-test";-import { exists, query } from "discourse/tests/helpers/qunit-helpers";-import hbs from "htmlbars-inline-precompile";-import fabricators from "../helpers/fabricators";-import { render, settled } from "@ember/test-helpers";-import { module, test } from "qunit";-import I18n from "I18n";--module(- "Discourse Chat | Component | chat-channel-about-view | admin user",- function (hooks) {- setupRenderingTest(hooks);-- hooks.beforeEach(function () {- this.set(- "channel",- fabricators.chatChannel({ chatable_type: "Category" })- );- this.channel.set("description", "foo");- this.currentUser.set("admin", true);- this.currentUser.set("has_chat_enabled", true);- this.siteSettings.chat_enabled = true;- });-- test("chatable name", async function (assert) {- await render(hbs`{{chat-channel-about-view channel=channel}}`);-- assert.equal(- query(".category-name").innerText,- this.channel.chatable.name- );- });-- test("chatable description", async function (assert) {- await render(hbs`{{chat-channel-about-view channel=channel}}`);-- assert.equal(- query(".category-name").innerText,- this.channel.chatable.name- );-- this.channel.set("description", null);- await settled();-- assert.equal(- query(".channel-info-about-view__description__helper-text").innerText,- I18n.t("chat.channel_edit_description_modal.description")- );- });-- test("edit title", async function (assert) {- await render(hbs`{{chat-channel-about-view channel=channel}}`);-- assert.ok(exists(".edit-title-btn"));- });-- test("edit description", async function (assert) {- await render(hbs`{{chat-channel-about-view channel=channel}}`);-- assert.ok(exists(".edit-description-btn"));- });-- test("join", async function (assert) {- await render(hbs`{{chat-channel-about-view channel=channel}}`);-- assert.ok(exists(".toggle-channel-membership-button.-join"));- });-- test("leave", async function (assert) {- this.channel.current_user_membership.set("following", true);- await render(hbs`{{chat-channel-about-view channel=channel}}`);-- assert.ok(exists(".toggle-channel-membership-button.-leave"));- });- }-);--module(- "Discourse Chat | Component | chat-channel-about-view | regular user",- function (hooks) {- setupRenderingTest(hooks);-- hooks.beforeEach(function () {- this.set(- "channel",- fabricators.chatChannel({ chatable_type: "Category" })- );- this.channel.set("description", "foo");- this.currentUser.set("has_chat_enabled", true);- this.siteSettings.chat_enabled = true;- });-- test("escapes channel title", async function (assert) {- this.channel.set("title", "<div class='xss'>evil</div>");-- await render(hbs`{{chat-channel-about-view channel=channel}}`);-- assert.notOk(exists(".xss"));- });-- test("chatable name", async function (assert) {- await render(hbs`{{chat-channel-about-view channel=channel}}`);-- assert.equal(- query(".category-name").innerText,- this.channel.chatable.name- );- });-- test("chatable description", async function (assert) {- await render(hbs`{{chat-channel-about-view channel=channel}}`);-- assert.equal(- query(".category-name").innerText,- this.channel.chatable.name- );-- this.channel.set("description", null);- await settled();-- assert.notOk(exists(".channel-info-about-view__description"));- });-- test("edit title", async function (assert) {- await render(hbs`{{chat-channel-about-view channel=channel}}`);-- assert.notOk(exists(".edit-title-btn"));- });-- test("edit description", async function (assert) {- await render(hbs`{{chat-channel-about-view channel=channel}}`);-- assert.notOk(exists(".edit-description-btn"));- });-- test("join", async function (assert) {- await render(hbs`{{chat-channel-about-view channel=channel}}`);-- assert.ok(exists(".toggle-channel-membership-button.-join"));- });-- test("leave", async function (assert) {- this.channel.current_user_membership.set("following", true);- await render(hbs`{{chat-channel-about-view channel=channel}}`);-- assert.ok(exists(".toggle-channel-membership-button.-leave"));- });- }-);diff --git a/plugins/chat/test/javascripts/components/chat-channel-card-test.js b/plugins/chat/test/javascripts/components/chat-channel-card-test.jsindex 15068e6a4b7..bf6240aef7c 100644--- a/plugins/chat/test/javascripts/components/chat-channel-card-test.js+++ b/plugins/chat/test/javascripts/components/chat-channel-card-test.js@@ -48,8 +48,8 @@ module("Discourse Chat | Component | chat-channel-card", function (hooks) {});test("Muted channel", async function (assert) {- this.channel.current_user_membership.set("muted", true);- this.channel.current_user_membership.set("following", true);+ this.channel.currentUserMembership.muted = true;+ this.channel.currentUserMembership.following = true;await render(hbs`{{chat-channel-card channel=channel}}`);assert.equal(@@ -59,7 +59,7 @@ module("Discourse Chat | Component | chat-channel-card", function (hooks) {});test("Joined channel", async function (assert) {- this.channel.current_user_membership.set("following", true);+ this.channel.currentUserMembership.set("following", true);await render(hbs`{{chat-channel-card channel=channel}}`);assert.equal(@@ -77,7 +77,7 @@ module("Discourse Chat | Component | chat-channel-card", function (hooks) {});test("Memberships count", async function (assert) {- this.channel.set("memberships_count", 4);+ this.channel.set("membershipsCount", 4);await render(hbs`{{chat-channel-card channel=channel}}`);assert.equal(diff --git a/plugins/chat/test/javascripts/components/chat-channel-members-view-test.js b/plugins/chat/test/javascripts/components/chat-channel-members-view-test.jsdeleted file mode 100644index d1953870e11..00000000000--- a/plugins/chat/test/javascripts/components/chat-channel-members-view-test.js+++ /dev/null@@ -1,140 +0,0 @@-import componentTest, {- setupRenderingTest,-} from "discourse/tests/helpers/component-test";-import { exists, query } from "discourse/tests/helpers/qunit-helpers";-import hbs from "htmlbars-inline-precompile";-import fabricators from "../helpers/fabricators";-import I18n from "I18n";-import { Promise } from "rsvp";-import { fillIn, triggerEvent } from "@ember/test-helpers";-import { module } from "qunit";--function fetchMembersHandler(channelId, params = {}) {- if (params.offset === 50) {- return Promise.resolve([{ user: { id: 3, username: "clara" } }]);- }-- if (params.offset === 100) {- return Promise.resolve([]);- }-- if (!params.username) {- return Promise.resolve([- { user: { id: 1, username: "jojo" } },- { user: { id: 2, username: "bob" } },- ]);- }-- if (params.username === "jojo") {- return Promise.resolve([{ user: { id: 1, username: "jojo" } }]);- } else {- return Promise.resolve([]);- }-}--function setupState(context) {- context.set("fetchMembersHandler", fetchMembersHandler);- context.set("channel", fabricators.chatChannel());- context.channel.set("memberships_count", 2);-}--module(- "Discourse Chat | Component | chat-channel-members-view",- function (hooks) {- setupRenderingTest(hooks);-- componentTest("no filter", {- template: hbs`{{chat-channel-members-view channel=channel fetchMembersHandler=fetchMembersHandler}}`,-- beforeEach() {- this.set("fetchMembersHandler", fetchMembersHandler);- this.set("channel", fabricators.chatChannel());- this.channel.set("memberships_count", 2);- },-- async test(assert) {- assert.ok(- exists(".channel-members-view__list-item[data-user-card='jojo']")- );- assert.ok(- exists(".channel-members-view__list-item[data-user-card='bob']")- );- },- });-- componentTest("filter", {- template: hbs`{{chat-channel-members-view channel=channel fetchMembersHandler=fetchMembersHandler}}`,-- beforeEach() {- setupState(this);- },-- async test(assert) {- await fillIn(".channel-members-view__search-input", "jojo");-- assert.ok(- exists(".channel-members-view__list-item[data-user-card='jojo']")- );- assert.notOk(- exists(".channel-members-view__list-item[data-user-card='bob']")- );- },- });-- componentTest("filter with no results", {- template: hbs`{{chat-channel-members-view channel=channel fetchMembersHandler=fetchMembersHandler}}`,-- beforeEach() {- setupState(this);- },-- async test(assert) {- await fillIn(".channel-members-view__search-input", "cat");-- assert.equal(- query(".channel-members-view__list").innerText.trim(),- I18n.t("chat.channel.no_memberships_found")- );-- assert.notOk(- exists(".channel-members-view__list-item[data-user-card='jojo']")- );- assert.notOk(- exists(".channel-members-view__list-item[data-user-card='bob']")- );- },- });-- componentTest("loading more", {- template: hbs`{{chat-channel-members-view channel=channel fetchMembersHandler=fetchMembersHandler}}`,-- beforeEach() {- this.set("fetchMembersHandler", fetchMembersHandler);- this.set("channel", fabricators.chatChannel());- this.channel.set("memberships_count", 3);- },-- async test(assert) {- await triggerEvent(".channel-members-view__list", "scroll");-- ["jojo", "bob", "clara"].forEach((username) => {- assert.ok(- exists(- `.channel-members-view__list-item[data-user-card='${username}']`- )- );- });-- await triggerEvent(".channel-members-view__list", "scroll");-- ["jojo", "bob", "clara"].forEach((username) => {- assert.ok(- exists(- `.channel-members-view__list-item[data-user-card='${username}']`- )- );- });- },- });- }-);diff --git a/plugins/chat/test/javascripts/components/chat-channel-metadata-test.js b/plugins/chat/test/javascripts/components/chat-channel-metadata-test.jsindex 285e10416f4..c8c78830a42 100644--- a/plugins/chat/test/javascripts/components/chat-channel-metadata-test.js+++ b/plugins/chat/test/javascripts/components/chat-channel-metadata-test.js@@ -28,9 +28,8 @@ module("Discourse Chat | Component | chat-channel-metadata", function (hooks) {test("unreadIndicator", async function (assert) {this.channel = fabricators.directMessageChatChannel();- this.currentUser.set("chat_channel_tracking_state", {- [this.channel.id]: { unread_count: 1 },- });+ this.channel.currentUserMembership.unread_count = 1;+this.unreadIndicator = true;await render(hbs`<ChatChannelMetadata @channel={{this.channel}} @unreadIndicator={{this.unreadIndicator}}/>`diff --git a/plugins/chat/test/javascripts/components/chat-channel-row-test.js b/plugins/chat/test/javascripts/components/chat-channel-row-test.jsindex 4310e5eca17..357c6c7366f 100644--- a/plugins/chat/test/javascripts/components/chat-channel-row-test.js+++ b/plugins/chat/test/javascripts/components/chat-channel-row-test.js@@ -60,7 +60,7 @@ module("Discourse Chat | Component | chat-channel-row", function (hooks) {assert.dom(".toggle-channel-membership-button").doesNotExist();- this.categoryChatChannel.current_user_membership.following = true;+ this.categoryChatChannel.currentUserMembership.following = true;await render(hbs`<ChatChannelRow @channel={{this.categoryChatChannel}} />`);@@ -92,7 +92,7 @@ module("Discourse Chat | Component | chat-channel-row", function (hooks) {assert.dom(".chat-channel-row").doesNotHaveClass("muted");- this.categoryChatChannel.current_user_membership.muted = true;+ this.categoryChatChannel.currentUserMembership.muted = true;await render(hbs`<ChatChannelRow @channel={{this.categoryChatChannel}} />`);@@ -130,11 +130,7 @@ module("Discourse Chat | Component | chat-channel-row", function (hooks) {assert.dom(".chat-channel-row").doesNotHaveClass("has-unread");- this.owner- .lookup("service:current-user")- .set("chat_channel_tracking_state", {- [this.categoryChatChannel.id]: { unread_count: 1 },- });+ this.categoryChatChannel.currentUserMembership.unread_count = 1;await render(hbs`<ChatChannelRow @channel={{this.categoryChatChannel}} />`);diff --git a/plugins/chat/test/javascripts/components/chat-channel-settings-view-test.js b/plugins/chat/test/javascripts/components/chat-channel-settings-view-test.jsdeleted file mode 100644index ef4fd1c4e7b..00000000000--- a/plugins/chat/test/javascripts/components/chat-channel-settings-view-test.js+++ /dev/null@@ -1,290 +0,0 @@-import componentTest, {- setupRenderingTest,-} from "discourse/tests/helpers/component-test";-import hbs from "htmlbars-inline-precompile";-import fabricators from "../helpers/fabricators";-import selectKit from "discourse/tests/helpers/select-kit-helper";-import pretender from "discourse/tests/helpers/create-pretender";-import { CHATABLE_TYPES } from "discourse/plugins/chat/discourse/models/chat-channel";-import { module } from "qunit";--function membershipFixture(id, options = {}) {- options = Object.assign(- {},- {- muted: false,- following: true,- },- options- );-- return {- following: options.following,- muted: options.muted,- desktop_notification_level: "mention",- mobile_notification_level: "mention",- chat_channel_id: id,- chatable_type: "Category",- user_count: 2,- };-}--module(- "Discourse Chat | Component | chat-channel-settings-view | Public channel - regular user",- function (hooks) {- setupRenderingTest(hooks);-- componentTest("saving desktop notifications", {- template: hbs`{{chat-channel-settings-view channel=channel}}`,-- beforeEach() {- this.set("channel", fabricators.chatChannel());- },-- async test(assert) {- pretender.put(- `/chat/api/chat_channels/${this.channel.id}/notifications_settings.json`,- () => {- return [- 200,- { "Content-Type": "application/json" },- membershipFixture(this.channel.id),- ];- }- );-- const sk = selectKit(- ".channel-settings-view__desktop-notification-level-selector"- );- await sk.expand();- await sk.selectRowByValue("mention");-- assert.equal(sk.header().value(), "mention");- },- });-- componentTest("saving mobile notifications", {- template: hbs`{{chat-channel-settings-view channel=channel}}`,-- beforeEach() {- this.set("channel", fabricators.chatChannel());- },-- async test(assert) {- pretender.put(- `/chat/api/chat_channels/${this.channel.id}/notifications_settings.json`,- () => {- return [- 200,- { "Content-Type": "application/json" },- membershipFixture(this.channel.id),- ];- }- );-- const sk = selectKit(- ".channel-settings-view__mobile-notification-level-selector"- );- await sk.expand();- await sk.selectRowByValue("mention");-- assert.equal(sk.header().value(), "mention");- },- });-- componentTest("muted", {- template: hbs`{{chat-channel-settings-view channel=channel}}`,-- beforeEach() {- this.set("channel", fabricators.chatChannel());- },-- async test(assert) {- pretender.put(- `/chat/api/chat_channels/${this.channel.id}/notifications_settings.json`,- () => {- return [- 200,- { "Content-Type": "application/json" },- membershipFixture(this.channel.id, { muted: false }),- ];- }- );-- const sk = selectKit(".channel-settings-view__muted-selector");- await sk.expand();- await sk.selectRowByName("Off");-- assert.equal(sk.header().value(), "false");- },- });-- componentTest("hide channel wide mentions", {- template: hbs`{{chat-channel-settings-view channel=channel}}`,-- beforeEach() {- this.set("channel", fabricators.chatChannel());- },-- async test(assert) {- assert- .dom(".channel-settings-view__channel-wide-mentions-selector")- .doesNotExist();- },- });-- componentTest("hide channel auto join", {- template: hbs`{{chat-channel-settings-view channel=channel}}`,-- beforeEach() {- this.set("channel", fabricators.chatChannel());- },-- async test(assert) {- assert.dom(".channel-settings-view__auto-join-selector").doesNotExist();- },- });- }-);--module(- "Discourse Chat | Component | chat-channel-settings-view | Direct Message channel - regular user",- function (hooks) {- setupRenderingTest(hooks);-- componentTest("saving desktop notifications", {- template: hbs`{{chat-channel-settings-view channel=channel}}`,-- beforeEach() {- this.set(- "channel",- fabricators.chatChannel({- chatable_type: CHATABLE_TYPES.directMessageChannel,- })- );- },-- async test(assert) {- pretender.put(- `/chat/api/chat_channels/${this.channel.id}/notifications_settings.json`,- () => {- return [- 200,- { "Content-Type": "application/json" },- membershipFixture(this.channel.id),- ];- }- );-- const sk = selectKit(- ".channel-settings-view__desktop-notification-level-selector"- );- await sk.expand();- await sk.selectRowByValue("mention");-- assert.equal(sk.header().value(), "mention");- },- });-- componentTest("saving mobile notifications", {- template: hbs`{{chat-channel-settings-view channel=channel}}`,-- beforeEach() {- this.set(- "channel",- fabricators.chatChannel({- chatable_type: CHATABLE_TYPES.directMessageChannel,- })- );- },- async test(assert) {- pretender.put(- `/chat/api/chat_channels/${this.channel.id}/notifications_settings.json`,- () => {- return [- 200,- { "Content-Type": "application/json" },- membershipFixture(this.channel.id),- ];- }- );-- const sk = selectKit(- ".channel-settings-view__mobile-notification-level-selector"- );- await sk.expand();- await sk.selectRowByValue("mention");-- assert.equal(sk.header().value(), "mention");- },- });-- componentTest("muted", {- template: hbs`{{chat-channel-settings-view channel=channel}}`,-- beforeEach() {- this.set(- "channel",- fabricators.chatChannel({- chatable_type: CHATABLE_TYPES.directMessageChannel,- })- );- },-- async test(assert) {- pretender.put(- `/chat/api/chat_channels/${this.channel.id}/notifications_settings.json`,- () => {- return [- 200,- { "Content-Type": "application/json" },- membershipFixture(this.channel.id, { muted: false }),- ];- }- );-- const sk = selectKit(".channel-settings-view__muted-selector");- await sk.expand();- await sk.selectRowByName("Off");-- assert.equal(sk.header().value(), "false");- },- });-- componentTest("hide channel wide mentions", {- template: hbs`{{chat-channel-settings-view channel=channel}}`,-- beforeEach() {- this.set(- "channel",- fabricators.chatChannel({- chatable_type: CHATABLE_TYPES.directMessageChannel,- })- );- },-- async test(assert) {- assert- .dom(".channel-settings-view__channel-wide-mentions-selector")- .doesNotExist();- },- });-- componentTest("hide channel auto join", {- template: hbs`{{chat-channel-settings-view channel=channel}}`,-- beforeEach() {- this.set(- "channel",- fabricators.chatChannel({- chatable_type: CHATABLE_TYPES.directMessageChannel,- })- );- },-- async test(assert) {- assert.dom(".channel-settings-view__auto-join-selector").doesNotExist();- },- });- }-);diff --git a/plugins/chat/test/javascripts/components/chat-channel-toggle-view-test.js b/plugins/chat/test/javascripts/components/chat-channel-toggle-view-test.jsdeleted file mode 100644index 426e0b3d180..00000000000--- a/plugins/chat/test/javascripts/components/chat-channel-toggle-view-test.js+++ /dev/null@@ -1,104 +0,0 @@-import componentTest, {- setupRenderingTest,-} from "discourse/tests/helpers/component-test";-import { query } from "discourse/tests/helpers/qunit-helpers";-import { click } from "@ember/test-helpers";-import hbs from "htmlbars-inline-precompile";-import fabricators from "../helpers/fabricators";-import I18n from "I18n";-import pretender from "discourse/tests/helpers/create-pretender";-import { module } from "qunit";--module(- "Discourse Chat | Component | chat-channel-toggle-view | closed channel",- function (hooks) {- setupRenderingTest(hooks);-- componentTest("texts", {- template: hbs`{{chat-channel-toggle-view channel=channel}}`,-- beforeEach() {- this.set("channel", fabricators.chatChannel({ status: "closed" }));- },-- async test(assert) {- assert.equal(- query("#chat-channel-toggle").innerText.trim(),- I18n.t("chat.channel_open.instructions")- );- assert.equal(- query("#chat-channel-toggle-btn").innerText.trim(),- I18n.t("chat.channel_settings.open_channel")- );- },- });-- componentTest("action", {- template: hbs`{{chat-channel-toggle-view channel=channel}}`,-- beforeEach() {- this.set("channel", fabricators.chatChannel({ status: "closed" }));- },-- async test(assert) {- pretender.put(- `/chat/chat_channels/${this.channel.id}/change_status.json`,- () => {- return [200, { "Content-Type": "application/json" }, {}];- }- );-- await click("#chat-channel-toggle-btn");-- assert.equal(this.channel.isClosed, false);- },- });- }-);--module(- "Discourse Chat | Component | chat-channel-toggle-view | opened channel",- function (hooks) {- setupRenderingTest(hooks);-- componentTest("texts", {- template: hbs`{{chat-channel-toggle-view channel=channel}}`,-- beforeEach() {- this.set("channel", fabricators.chatChannel({ status: "open" }));- },-- async test(assert) {- assert.equal(- query("#chat-channel-toggle").innerText.trim(),- I18n.t("chat.channel_close.instructions")- );- assert.equal(- query("#chat-channel-toggle-btn").innerText.trim(),- I18n.t("chat.channel_settings.close_channel")- );- },- });-- componentTest("action", {- template: hbs`{{chat-channel-toggle-view channel=channel}}`,-- beforeEach() {- this.set("channel", fabricators.chatChannel({ status: "open" }));- },-- async test(assert) {- pretender.put(- `/chat/chat_channels/${this.channel.id}/change_status.json`,- () => {- return [200, { "Content-Type": "application/json" }, {}];- }- );-- await click("#chat-channel-toggle-btn");-- assert.equal(this.channel.isClosed, true);- },- });- }-);diff --git a/plugins/chat/test/javascripts/components/chat-channel-unread-indicator-test.js b/plugins/chat/test/javascripts/components/chat-channel-unread-indicator-test.jsdeleted file mode 100644index 718757683c4..00000000000--- a/plugins/chat/test/javascripts/components/chat-channel-unread-indicator-test.js+++ /dev/null@@ -1,91 +0,0 @@-import { set } from "@ember/object";-import componentTest, {- setupRenderingTest,-} from "discourse/tests/helpers/component-test";-import { exists } from "discourse/tests/helpers/qunit-helpers";-import hbs from "htmlbars-inline-precompile";-import { CHATABLE_TYPES } from "discourse/plugins/chat/discourse/models/chat-channel";-import { module } from "qunit";--const directMessageChannel = {- id: 1,- chatable_type: CHATABLE_TYPES.directMessageChannel,- chatable: {- users: [{ id: 1 }],- },-};--const topicChannel = {- id: 2,- chatable_type: CHATABLE_TYPES.topicChannel,- chatable: {- users: [{ id: 1 }],- },-};--module(- "Discourse Chat | Component | chat-channel-unread-indicator",- function (hooks) {- setupRenderingTest(hooks);-- componentTest("has no unread", {- template: hbs`{{chat-channel-unread-indicator channel=channel}}`,-- beforeEach() {- set(this.currentUser, "chat_channel_tracking_state", {- unread_count: 0,- });- this.set("channel", topicChannel);- },-- async test(assert) {- assert.notOk(exists(".chat-channel-unread-indicator"));- },- });-- componentTest("has unread and no mentions", {- template: hbs`{{chat-channel-unread-indicator channel=channel}}`,-- beforeEach() {- set(this.currentUser, "chat_channel_tracking_state", {- [topicChannel.id]: { unread_count: 1 },- });- this.set("channel", topicChannel);- },-- async test(assert) {- assert.ok(exists(".chat-channel-unread-indicator:not(.urgent)"));- },- });-- componentTest("has unread and mentions", {- template: hbs`{{chat-channel-unread-indicator channel=channel}}`,-- beforeEach() {- set(this.currentUser, "chat_channel_tracking_state", {- [topicChannel.id]: { unread_count: 1, unread_mentions: 1 },- });- this.set("channel", topicChannel);- },-- async test(assert) {- assert.ok(exists(".chat-channel-unread-indicator.urgent"));- },- });-- componentTest("direct message channel | has unread", {- template: hbs`{{chat-channel-unread-indicator channel=channel}}`,-- beforeEach() {- set(this.currentUser, "chat_channel_tracking_state", {- [directMessageChannel.id]: { unread_count: 1 },- });- this.set("channel", directMessageChannel);- },-- async test(assert) {- assert.ok(exists(".chat-channel-unread-indicator.urgent"));- },- });- }-);diff --git a/plugins/chat/test/javascripts/components/sidebar-channels-test.js b/plugins/chat/test/javascripts/components/sidebar-channels-test.jsdeleted file mode 100644index 52b4ee61f95..00000000000--- a/plugins/chat/test/javascripts/components/sidebar-channels-test.js+++ /dev/null@@ -1,78 +0,0 @@-import componentTest, {- setupRenderingTest,-} from "discourse/tests/helpers/component-test";-import hbs from "htmlbars-inline-precompile";-import { exists } from "discourse/tests/helpers/qunit-helpers";-import {- setup as setupChatStub,- teardown as teardownChatStub,-} from "../helpers/chat-stub";-import { module } from "qunit";--module("Discourse Chat | Component | sidebar-channels", function (hooks) {- setupRenderingTest(hooks);-- componentTest("default", {- template: hbs`{{sidebar-channels}}`,-- beforeEach() {- setupChatStub(this);- },-- afterEach() {- teardownChatStub();- },-- async test(assert) {- assert.ok(exists("[data-chat-channel-id]"));- },- });-- componentTest("chat is on chat page", {- template: hbs`{{sidebar-channels}}`,-- beforeEach() {- setupChatStub(this, {});- },-- afterEach() {- teardownChatStub();- },-- async test(assert) {- assert.ok(exists("[data-chat-channel-id]"));- },- });-- componentTest("none of the conditions are fulfilled", {- template: hbs`{{sidebar-channels}}`,-- beforeEach() {- setupChatStub(this, { userCanChat: false });- },-- afterEach() {- teardownChatStub();- },-- async test(assert) {- assert.notOk(exists("[data-chat-channel-id]"));- },- });-- componentTest("user cant chat", {- template: hbs`{{sidebar-channels}}`,-- beforeEach() {- setupChatStub(this, { userCanChat: false });- },-- afterEach() {- teardownChatStub();- },-- async test(assert) {- assert.notOk(exists("[data-chat-channel-id]"));- },- });-});diff --git a/plugins/chat/test/javascripts/helpers/chat-pretenders.js b/plugins/chat/test/javascripts/helpers/chat-pretenders.jsindex 98a71f824f8..a72c917f7d4 100644--- a/plugins/chat/test/javascripts/helpers/chat-pretenders.js+++ b/plugins/chat/test/javascripts/helpers/chat-pretenders.js@@ -138,8 +138,8 @@ export function directMessageChannelPretender(opts = { unread_count: 0, muted: false }) {let copy = cloneJSON(directMessageChannels[0]);- copy.chat_channel.current_user_membership.unread_count = opts.unread_count;- copy.chat_channel.current_user_membership.muted = opts.muted;+ copy.chat_channel.currentUserMembership.unread_count = opts.unread_count;+ copy.chat_channel.currentUserMembership.muted = opts.muted;server.get("/chat/chat_channels/75.json", () => helper.response(copy));}@@ -150,14 +150,14 @@ export function chatChannelPretender(server, helper, changes = []) {let found;found = copy.public_channels.find((c) => c.id === change.id);if (found) {- found.current_user_membership.unread_count = change.unread_count;- found.current_user_membership.muted = change.muted;+ found.currentUserMembership.unread_count = change.unread_count;+ found.currentUserMembership.muted = change.muted;}if (!found) {found = copy.direct_message_channels.find((c) => c.id === change.id);if (found) {- found.current_user_membership.unread_count = change.unread_count;- found.current_user_membership.muted = change.muted;+ found.currentUserMembership.unread_count = change.unread_count;+ found.currentUserMembership.muted = change.muted;}}});diff --git a/plugins/chat/test/javascripts/helpers/chat-stub.js b/plugins/chat/test/javascripts/helpers/chat-stub.jsdeleted file mode 100644index ad2f8df2c35..00000000000--- a/plugins/chat/test/javascripts/helpers/chat-stub.js+++ /dev/null@@ -1,26 +0,0 @@-import fabricators from "../helpers/fabricators";-import { isPresent } from "@ember/utils";-import Service from "@ember/service";--let publicChannels;-let userCanChat;--class ChatStub extends Service {- userCanChat = userCanChat;- publicChannels = publicChannels;-}--export function setup(context, options = {}) {- context.registry.register("service:chat-stub", ChatStub);- context.registry.injection("component", "chat", "service:chat-stub");-- publicChannels = isPresent(options.publicChannels)- ? options.publicChannels- : [fabricators.chatChannel()];- userCanChat = isPresent(options.userCanChat) ? options.userCanChat : true;-}--export function teardown() {- publicChannels = [];- userCanChat = true;-}diff --git a/plugins/chat/test/javascripts/unit/services/chat-test.js b/plugins/chat/test/javascripts/unit/services/chat-test.jsdeleted file mode 100644index 9aa59b49b4e..00000000000--- a/plugins/chat/test/javascripts/unit/services/chat-test.js+++ /dev/null@@ -1,296 +0,0 @@-import MockPresenceChannel from "../../helpers/mock-presence-channel";-import {- acceptance,- publishToMessageBus,-} from "discourse/tests/helpers/qunit-helpers";-import { test } from "qunit";-import fabricators from "../../helpers/fabricators";-import { directMessageChannels } from "discourse/plugins/chat/chat-fixtures";-import { cloneJSON } from "discourse-common/lib/object";-import ChatChannel from "discourse/plugins/chat/discourse/models/chat-channel";-import sinon from "sinon";-import pretender from "discourse/tests/helpers/create-pretender";-import { settled } from "@ember/test-helpers";--acceptance("Discourse Chat | Unit | Service | chat", function (needs) {- needs.hooks.beforeEach(function () {- Object.defineProperty(this, "chatService", {- get: () => this.container.lookup("service:chat"),- });- Object.defineProperty(this, "currentUser", {- get: () => this.container.lookup("service:current-user"),- });- });-- needs.user({ ignored_users: [] });-- needs.pretender((server, helper) => {- server.get("/chat/chat_channels.json", () => {- return helper.response({- public_channels: [- {- id: 1,- title: "something",- chatable_type: "Category",- last_message_sent_at: "2021-11-08T21:26:05.710Z",- current_user_membership: {- unread_count: 2,- last_read_message_id: 123,- unread_mentions: 0,- muted: false,- },- message_bus_last_ids: {- new_mentions: 0,- new_messages: 0,- },- },- ],- direct_message_channels: [],- message_bus_last_ids: {- channel_metadata: 0,- channel_edits: 0,- channel_status: 0,- new_channel: 0,- user_tracking_state: 0,- },- });- });-- server.put("/chat/:chatChannelId/read/:messageId.json", () => {- return helper.response({ success: "OK" });- });- });-- function setupMockPresenceChannel(chatService) {- chatService.set(- "presenceChannel",- MockPresenceChannel.create({- name: `/chat-reply/1`,- })- );- }-- test("#markNetworkAsReliable", async function (assert) {- setupMockPresenceChannel(this.chatService);-- this.chatService.markNetworkAsReliable();-- assert.strictEqual(this.chatService.isNetworkUnreliable, false);- });-- test("#markNetworkAsUnreliable", async function (assert) {- setupMockPresenceChannel(this.chatService);- this.chatService.markNetworkAsUnreliable();-- assert.strictEqual(this.chatService.isNetworkUnreliable, true);-- await settled();-- assert.strictEqual(- this.chatService.isNetworkUnreliable,- false,- "it resets state after a delay"- );- });-- test("#startTrackingChannel - sorts dm channels", async function (assert) {- setupMockPresenceChannel(this.chatService);- const fixtures = cloneJSON(directMessageChannels).mapBy("chat_channel");- const channel1 = ChatChannel.create(fixtures[0]);- const channel2 = ChatChannel.create(fixtures[1]);- await this.chatService.startTrackingChannel(channel1);- this.currentUser.set(- `chat_channel_tracking_state.${channel1.id}.unread_count`,- 0- );- await this.chatService.startTrackingChannel(channel2);-- assert.strictEqual(- this.chatService.directMessageChannels.firstObject.title,- channel2.title- );- });-- test("#refreshTrackingState", async function (assert) {- this.currentUser.set("chat_channel_tracking_state", {});-- await this.chatService.refreshTrackingState();-- assert.equal(- this.currentUser.chat_channel_tracking_state[1].unread_count,- 2- );- });-- test("attempts to track a non followed channel", async function (assert) {- this.currentUser.set("chat_channel_tracking_state", {});- const channel = fabricators.chatChannel();- await this.chatService.startTrackingChannel(channel);-- assert.false(channel.current_user_membership.following);- assert.notOk(- this.currentUser.chat_channel_tracking_state[channel.id],- "it doesn’t track it"- );- });-- test("new message", async function (assert) {- setupMockPresenceChannel(this.chatService);- await this.chatService.forceRefreshChannels();-- await publishToMessageBus("/chat/1/new-messages", {- user_id: this.currentUser.id,- username: this.currentUser.username,- message_id: 124,- });-- assert.equal(- this.currentUser.chat_channel_tracking_state[1].chat_message_id,- 124,- "updates tracking state last message id to the message id sent by current user"- );- assert.equal(- this.currentUser.chat_channel_tracking_state[1].unread_count,- 2,- "does not increment unread count"- );- });-- test("/chat/:channelId/new-messages - message from current user", async function (assert) {- setupMockPresenceChannel(this.chatService);- await this.chatService.forceRefreshChannels();-- await publishToMessageBus("/chat/1/new-messages", {- user_id: this.currentUser.id,- username: this.currentUser.username,- message_id: 124,- });-- assert.equal(- this.currentUser.chat_channel_tracking_state[1].chat_message_id,- 124,- "updates tracking state last message id to the message id sent by current user"- );- assert.equal(- this.currentUser.chat_channel_tracking_state[1].unread_count,- 2,- "does not increment unread count"- );- });-- test("/chat/:channelId/new-messages - message from user that current user is ignoring", async function (assert) {- this.currentUser.set("ignored_users", ["johnny"]);- setupMockPresenceChannel(this.chatService);- await this.chatService.forceRefreshChannels();-- await publishToMessageBus("/chat/1/new-messages", {- user_id: 2327,- username: "johnny",- message_id: 124,- });-- assert.equal(- this.currentUser.chat_channel_tracking_state[1].chat_message_id,- 124,- "updates tracking state last message id to the message id sent by johnny"- );- assert.equal(- this.currentUser.chat_channel_tracking_state[1].unread_count,- 2,- "does not increment unread count"- );- });-- test("/chat/:channelId/new-messages - message from another user", async function (assert) {- setupMockPresenceChannel(this.chatService);- await this.chatService.forceRefreshChannels();-- await publishToMessageBus("/chat/1/new-messages", {- user_id: 2327,- username: "jane",- message_id: 124,- });-- assert.equal(- this.currentUser.chat_channel_tracking_state[1].chat_message_id,- 123,- "does not update tracking state last message id to the message id sent by jane"- );- assert.equal(- this.currentUser.chat_channel_tracking_state[1].unread_count,- 3,- "does increment unread count"- );- });-- test("#updateLastReadMessage - updates and tracks the last read message", async function (assert) {- this.currentUser.set("chat_channel_tracking_state", {});- sinon.stub(document, "querySelectorAll").callsFake(function () {- return [{ dataset: { id: 2 } }];- });- const activeChannel = fabricators.chatChannel({- current_user_membership: { last_read_message_id: 1, following: true },- });- this.chatService.setActiveChannel(activeChannel);-- this.chatService.updateLastReadMessage();- await settled();-- assert.equal(activeChannel.lastSendReadMessageId, 2);- });-- test("#updateLastReadMessage - does nothing if the user doesn't follow the channel", async function (assert) {- this.currentUser.set("chat_channel_tracking_state", {});- this.chatService.setActiveChannel(- fabricators.chatChannel({ current_user_membership: { following: false } })- );- sinon.stub(document, "querySelectorAll").callsFake(function () {- return [{ dataset: { id: 1 } }];- });-- this.chatService.updateLastReadMessage();- await settled();-- assert.equal(this.chatService.activeChannel.lastSendReadMessageId, null);- });-- test("#updateLastReadMessage - does nothing if the user already read the message", async function (assert) {- this.currentUser.set("chat_channel_tracking_state", {});- sinon.stub(document, "querySelectorAll").callsFake(function () {- return [{ dataset: { id: 1 } }];- });- const activeChannel = fabricators.chatChannel({- current_user_membership: { last_read_message_id: 2, following: true },- });- this.chatService.setActiveChannel(activeChannel);-- this.chatService.updateLastReadMessage();- await settled();-- assert.equal(activeChannel.lastSendReadMessageId, 2);- });-});--acceptance(- "Discourse Chat | Unit | Service | chat - no current user",- function (needs) {- needs.hooks.beforeEach(function () {- Object.defineProperty(this, "chatService", {- get: () => this.container.lookup("service:chat"),- });- });-- test("#refreshTrackingState", async function (assert) {- pretender.get(`/chat/chat_channels.json`, () => {- assert.step("unexpected");- return [200, { "Content-Type": "application/json" }, {}];- });-- assert.step("start");- await this.chatService.refreshTrackingState();- assert.step("end");-- assert.verifySteps(["start", "end"], "it does no requests");- });- }-);