A platform for community discussion. Free, open, simple.
UX: improve livestream chat messaging (#41750)
Krisdd2c5ba0f869
diff --git a/app/models/topic.rb b/app/models/topic.rbindex 2fab9ee7264..30ebb2981bf 100644--- a/app/models/topic.rb+++ b/app/models/topic.rb@@ -593,6 +593,12 @@ class Topic < ActiveRecord::Basefancy_title.length > Topic.max_fancy_title_length ? escaped : fancy_titleend+ # Used when interpolating a topic title into a Markdown link label, where+ # unescaped brackets or parentheses could change the resulting link.+ def markdown_link_title+ title.gsub(/([\\\[\]()])/) { "\\#{$1}" }+ end+def fancy_titlereturn ERB::Util.html_escape(title) unless SiteSetting.title_fancy_entities?diff --git a/db/structure.sql b/db/structure.sqlindex 2527876e2ae..53926dbfac7 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -6560,7 +6560,8 @@ CREATE TABLE public.livestream_topic_chat_channels (topic_id bigint NOT NULL,chat_channel_id bigint NOT NULL,created_at timestamp(6) without time zone NOT NULL,- updated_at timestamp(6) without time zone NOT NULL+ updated_at timestamp(6) without time zone NOT NULL,+ reference_message_id bigint);@@ -22700,6 +22701,7 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groupsSET search_path TO "$user", public;INSERT INTO "schema_migrations" (version) VALUES+('20260715202231'),('20260715183411'),('20260715134306'),('20260715090434'),diff --git a/plugins/chat/app/controllers/chat/api/channels_controller.rb b/plugins/chat/app/controllers/chat/api/channels_controller.rbindex f6d0ef12c91..dac5dc2f126 100644--- a/plugins/chat/app/controllers/chat/api/channels_controller.rb+++ b/plugins/chat/app/controllers/chat/api/channels_controller.rb@@ -30,12 +30,15 @@ class Chat::Api::ChannelsController < Chat::ApiControllermemberships = current_user ? Chat::ChannelMembershipManager.all_for_user(current_user) : []channels = Chat::ChannelFetcher.secured_public_channels(guardian, options)+ shared_channel_serializer_options =+ DiscoursePluginRegistry.apply_modifier(:chat_channel_serializer_public_options, {}, guardian)serialized_channels =channels.map do |channel|Chat::ChannelSerializer.new(channel,- scope: Guardian.new(current_user),+ scope: guardian,membership: memberships.find { |membership| membership.chat_channel_id == channel.id },+ **shared_channel_serializer_options,)enddiff --git a/plugins/chat/app/serializers/chat/structured_channel_serializer.rb b/plugins/chat/app/serializers/chat/structured_channel_serializer.rbindex 188f28dd486..fa27a25e5d5 100644--- a/plugins/chat/app/serializers/chat/structured_channel_serializer.rb+++ b/plugins/chat/app/serializers/chat/structured_channel_serializer.rb@@ -22,6 +22,9 @@ module Chatenddef public_channels+ shared_channel_serializer_options =+ DiscoursePluginRegistry.apply_modifier(:chat_channel_serializer_public_options, {}, scope)+object[:public_channels].map do |channel|message_bus_last_ids = {channel_message_bus_last_id:@@ -43,8 +46,7 @@ module Chat)end- Chat::ChannelSerializer.new(- channel,+ channel_serializer_options = {root: nil,scope: scope,membership: channel_membership(channel.id),@@ -55,7 +57,9 @@ module Chat# the login/signup flow before attempting to join.can_join_chat_channel: true,post_allowed_category_ids: @options[:post_allowed_category_ids],- )+ }.merge(shared_channel_serializer_options)++ Chat::ChannelSerializer.new(channel, channel_serializer_options)endenddiff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-card.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-card.gjsindex 1f0ba20d5ce..880eb1963c1 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-card.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-card.gjs@@ -1,6 +1,8 @@import { concat, hash } from "@ember/helper";import { LinkTo } from "@ember/routing";import { trustHTML } from "@ember/template";+import PluginOutlet from "discourse/components/plugin-outlet";+import lazyHash from "discourse/helpers/lazy-hash";import { gt } from "discourse/truth-helpers";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dEmoji from "discourse/ui-kit/helpers/d-emoji";@@ -48,24 +50,30 @@ export default <template></div><div class="chat-channel-card__cta">- {{#if @channel.isFollowing}}- <ToggleChannelMembershipButton- @channel={{@channel}}- @options={{hash- leaveClass="btn-transparent --danger chat-channel-card__leave-btn"- labelType="short"- }}- />+ <PluginOutlet+ @name="chat-channel-card-cta"+ @outletArgs={{lazyHash channel=@channel}}+ @defaultGlimmer={{true}}+ >+ {{#if @channel.isFollowing}}+ <ToggleChannelMembershipButton+ @channel={{@channel}}+ @options={{hash+ leaveClass="btn-transparent --danger chat-channel-card__leave-btn"+ labelType="short"+ }}+ />- {{else if @channel.isJoinable}}- <ToggleChannelMembershipButton- @channel={{@channel}}- @options={{hash- joinClass="btn-primary btn-small chat-channel-card__join-btn"- labelType="short"- }}- />- {{/if}}+ {{else if @channel.isJoinable}}+ <ToggleChannelMembershipButton+ @channel={{@channel}}+ @options={{hash+ joinClass="btn-primary btn-small chat-channel-card__join-btn"+ labelType="short"+ }}+ />+ {{/if}}+ </PluginOutlet></div>{{#if (gt @channel.membershipsCount 0)}}diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel-preview-card.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel-preview-card.gjsindex 813f631c5f5..e93edce43a8 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel-preview-card.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel-preview-card.gjs@@ -3,6 +3,8 @@ import { hash } from "@ember/helper";import { action } from "@ember/object";import { getOwner } from "@ember/owner";import { service } from "@ember/service";+import PluginOutlet from "discourse/components/plugin-outlet";+import lazyHash from "discourse/helpers/lazy-hash";import DButton from "discourse/ui-kit/d-button";import dIcon from "discourse/ui-kit/helpers/d-icon";import { i18n } from "discourse-i18n";@@ -41,24 +43,30 @@ export default class ChatChannelPreviewCard extends Component {{{#if this.currentUser}}{{#if this.showJoinButton}}<div class="chat-channel-preview-card --logged-in">- <div class="chat-channel-preview-card__icon">- {{dIcon "lock"}}- </div>+ <PluginOutlet+ @name="chat-channel-preview-card-content"+ @outletArgs={{lazyHash channel=@channel context=@context}}+ @defaultGlimmer={{true}}+ >+ <div class="chat-channel-preview-card__icon">+ {{dIcon "lock"}}+ </div>- <div class="chat-channel-preview-card__title">- {{this.guestTitle}}- </div>+ <div class="chat-channel-preview-card__title">+ {{this.guestTitle}}+ </div>- <div class="chat-channel-preview-card__body">- {{i18n "chat.channel.preview_card.join_body"}}- </div>+ <div class="chat-channel-preview-card__body">+ {{i18n "chat.channel.preview_card.join_body"}}+ </div>- <div class="chat-channel-preview-card__actions">- <ToggleChannelMembershipButton- @channel={{@channel}}- @options={{hash joinClass="btn-primary" labelType="short"}}- />- </div>+ <div class="chat-channel-preview-card__actions">+ <ToggleChannelMembershipButton+ @channel={{@channel}}+ @options={{hash joinClass="btn-primary" labelType="short"}}+ />+ </div>+ </PluginOutlet></div>{{else}}<div class="chat-channel-preview-card --logged-in --no-access">diff --git a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjsindex 86de3008dbb..3803bcca597 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat-channel.gjs@@ -350,6 +350,13 @@ export default class ChatChannel extends Component {const messages = [];let foundFirstNew = false;+ const hiddenMessageIds = new Set(+ (this.args.hiddenMessageIds ?? []).map(Number)+ );+ const messagesData = (result?.messages ?? []).filter(+ (messageData) => !hiddenMessageIds.has(messageData.id)+ );+// Only compute the newest message marker on a full load.// In an already loaded list we need to preserve the "last visit" line.const hasNewest = this.messagesManager.messages.some(@@ -359,7 +366,7 @@ export default class ChatChannel extends Component {channel.newestMessage = null;}- result?.messages?.forEach((messageData, index) => {+ messagesData.forEach((messageData, index) => {messageData.firstOfResults = index === 0;if (this.currentUser?.ignored_users) {@@ -828,7 +835,7 @@ export default class ChatChannel extends Component {/>{{else}}{{#if (and (not @channel.isFollowing) @channel.isCategoryChannel)}}- <ChatChannelPreviewCard @channel={{@channel}} />+ <ChatChannelPreviewCard @channel={{@channel}} @context={{@context}} />{{else}}<ChatComposerChannel@channel={{@channel}}diff --git a/plugins/chat/assets/javascripts/discourse/models/chat-channel.js b/plugins/chat/assets/javascripts/discourse/models/chat-channel.jsindex 942504473c1..f0873cc7f0f 100644--- a/plugins/chat/assets/javascripts/discourse/models/chat-channel.js+++ b/plugins/chat/assets/javascripts/discourse/models/chat-channel.js@@ -100,6 +100,7 @@ export default class ChatChannel {this.currentUserMembership = args.current_user_membership;this.lastMessage = args.last_message;this.meta = args.meta;+ this.livestreamTopic = args.livestream_topic;this.chatable = this.#initChatable(args.chatable ?? []);this.tracking = new ChatTrackingState(getOwnerWithFallback(this));diff --git a/plugins/chat/assets/stylesheets/common/chat-channel-preview-card.scss b/plugins/chat/assets/stylesheets/common/chat-channel-preview-card.scssindex ae947e28048..29f44388788 100644--- a/plugins/chat/assets/stylesheets/common/chat-channel-preview-card.scss+++ b/plugins/chat/assets/stylesheets/common/chat-channel-preview-card.scss@@ -1,5 +1,3 @@-@use "lib/viewport";-.chat-channel-preview-card {display: grid;grid-template-columns: auto 1fr auto;@@ -27,7 +25,7 @@"body body";}- @include viewport.from(sm) {+ @container (width >= 40rem) {grid-template-areas:"icon title actions""icon body actions";@@ -45,7 +43,7 @@}.full-page-chat & {- @include viewport.until(sm) {+ @container (width < 40rem) {margin-inline: var(--space-4);max-width: calc(100% - var(--space-8));}@@ -63,7 +61,7 @@width: 2.5rem;height: 2.5rem;- @include viewport.until(sm) {+ @container (width < 40rem) {width: 2rem;height: 2rem;}@@ -76,7 +74,7 @@&__body {grid-area: body;- color: var(--primary-medium);+ color: var(--primary-high);font-size: var(--font-down-1);}@@ -86,7 +84,7 @@align-items: center;gap: var(--space-2);- @include viewport.until(sm) {+ @container (width < 40rem) {margin-top: var(--space-2);}@@ -96,7 +94,7 @@}.toggle-channel-membership-button {- @include viewport.until(sm) {+ @container (width < 40rem) {width: 100%;}}diff --git a/plugins/chat/lib/chat/channel_fetcher.rb b/plugins/chat/lib/chat/channel_fetcher.rbindex e568aef500f..d4b133c3ab0 100644--- a/plugins/chat/lib/chat/channel_fetcher.rb+++ b/plugins/chat/lib/chat/channel_fetcher.rb@@ -115,6 +115,10 @@ module Chat)channels = channels.includes(:chat_channel_archive) if options[:include_archives]+ extra_includes =+ DiscoursePluginRegistry.apply_modifier(:chat_channel_fetcher_public_includes, [])+ channels = channels.includes(*extra_includes) if extra_includes.present?+channels =channels.with_categoriesdiff --git a/plugins/chat/spec/serializer/chat/structured_channel_serializer_spec.rb b/plugins/chat/spec/serializer/chat/structured_channel_serializer_spec.rbindex 1063961f1de..5ef13f0ab06 100644--- a/plugins/chat/spec/serializer/chat/structured_channel_serializer_spec.rb+++ b/plugins/chat/spec/serializer/chat/structured_channel_serializer_spec.rb@@ -172,15 +172,17 @@ RSpec.describe Chat::StructuredChannelSerializer do.expects(:new).with(channel1,- root: nil,- scope: guardian,- membership: membership1,- new_messages_message_bus_last_id: 0,- new_mentions_message_bus_last_id: 0,- kick_message_bus_last_id: 0,- channel_message_bus_last_id: 0,- can_join_chat_channel: true,- post_allowed_category_ids: nil,+ has_entries(+ root: nil,+ scope: guardian,+ membership: membership1,+ new_messages_message_bus_last_id: 0,+ new_mentions_message_bus_last_id: 0,+ kick_message_bus_last_id: 0,+ channel_message_bus_last_id: 0,+ can_join_chat_channel: true,+ post_allowed_category_ids: nil,+ ),).oncedescribed_class.new(data, scope: guardian).as_jsondiff --git a/plugins/discourse-calendar/about.json b/plugins/discourse-calendar/about.jsonnew file mode 100644index 00000000000..8c0ad9ee3af--- /dev/null+++ b/plugins/discourse-calendar/about.json@@ -0,0 +1,7 @@+{+ "tests": {+ "requiredPlugins": [+ "chat"+ ]+ }+}\ No newline at end of filediff --git a/plugins/discourse-calendar/app/models/discourse_calendar/livestream/topic_chat_channel.rb b/plugins/discourse-calendar/app/models/discourse_calendar/livestream/topic_chat_channel.rbindex ddf944e9940..632c7691061 100644--- a/plugins/discourse-calendar/app/models/discourse_calendar/livestream/topic_chat_channel.rb+++ b/plugins/discourse-calendar/app/models/discourse_calendar/livestream/topic_chat_channel.rb@@ -14,11 +14,12 @@ end## Table name: livestream_topic_chat_channels#-# id :bigint not null, primary key-# created_at :datetime not null-# updated_at :datetime not null-# chat_channel_id :bigint not null-# topic_id :bigint not null+# id :bigint not null, primary key+# created_at :datetime not null+# updated_at :datetime not null+# chat_channel_id :bigint not null+# reference_message_id :bigint+# topic_id :bigint not null## Indexes#diff --git a/plugins/discourse-calendar/app/models/discourse_post_event/event.rb b/plugins/discourse-calendar/app/models/discourse_post_event/event.rbindex 4dd163fdf51..5b12541ee57 100644--- a/plugins/discourse-calendar/app/models/discourse_post_event/event.rb+++ b/plugins/discourse-calendar/app/models/discourse_post_event/event.rb@@ -399,12 +399,24 @@ module DiscoursePostEventendend- def can_user_update_attendance?(user)+ # unlike can_user_update_attendance?, this stays true after the event+ # closes or expires so attendees keep access to the livestream chat.+ #+ # Callers serializing many events at once (e.g. the chat channel list) can+ # pass preloaded invitee_event_ids/group_names to avoid a per-event query.+ def can_access_livestream_chat?(user, invitee_event_ids: nil, group_names: nil)+ return true if !private?+ return false if user.blank?+ return true if user.admin?++ invited?(user, invitee_event_ids:, group_names:)+ end++ def can_user_update_attendance?(user, invitee_event_ids: nil, group_names: nil)return false if closed || expired?return true if public?- private? &&- (invitees.exists?(user_id: user.id) || (user.groups.pluck(:name) & raw_invitees).any?)+ private? && invited?(user, invitee_event_ids:, group_names:)enddef sync_image_to_post_and_topic(generate_thumbnails: false)@@ -571,6 +583,14 @@ module DiscoursePostEventprivate+ def invited?(user, invitee_event_ids: nil, group_names: nil)+ if invitee_event_ids && group_names+ invitee_event_ids.include?(id) || (Array(raw_invitees) & Array(group_names)).any?+ else+ invitees.exists?(user_id: user.id) || user.groups.where(name: Array(raw_invitees)).exists?+ end+ end+def reset_invitees_topic_trackingtopic_id = post&.topic_idreturn if topic_id.nil?diff --git a/plugins/discourse-calendar/app/services/discourse_post_event/chat_channel_sync.rb b/plugins/discourse-calendar/app/services/discourse_post_event/chat_channel_sync.rbindex 5adefca8ff1..ab60caec6ce 100644--- a/plugins/discourse-calendar/app/services/discourse_post_event/chat_channel_sync.rb+++ b/plugins/discourse-calendar/app/services/discourse_post_event/chat_channel_sync.rb@@ -60,6 +60,7 @@ module DiscoursePostEventguardian:,params: {name:,+ emoji: "spiral_calendar",category_id: event.post.topic.category_id,},) do |result|diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/index.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/index.gjsindex 149873819e5..137ba0153e5 100644--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/index.gjs+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/index.gjs@@ -83,6 +83,7 @@ const StatusPlaceholder = <template>export default class DiscoursePostEvent extends Component {@service currentUser;@service discoursePostEventApi;+ @service embeddableChat;@service messageBus;@service siteSettings;@@ -115,6 +116,14 @@ export default class DiscoursePostEvent extends Component {return this.fetchedEvent ?? this.args.event;}+ get useLivestreamLayout() {+ return (+ this.event.livestream &&+ this.embeddableChat.chatChannelId &&+ !this.embeddableChat.isChannelOpenInDrawer+ );+ }+get isPartialEvent() {return !this.args.event?.creator;}@@ -400,7 +409,7 @@ export default class DiscoursePostEvent extends Component {{{/if}}{{#unless @hideLivestreamVideo}}- {{#if event.livestream}}+ {{#if this.useLivestreamLayout}}{{bodyClass "livestream-topic"}}{{/if}}<Livestream @event={{event}} />diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/embeddable-chat-channel.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/embeddable-chat-channel.gjsindex 25e45ea824d..a22410df5c5 100644--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/embeddable-chat-channel.gjs+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/embeddable-chat-channel.gjs@@ -12,6 +12,8 @@ import ChatChannel from "discourse/plugins/chat/discourse/components/chat-channediscourseImport: "optional",};+export const LIVESTREAM_CHAT_CONTEXT = "livestream-embedded-chat";+export default class EmbedableChatChannel extends Component {@service chatChannelsManager;@service currentUser;@@ -44,6 +46,14 @@ export default class EmbedableChatChannel extends Component {return `/discourse-calendar/livestream/chat-status/${this.currentUser.id}`;}+ get hiddenMessageIds() {+ // the pinned topic reference message is redundant when the chat is+ // embedded in the livestream topic it links to+ const messageId = this.activeChannel?.livestreamTopic?.reference_message_id;++ return messageId ? [Number(messageId)] : [];+ }+@bindasync onMessage(message) {const membership = JSON.parse(message).user_channel_membership;@@ -92,7 +102,11 @@ export default class EmbedableChatChannel extends Component {<div class="chat-drawer">{{#if (and this.activeChannel ChatChannel)}}{{#each (array this.activeChannel) as |channel|}}- <ChatChannel @channel={{channel}} />+ <ChatChannel+ @channel={{channel}}+ @context={{LIVESTREAM_CHAT_CONTEXT}}+ @hiddenMessageIds={{this.hiddenMessageIds}}+ />{{/each}}{{/if}}</div>diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/connectors/chat-channel-card-cta/livestream-rsvp.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/connectors/chat-channel-card-cta/livestream-rsvp.gjsnew file mode 100644index 00000000000..b414f4d41f4--- /dev/null+++ b/plugins/discourse-calendar/assets/javascripts/discourse/connectors/chat-channel-card-cta/livestream-rsvp.gjs@@ -0,0 +1,22 @@+import DButton from "discourse/ui-kit/d-button";+import LivestreamRsvp from "../../lib/livestream-rsvp";++export default class LivestreamRsvpCard extends LivestreamRsvp {+ get showRsvpButton() {+ return this.shouldRenderRsvp && !this.channel.isFollowing;+ }++ <template>+ {{#if this.showRsvpButton}}+ <DButton+ class="btn-primary btn-small chat-channel-card__join-btn livestream-rsvp__going-button"+ @icon="check"+ @label="discourse_post_event.models.invitee.status.going"+ @disabled={{this.isSaving}}+ @action={{this.markAsGoing}}+ />+ {{else}}+ {{yield}}+ {{/if}}+ </template>+}diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/connectors/chat-channel-preview-card-content/livestream-rsvp.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/connectors/chat-channel-preview-card-content/livestream-rsvp.gjsnew file mode 100644index 00000000000..9e3dc25d1b7--- /dev/null+++ b/plugins/discourse-calendar/assets/javascripts/discourse/connectors/chat-channel-preview-card-content/livestream-rsvp.gjs@@ -0,0 +1,54 @@+import { trustHTML } from "@ember/template";+import DButton from "discourse/ui-kit/d-button";+import dIcon from "discourse/ui-kit/helpers/d-icon";+import { i18n } from "discourse-i18n";+import { LIVESTREAM_CHAT_CONTEXT } from "../../components/livestream/embeddable-chat-channel";+import LivestreamRsvp from "../../lib/livestream-rsvp";++export default class LivestreamRsvpPreviewCard extends LivestreamRsvp {+ get isOnTopic() {+ return this.args.outletArgs.context === LIVESTREAM_CHAT_CONTEXT;+ }++ get rsvpMessage() {+ // when the chat renders within the livestream topic, there is no point+ // linking to the topic the user is already on+ if (this.isOnTopic) {+ return i18n("discourse_calendar.livestream.chat.rsvp_to_event");+ }++ return trustHTML(+ i18n("discourse_calendar.livestream.chat.rsvp_to_event_with_link", {+ url: this.livestreamTopic.url,+ })+ );+ }++ <template>+ {{#if this.shouldRenderRsvp}}+ <div class="chat-channel-preview-card__icon">+ {{dIcon "calendar-days"}}+ </div>++ <div class="chat-channel-preview-card__title livestream-rsvp__message">+ {{this.rsvpMessage}}+ </div>++ <div class="chat-channel-preview-card__body">+ {{i18n "discourse_calendar.livestream.chat.rsvp_body"}}+ </div>++ <div class="chat-channel-preview-card__actions">+ <DButton+ class="btn-primary livestream-rsvp__going-button"+ @icon="check"+ @label="discourse_post_event.models.invitee.status.going"+ @disabled={{this.isSaving}}+ @action={{this.markAsGoing}}+ />+ </div>+ {{else}}+ {{yield}}+ {{/if}}+ </template>+}diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/connectors/chat-join-channel-button/join-channel-message.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/connectors/chat-join-channel-button/join-channel-message.gjsdeleted file mode 100644index 3dfdccc8600..00000000000--- a/plugins/discourse-calendar/assets/javascripts/discourse/connectors/chat-join-channel-button/join-channel-message.gjs+++ /dev/null@@ -1,29 +0,0 @@-import Component from "@glimmer/component";-import { service } from "@ember/service";-import { i18n } from "discourse-i18n";--export default class JoinChannelMessage extends Component {- @service embeddableChat;-- get shouldRenderJoinText() {- return (- this.embeddableChat.topicHasLivestream &&- this.embeddableChat.chatChannelId- );- }-- <template>- {{#if this.shouldRenderJoinText}}- <div class="livestream-join-channel-message">- <h2>- {{i18n "discourse_calendar.livestream.chat.join_channel_header"}}- </h2>- <p>- {{i18n "discourse_calendar.livestream.chat.join_channel_message"}}- </p>- </div>- {{else}}- {{yield}}- {{/if}}- </template>-}diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/lib/livestream-rsvp.js b/plugins/discourse-calendar/assets/javascripts/discourse/lib/livestream-rsvp.jsnew file mode 100644index 00000000000..284a64caacc--- /dev/null+++ b/plugins/discourse-calendar/assets/javascripts/discourse/lib/livestream-rsvp.js@@ -0,0 +1,105 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import { service } from "@ember/service";+import { isEmpty } from "@ember/utils";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { bind } from "discourse/lib/decorators";++export default class LivestreamRsvp extends Component {+ @service appEvents;+ @service currentUser;+ @service discoursePostEventApi;+ @service messageBus;++ @tracked isSaving = false;++ constructor() {+ super(...arguments);++ if (this.livestreamTopic && this.currentUser) {+ this.messageBus.subscribe(+ this.messageBusChannel,+ this.onMembershipChange+ );+ }+ }++ willDestroy() {+ super.willDestroy(...arguments);++ if (this.livestreamTopic && this.currentUser) {+ this.messageBus.unsubscribe(+ this.messageBusChannel,+ this.onMembershipChange+ );+ }+ }++ get channel() {+ return this.args.outletArgs.channel;+ }++ get livestreamTopic() {+ return this.channel?.livestreamTopic;+ }++ get messageBusChannel() {+ return `/discourse-calendar/livestream/chat-status/${this.currentUser.id}`;+ }++ get shouldRenderRsvp() {+ if (!this.livestreamTopic) {+ return false;+ }++ // can_update_attendance is computed server-side for the current user, so+ // users who cannot join the event (private event group permissions,+ // closed or expired events) keep the default join button instead; the+ // same applies to users who already RSVP'd going but left the channel,+ // so they always have an actionable button+ return (+ this.livestreamTopic.can_update_attendance &&+ !isEmpty(this.livestreamTopic.event_id) &&+ this.livestreamTopic.watching_invitee_status !== "going"+ );+ }++ @bind+ onMembershipChange(message) {+ const membership = JSON.parse(message).user_channel_membership;++ if (membership.chat_channel_id !== this.channel.id) {+ return;+ }++ this.channel.currentUserMembership = membership;+ }++ @action+ async markAsGoing() {+ this.isSaving = true;++ try {+ const event = await this.discoursePostEventApi.event(+ this.livestreamTopic.event_id+ );+ const payload = { status: "going" };+ const data = { status: "going", postId: event.id };++ if (event.watchingInvitee) {+ await this.discoursePostEventApi.updateEventAttendance(event, payload);+ this.appEvents.trigger("calendar:update-invitee-status", data);+ } else {+ await this.discoursePostEventApi.joinEvent(event, payload);+ this.appEvents.trigger("calendar:create-invitee-status", data);+ }+ } catch (e) {+ popupAjaxError(e);+ } finally {+ if (!this.isDestroying && !this.isDestroyed) {+ this.isSaving = false;+ }+ }+ }+}diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/models/discourse-post-event-event.js b/plugins/discourse-calendar/assets/javascripts/discourse/models/discourse-post-event-event.jsindex f98e3f89e88..f8df2613546 100644--- a/plugins/discourse-calendar/assets/javascripts/discourse/models/discourse-post-event-event.js+++ b/plugins/discourse-calendar/assets/javascripts/discourse/models/discourse-post-event-event.js@@ -237,6 +237,7 @@ export default class DiscoursePostEventEvent {this.canActOnDiscoursePostEvent = event.canActOnDiscoursePostEvent;this.shouldDisplayInvitees = event.shouldDisplayInvitees;this.stats = event.stats;+ this.watchingInvitee = event.watchingInvitee;this.sampleInvitees = event.sampleInvitees || [];this.reminders = event.reminders;this.imageUpload = event.imageUpload;diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/services/embeddable-chat.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/services/embeddable-chat.gjsindex e497c7901a2..3824b1bb6af 100644--- a/plugins/discourse-calendar/assets/javascripts/discourse/services/embeddable-chat.gjs+++ b/plugins/discourse-calendar/assets/javascripts/discourse/services/embeddable-chat.gjs@@ -10,6 +10,7 @@ export default class EmbeddableChat extends Service {@service currentUser;@service capabilities;@optionalService chat;+ @optionalService chatStateManager;@tracked isMobileChatVisible = false;@@ -17,6 +18,14 @@ export default class EmbeddableChat extends Service {return this.chat?.userCanChat ?? false;}+ get isChannelOpenInDrawer() {+ return (+ this.chatStateManager?.isDrawerActive &&+ this.chatStateManager?.isDrawerExpanded &&+ this.chat?.activeChannel?.id === this.chatChannelId+ );+ }+canRenderChatChannel(mobileViewAllowed = false) {if (this.isMobileViewport === mobileViewAllowed &&@@ -33,7 +42,7 @@ export default class EmbeddableChat extends Service {);if (withinPathsAllowed && this.chatChannelId) {- return true;+ return !this.isChannelOpenInDrawer;}}diff --git a/plugins/discourse-calendar/assets/stylesheets/common/livestream.scss b/plugins/discourse-calendar/assets/stylesheets/common/livestream.scssindex 1ce1ab02a2f..f4ca6960804 100644--- a/plugins/discourse-calendar/assets/stylesheets/common/livestream.scss+++ b/plugins/discourse-calendar/assets/stylesheets/common/livestream.scss@@ -29,6 +29,12 @@ body.chat-enabled.livestream-topic.confirmed-event-assistance {}}+.livestream-rsvp__going-button {+ @container (width < 40rem) {+ width: 100%;+ }+}+.discourse-calendar-livestream-zoom-entry-container {margin-top: 1rem;}@@ -136,28 +142,6 @@ body.chat-enabled.livestream-topic.confirmed-event-assistance {}}-body.chat-enabled.livestream-topic,-body.chat-enabled.websdk-body {- .chat-channel-preview-card {- flex-direction: column;- align-items: center;- justify-content: center;-- .chat-channel__placeholder {- display: none;- }- }-}--.livestream-join-channel-message {- text-align: center;- margin-top: 1rem;-- h2 {- margin-bottom: 0.5rem;- }-}-// Overrides zoom toasts, we do not want these showing as they are// un-dismissable and not helpful messages.notistack-SnackbarContainer {diff --git a/plugins/discourse-calendar/config/locales/client.en.yml b/plugins/discourse-calendar/config/locales/client.en.ymlindex 57340e40a9e..b13c610065e 100644--- a/plugins/discourse-calendar/config/locales/client.en.yml+++ b/plugins/discourse-calendar/config/locales/client.en.yml@@ -40,9 +40,9 @@ en:other: "The webinar hasn't started yet. Retrying join in %{count} seconds..."not_started_trying_again: "Trying to join the webinar again now..."chat:- going: "Click Going"- join_channel_header: "🌟 Join the Buzz! 🌟"- join_channel_message: "Confirm your attendance and unlock our event chat. Dive into discussions, share your excitement, and connect with fellow attendees!"+ rsvp_to_event: "RSVP to the event to start chatting"+ rsvp_to_event_with_link: "RSVP to <a href='%{url}'>the event</a> to start chatting"+ rsvp_body: "Connect with other attendees before, during, and after the event."invite_user_notification: "%{username} invited you to: %{description}"preferences:all_events: "Discourse Calendar - All Events"diff --git a/plugins/discourse-calendar/config/locales/server.en.yml b/plugins/discourse-calendar/config/locales/server.en.ymlindex beb69a17f80..816e8aada82 100644--- a/plugins/discourse-calendar/config/locales/server.en.yml+++ b/plugins/discourse-calendar/config/locales/server.en.yml@@ -105,6 +105,9 @@ en:all_events_feed_name: "%{site_title} - All events"my_events_feed_name: "%{site_title} - My events"invite_user_notification: "%{username} invited you to: %{description}"+ livestream:+ chat:+ topic_reference_message: "This channel is for the event [%{title}](%{url}) — visit the topic for details and to RSVP."calendar_must_be_in_first_post: "Calendar tag can only be used in first post of a topic."more_than_one_calendar: "You can’t have more than one calendar in a post."more_than_two_dates: "A post of a calendar topic can’t contain more than two dates."diff --git a/plugins/discourse-calendar/db/migrate/20260715202231_add_reference_message_id_to_livestream_topic_chat_channels.rb b/plugins/discourse-calendar/db/migrate/20260715202231_add_reference_message_id_to_livestream_topic_chat_channels.rbnew file mode 100644index 00000000000..c9b23bbe409--- /dev/null+++ b/plugins/discourse-calendar/db/migrate/20260715202231_add_reference_message_id_to_livestream_topic_chat_channels.rb@@ -0,0 +1,6 @@+# frozen_string_literal: true+class AddReferenceMessageIdToLivestreamTopicChatChannels < ActiveRecord::Migration[8.0]+ def change+ add_column :livestream_topic_chat_channels, :reference_message_id, :bigint+ end+enddiff --git a/plugins/discourse-calendar/plugin.rb b/plugins/discourse-calendar/plugin.rbindex 7fd66612b73..7339125886c 100644--- a/plugins/discourse-calendar/plugin.rb+++ b/plugins/discourse-calendar/plugin.rb@@ -77,6 +77,7 @@ module ::DiscourseCalendarchatable_id: topic.category.id,chatable_type: "Category",name: topic.title,+ emoji: "spiral_calendar",status: Chat::Channel.statuses[:open],type: "CategoryChannel",allow_channel_wide_mentions: true,@@ -84,6 +85,61 @@ module ::DiscourseCalendarDiscourseCalendar::Livestream::TopicChatChannel.create!(topic: topic, chat_channel: channel)channel.user_chat_channel_memberships.create!(user: topic.user, following: false)+ pin_topic_reference_message(topic, channel)+ end++ def self.pin_topic_reference_message(topic, channel)+ guardian = Discourse.system_user.guardian+ message = nil++ Chat::CreateMessage.call(+ guardian:,+ params: {+ chat_channel_id: channel.id,+ message:+ I18n.t(+ "discourse_calendar.livestream.chat.topic_reference_message",+ title: topic.markdown_link_title,+ url: topic.relative_url,+ ),+ },+ options: {+ enforce_membership: true,+ },+ ) do |create_result|+ on_success { |message_instance:| message = message_instance }+ on_failure do+ Rails.logger.warn(+ "Failed to create livestream topic reference message for channel #{channel.id}: #{create_result.inspect_steps}",+ )+ end+ end++ return if message.blank?++ DiscourseCalendar::Livestream::TopicChatChannel.where(chat_channel_id: channel.id).update_all(+ reference_message_id: message.id,+ )++ return if !SiteSetting.chat_pinned_messages++ Chat::PinMessage.call(+ guardian:,+ params: {+ message_id: message.id,+ channel_id: channel.id,+ },+ ) do |pin_result|+ on_failure do+ Rails.logger.warn(+ "Failed to pin livestream topic reference message for channel #{channel.id}: #{pin_result.inspect_steps}",+ )+ end+ end+ rescue StandardError => e+ Rails.logger.warn(+ "Failed to post livestream topic reference message for channel #{channel.id}: #{e.message}",+ )enddef self.livestream_chat_status_channel(user_id)@@ -97,6 +153,51 @@ module ::DiscourseCalendaruser_ids: [user.id],)end++ class ChannelSerializationContext+ def initialize(user)+ @user = user+ end++ def invitees_by_post_id+ return {} if @user.nil?++ @invitees_by_post_id ||=+ DiscoursePostEvent::Invitee.where(user_id: @user.id).index_by(&:post_id)+ end++ def invitee_event_ids+ invitees_by_post_id.keys+ end++ def group_names+ return [] if @user.nil?++ @group_names ||= @user.groups.pluck(:name)+ end+ end++ module ChannelSerializerExtension+ private++ def livestream_serialization_context+ @livestream_serialization_context ||=+ @options[:livestream_context] ||+ DiscourseCalendar::Livestream::ChannelSerializationContext.new(scope.user)+ end++ def livestream_invitees_by_post_id+ livestream_serialization_context.invitees_by_post_id+ end++ def livestream_invitee_event_ids+ livestream_serialization_context.invitee_event_ids+ end++ def livestream_user_group_names+ livestream_serialization_context.group_names+ end+ endenddef self.users_on_holiday@@ -843,12 +944,74 @@ after_initialize do:topic_view,:chat_channel_id,include_condition: -> do- object.topic.first_post&.event&.livestream? && object.topic.topic_chat_channel.present?+ event = object.topic.first_post&.event+ event&.livestream? && object.topic.topic_chat_channel.present? &&+ (scope.is_admin? || event.can_access_livestream_chat?(scope.user))end,) { object.topic.topic_chat_channel.chat_channel_id }add_to_serializer(:topic_view, :has_livestream) { object.topic.first_post&.event&.livestream? }+ Chat::ChannelSerializer.include(DiscourseCalendar::Livestream::ChannelSerializerExtension)++ register_modifier(:chat_channel_fetcher_public_includes) do |includes|+ includes + [{ livestream_topic_chat_channel: { topic: { first_post: :event } } }]+ end++ register_modifier(:chat_channel_serializer_public_options) do |serializer_options, guardian|+ serializer_options.merge(+ livestream_context:+ DiscourseCalendar::Livestream::ChannelSerializationContext.new(guardian.user),+ )+ end++ add_to_serializer(+ "Chat::Channel",+ :livestream_topic,+ include_condition: -> do+ return false if object.chatable_type != "Category"++ topic = object.livestream_topic_chat_channel&.topic+ event = topic&.first_post&.event++ return false if !event++ event.livestream? &&+ event.can_access_livestream_chat?(+ scope.user,+ invitee_event_ids: livestream_invitee_event_ids,+ group_names: livestream_user_group_names,+ )+ end,+ ) do+ topic = object.livestream_topic_chat_channel.topic+ event = topic.first_post&.event+ watching_invitee = livestream_invitees_by_post_id[event&.id]++ can_update_attendance =+ if scope.anonymous? || !event+ false+ else+ event.can_user_update_attendance?(+ scope.user,+ invitee_event_ids: livestream_invitee_event_ids,+ group_names: livestream_user_group_names,+ )+ end++ {+ id: topic.id,+ title: topic.title,+ slug: topic.slug,+ url: topic.relative_url,+ event_id: topic.first_post&.id,+ reference_message_id: object.livestream_topic_chat_channel.reference_message_id,+ can_update_attendance: can_update_attendance,+ watching_invitee_status:+ watching_invitee && DiscoursePostEvent::Invitee.statuses[watching_invitee.status],+ }+ end+on(:chat_channel_trashed) do |channel, user|# If the chat channel is deleted, delete the related TopicChatChannel recordDiscourseCalendar::Livestream::TopicChatChannel.where(chat_channel_id: channel.id).destroy_alldiff --git a/plugins/discourse-calendar/spec/lib/discourse_calendar/livestream/handle_topic_chat_channel_creation_spec.rb b/plugins/discourse-calendar/spec/lib/discourse_calendar/livestream/handle_topic_chat_channel_creation_spec.rbindex c6d9b721579..c6905ab7c08 100644--- a/plugins/discourse-calendar/spec/lib/discourse_calendar/livestream/handle_topic_chat_channel_creation_spec.rb+++ b/plugins/discourse-calendar/spec/lib/discourse_calendar/livestream/handle_topic_chat_channel_creation_spec.rb@@ -34,6 +34,7 @@ RSpec.describe DiscourseCalendar::Livestream docontext "when the first post is a livestream event" dobefore doSiteSetting.calendar_enabled = true+ SiteSetting.chat_pinned_messages = truepost = Fabricate(:post, topic: topic)Fabricate(:event, post: post, livestream: true, location: "https://example.com/live")end@@ -43,6 +44,7 @@ RSpec.describe DiscourseCalendar::Livestream doexpect(Chat::Channel.count).to eq(1)expect(Chat::Channel.first.chatable).to eq(category)+ expect(Chat::Channel.first.emoji).to eq("spiral_calendar")endit "creates a topic chat channel" do@@ -52,11 +54,10 @@ RSpec.describe DiscourseCalendar::Livestream doexpect(DiscourseCalendar::Livestream::TopicChatChannel.first.topic).to eq(topic)end- it "creates a user chat channel membership" do+ it "creates a user chat channel membership for the topic creator" dodescribed_class.handle_topic_chat_channel_creation(topic)- expect(Chat::UserChatChannelMembership.count).to eq(1)- expect(Chat::UserChatChannelMembership.first.user).to eq(topic.user)+ expect(Chat::UserChatChannelMembership.where(user: topic.user, following: false)).to existendit "deletes the chat channel and the topic chat channel when the topic is destroyed" do@@ -106,6 +107,36 @@ RSpec.describe DiscourseCalendar::Livestream doexpect(Chat::Channel.count).to eq(0)end+ it "posts a pinned message referencing the topic when pinned messages are enabled" do+ described_class.handle_topic_chat_channel_creation(topic)++ channel = Chat::Channel.first+ message = Chat::Message.find_by(chat_channel: channel, user: Discourse.system_user)+ expect(message.message).to include(topic.title)+ expect(message.message).to include(topic.relative_url)+ expect(Chat::PinnedMessage.where(chat_message: message, chat_channel: channel)).to exist+ expect(DiscourseCalendar::Livestream::TopicChatChannel.first.reference_message_id).to eq(+ message.id,+ )+ end++ it "escapes markdown metacharacters from the topic title in the reference message" do+ malicious =+ Fabricate(:topic, category: category, title: "Party](https://evil.example) oops")+ malicious_post = Fabricate(:post, topic: malicious)+ Fabricate(+ :event,+ post: malicious_post,+ livestream: true,+ location: "https://example.com/live",+ )++ channel = malicious.reload.topic_chat_channel.chat_channel+ message = Chat::Message.find_by(chat_channel: channel, user: Discourse.system_user)+ expect(message.message).to include("Party\\]\\(https://evil.example\\) oops")+ expect(message.message).not_to include("[Party](")+ end+it "updated the chat channel when the topic category is updated" dodescribed_class.handle_topic_chat_channel_creation(topic)@@ -118,6 +149,23 @@ RSpec.describe DiscourseCalendar::Livestream doexpect(Chat::Channel.first.chatable).to eq(new_category)endend++ context "when the first post is a livestream event and pinned messages are disabled" do+ before do+ SiteSetting.calendar_enabled = true+ SiteSetting.chat_pinned_messages = false+ post = Fabricate(:post, topic: topic)+ Fabricate(:event, post: post, livestream: true, location: "https://example.com/live")+ end++ it "posts the topic reference message without pinning it" do+ described_class.handle_topic_chat_channel_creation(topic)++ channel = Chat::Channel.first+ expect(Chat::Message.where(chat_channel: channel, user: Discourse.system_user)).to exist+ expect(Chat::PinnedMessage.count).to eq(0)+ end+ endendendenddiff --git a/plugins/discourse-calendar/spec/requests/chat/livestream_channels_spec.rb b/plugins/discourse-calendar/spec/requests/chat/livestream_channels_spec.rbnew file mode 100644index 00000000000..fb47bbfadb4--- /dev/null+++ b/plugins/discourse-calendar/spec/requests/chat/livestream_channels_spec.rb@@ -0,0 +1,58 @@+# frozen_string_literal: true++RSpec.describe "Livestream channel list serialization" do+ fab!(:user)+ fab!(:category)+ fab!(:group) { Fabricate(:group).tap { |g| g.add(user) } }++ before do+ SiteSetting.calendar_enabled = true+ SiteSetting.discourse_post_event_enabled = true+ SiteSetting.chat_enabled = true+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]+ # avoid the onebox-warming job making a real request+ Jobs.run_later!+ sign_in(user)+ end++ def create_livestream_channel+ topic = Fabricate(:topic, category:)+ post = Fabricate(:post, topic:)+ DiscoursePostEvent::Event.create!(+ id: post.id,+ original_starts_at: 1.hour.from_now,+ original_ends_at: 2.hours.from_now,+ location: "https://example.com/live",+ status: DiscoursePostEvent::Event.statuses[:private],+ raw_invitees: [group.name],+ livestream: true,+ )+ topic.reload.topic_chat_channel.chat_channel+ end++ def event_related_query_count(queries)+ queries.count do |sql|+ sql.include?("discourse_post_event_invitees") || sql.include?("discourse_post_event_events")+ end+ end++ it "batches livestream metadata instead of querying per channel" do+ create_livestream_channel++ queries_for_one = track_sql_queries { get "/chat/api/channels.json", params: { filter: "" } }+ expect(response.status).to eq(200)+ channels = response.parsed_body["channels"]+ expect(channels.filter_map { |c| c["livestream_topic"] }).to be_present++ create_livestream_channel+ create_livestream_channel++ queries_for_many = track_sql_queries { get "/chat/api/channels.json", params: { filter: "" } }+ expect(response.status).to eq(200)+ expect(response.parsed_body["channels"].size).to be >= 3++ expect(event_related_query_count(queries_for_many)).to eq(+ event_related_query_count(queries_for_one),+ )+ end+enddiff --git a/plugins/discourse-calendar/spec/serializers/chat_channel_serializer_spec.rb b/plugins/discourse-calendar/spec/serializers/chat_channel_serializer_spec.rbnew file mode 100644index 00000000000..672ca0fdea7--- /dev/null+++ b/plugins/discourse-calendar/spec/serializers/chat_channel_serializer_spec.rb@@ -0,0 +1,87 @@+# frozen_string_literal: true++RSpec.describe Chat::ChannelSerializer do+ fab!(:category)+ fab!(:viewer, :user)+ let(:topic) { Fabricate(:topic, category:) }+ let(:first_post) { Fabricate(:post, topic:) }++ before do+ SiteSetting.calendar_enabled = true+ SiteSetting.discourse_post_event_enabled = true+ SiteSetting.chat_enabled = true+ # avoid the onebox-warming job making a real request+ Jobs.run_later!+ first_post+ end++ def create_event(livestream: true, status: :public, raw_invitees: nil)+ DiscoursePostEvent::Event.create!(+ id: first_post.id,+ original_starts_at: 1.hour.from_now,+ original_ends_at: 2.hours.from_now,+ location: "https://example.com/live",+ status: DiscoursePostEvent::Event.statuses[status],+ raw_invitees:,+ livestream:,+ )+ end++ def livestream_channel+ topic.reload.topic_chat_channel.chat_channel+ end++ def serialize(channel, user)+ described_class.new(channel, scope: Guardian.new(user), root: nil).as_json+ end++ describe "#livestream_topic" do+ it "references the linked topic for accessible livestream channels" do+ create_event(livestream: true)++ expect(serialize(livestream_channel, viewer)[:livestream_topic]).to include(+ id: topic.id,+ title: topic.title,+ slug: topic.slug,+ url: topic.relative_url,+ event_id: first_post.id,+ )+ end++ it "is omitted for channels without a linked livestream topic" do+ channel = Fabricate(:chat_channel, chatable: category)++ expect(serialize(channel, viewer)).not_to have_key(:livestream_topic)+ end++ it "is omitted for users who cannot access a private event" do+ create_event(livestream: true, status: :private, raw_invitees: ["some_group"])++ expect(serialize(livestream_channel, viewer)).not_to have_key(:livestream_topic)+ end++ it "is included for users in an invited group" do+ group = Fabricate(:group)+ group.add(viewer)+ create_event(livestream: true, status: :private, raw_invitees: [group.name])++ expect(serialize(livestream_channel, viewer)[:livestream_topic]).to include(id: topic.id)+ end++ it "is included for admins even when they cannot access the event" do+ create_event(livestream: true, status: :private, raw_invitees: ["some_group"])++ expect(serialize(livestream_channel, Fabricate(:admin))[:livestream_topic]).to include(+ id: topic.id,+ )+ end++ it "is omitted once livestream is disabled, even if the channel row remains" do+ event = create_event(livestream: true)+ channel = livestream_channel+ event.update!(livestream: false)++ expect(serialize(channel.reload, viewer)).not_to have_key(:livestream_topic)+ end+ end+enddiff --git a/plugins/discourse-calendar/spec/serializers/topic_view_serializer_spec.rb b/plugins/discourse-calendar/spec/serializers/topic_view_serializer_spec.rbindex 4e9886176d2..2f492aee620 100644--- a/plugins/discourse-calendar/spec/serializers/topic_view_serializer_spec.rb+++ b/plugins/discourse-calendar/spec/serializers/topic_view_serializer_spec.rb@@ -134,6 +134,7 @@ RSpec.describe TopicViewSerializer dodescribe "#chat_channel_id" dofab!(:category)+ fab!(:viewer, :user)let(:topic) { Fabricate(:topic, category:) }before do@@ -143,21 +144,31 @@ RSpec.describe TopicViewSerializer dofirst_postend- def create_event(livestream:)+ def create_event(livestream:, status: :public, raw_invitees: nil)DiscoursePostEvent::Event.create!(id: first_post.id,original_starts_at: 1.hour.from_now,original_ends_at: 2.hours.from_now,location: "https://example.com/live",+ status: DiscoursePostEvent::Event.statuses[status],+ raw_invitees:,livestream:,)end+ def parsed_json_for(user)+ JSON.parse(+ described_class.new(TopicView.new(topic), scope: Guardian.new(user), root: false).to_json,+ )+ end+it "is included while the event is a livestream" docreate_event(livestream: true)expect(topic.topic_chat_channel).to be_present- expect(parsed_json["chat_channel_id"]).to eq(topic.topic_chat_channel.chat_channel_id)+ expect(parsed_json_for(viewer)["chat_channel_id"]).to eq(+ topic.topic_chat_channel.chat_channel_id,+ )endit "is not included once livestream is disabled, even if the channel row remains" do@@ -165,7 +176,55 @@ RSpec.describe TopicViewSerializer doevent.update!(livestream: false)expect(topic.reload.topic_chat_channel).to be_present- expect(parsed_json).not_to have_key("chat_channel_id")+ expect(parsed_json_for(viewer)).not_to have_key("chat_channel_id")+ end++ it "is not included for users who cannot join the event" do+ create_event(livestream: true, status: :private, raw_invitees: ["some_group"])++ expect(parsed_json_for(viewer)).not_to have_key("chat_channel_id")+ end++ it "is not included for anonymous users on private events" do+ create_event(livestream: true, status: :private, raw_invitees: ["some_group"])++ expect(parsed_json_for(nil)).not_to have_key("chat_channel_id")+ end++ it "is included for anonymous users on public events" do+ create_event(livestream: true)++ expect(parsed_json_for(nil)["chat_channel_id"]).to eq(+ topic.topic_chat_channel.chat_channel_id,+ )+ end++ it "is still included once the event is expired" do+ create_event(livestream: true)++ freeze_time(3.hours.from_now)++ expect(parsed_json_for(viewer)["chat_channel_id"]).to eq(+ topic.topic_chat_channel.chat_channel_id,+ )+ end++ it "is included for users in a group that can join the event" do+ group = Fabricate(:group)+ group.add(viewer)+ create_event(livestream: true, status: :private, raw_invitees: [group.name])++ expect(parsed_json_for(viewer)["chat_channel_id"]).to eq(+ topic.topic_chat_channel.chat_channel_id,+ )+ end++ it "is included for admins even when they cannot join the event" do+ create_event(livestream: true, status: :private, raw_invitees: ["some_group"])++ expect(parsed_json_for(Fabricate(:admin))["chat_channel_id"]).to eq(+ topic.topic_chat_channel.chat_channel_id,+ )endendenddiff --git a/plugins/discourse-calendar/spec/system/desktop_topic_livestream_authenticated_spec.rb b/plugins/discourse-calendar/spec/system/desktop_topic_livestream_authenticated_spec.rbindex ac4e011865f..fbb8025f497 100644--- a/plugins/discourse-calendar/spec/system/desktop_topic_livestream_authenticated_spec.rb+++ b/plugins/discourse-calendar/spec/system/desktop_topic_livestream_authenticated_spec.rb@@ -23,9 +23,7 @@ describe "Discourse Livestream - Topic Livestream - Desktop - Authenticated" doexpect(topic_page).to have_css("#custom-chat-container")expect(topic_page).to have_css("#custom-chat-container .chat-channel-preview-card")- expect(topic_page).to have_text(- I18n.t("js.discourse_calendar.livestream.chat.join_channel_header"),- )+ expect(topic_page).to have_text(I18n.t("js.discourse_calendar.livestream.chat.rsvp_to_event"))endit "does not create a chat channel for regular topics" do@@ -33,7 +31,7 @@ describe "Discourse Livestream - Topic Livestream - Desktop - Authenticated" doexpect(topic_page).not_to have_css("#custom-chat-container")expect(topic_page).not_to have_text(- I18n.t("js.discourse_calendar.livestream.chat.join_channel_header"),+ I18n.t("js.discourse_calendar.livestream.chat.rsvp_to_event"),)endenddiff --git a/plugins/discourse-calendar/test/javascripts/components/livestream-rsvp-test.gjs b/plugins/discourse-calendar/test/javascripts/components/livestream-rsvp-test.gjsnew file mode 100644index 00000000000..7fd42f46c7e--- /dev/null+++ b/plugins/discourse-calendar/test/javascripts/components/livestream-rsvp-test.gjs@@ -0,0 +1,161 @@+import { getOwner } from "@ember/owner";+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import { i18n } from "discourse-i18n";+import ChatChannelCard from "discourse/plugins/chat/discourse/components/chat-channel-card";+import ChatChannelPreviewCard from "discourse/plugins/chat/discourse/components/chat-channel-preview-card";+import ChatFabricators from "discourse/plugins/chat/discourse/lib/fabricators";+import { LIVESTREAM_CHAT_CONTEXT } from "discourse/plugins/discourse-calendar/discourse/components/livestream/embeddable-chat-channel";++module("Discourse Calendar | Component | LivestreamRsvp", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.channel = new ChatFabricators(getOwner(this)).channel({+ chatable_type: "Category",+ });+ this.channel.title = "livestream chat";+ this.channel.meta = { can_join_chat_channel: true };+ this.currentUser.set("has_chat_enabled", true);+ this.siteSettings.chat_enabled = true;++ this.setLivestreamTopic = (overrides = {}) => {+ this.channel.livestreamTopic = {+ id: 1,+ title: "Watching the birds",+ slug: "watching-the-birds",+ url: "/t/watching-the-birds/1",+ event_id: 99,+ can_update_attendance: true,+ watching_invitee_status: null,+ ...overrides,+ };+ };+ });++ test("replaces the join button with a linked RSVP message for livestream channels", async function (assert) {+ this.setLivestreamTopic();++ await render(+ <template><ChatChannelPreviewCard @channel={{this.channel}} /></template>+ );++ assert+ .dom(".livestream-rsvp__message a[href='/t/watching-the-birds/1']")+ .exists("links to the livestream topic");+ assert+ .dom(".chat-channel-preview-card__actions .livestream-rsvp__going-button")+ .exists("renders the RSVP button in the preview card actions");+ assert.dom(".toggle-channel-membership-button.-join").doesNotExist();+ });++ test("does not link the topic when rendered within the livestream topic", async function (assert) {+ this.setLivestreamTopic();++ await render(+ <template>+ <ChatChannelPreviewCard+ @channel={{this.channel}}+ @context={{LIVESTREAM_CHAT_CONTEXT}}+ />+ </template>+ );++ assert+ .dom(".livestream-rsvp__message")+ .hasText(i18n("discourse_calendar.livestream.chat.rsvp_to_event"));+ assert.dom(".livestream-rsvp__message a").doesNotExist();+ });++ test("keeps the default join button when the user cannot join the event", async function (assert) {+ this.setLivestreamTopic({ can_update_attendance: false });++ await render(+ <template><ChatChannelPreviewCard @channel={{this.channel}} /></template>+ );++ assert.dom(".toggle-channel-membership-button.-join").exists();+ assert.dom(".livestream-rsvp__going-button").doesNotExist();+ });++ test("keeps the default join button when the user is already going", async function (assert) {+ this.setLivestreamTopic({ watching_invitee_status: "going" });++ await render(+ <template><ChatChannelPreviewCard @channel={{this.channel}} /></template>+ );++ assert.dom(".toggle-channel-membership-button.-join").exists();+ assert.dom(".livestream-rsvp__going-button").doesNotExist();+ });++ test("keeps the default join button for regular channels", async function (assert) {+ await render(+ <template><ChatChannelPreviewCard @channel={{this.channel}} /></template>+ );++ assert.dom(".toggle-channel-membership-button.-join").exists();+ assert.dom(".livestream-rsvp__going-button").doesNotExist();+ });++ test("does not render the RSVP replacement when the livestream topic is absent", async function (assert) {+ this.channel.livestreamTopic = undefined;++ await render(+ <template><ChatChannelPreviewCard @channel={{this.channel}} /></template>+ );++ assert.dom(".livestream-rsvp").doesNotExist();+ assert.dom(".livestream-rsvp__message").doesNotExist();+ assert.dom(".livestream-rsvp__going-button").doesNotExist();+ assert.dom(".toggle-channel-membership-button.-join").exists();+ });++ module("browse channels card", function () {+ test("replaces the join button with the RSVP button for livestream channels", async function (assert) {+ this.setLivestreamTopic();++ await render(+ <template><ChatChannelCard @channel={{this.channel}} /></template>+ );++ assert+ .dom(".chat-channel-card__cta .livestream-rsvp__going-button")+ .exists("renders the RSVP button in the card CTA");+ assert.dom(".toggle-channel-membership-button.-join").doesNotExist();+ });++ test("keeps the default join button when the user cannot join the event", async function (assert) {+ this.setLivestreamTopic({ can_update_attendance: false });++ await render(+ <template><ChatChannelCard @channel={{this.channel}} /></template>+ );++ assert.dom(".toggle-channel-membership-button.-join").exists();+ assert.dom(".livestream-rsvp__going-button").doesNotExist();+ });++ test("keeps the default join button for regular channels", async function (assert) {+ await render(+ <template><ChatChannelCard @channel={{this.channel}} /></template>+ );++ assert.dom(".toggle-channel-membership-button.-join").exists();+ assert.dom(".livestream-rsvp__going-button").doesNotExist();+ });++ test("keeps the leave button for existing chat members", async function (assert) {+ this.setLivestreamTopic();+ this.channel.currentUserMembership = { following: true };++ await render(+ <template><ChatChannelCard @channel={{this.channel}} /></template>+ );++ assert.dom(".toggle-channel-membership-button.-leave").exists();+ assert.dom(".livestream-rsvp__going-button").doesNotExist();+ });+ });+});diff --git a/spec/models/topic_spec.rb b/spec/models/topic_spec.rbindex 1cc7b8ac41c..e5bca79e540 100644--- a/spec/models/topic_spec.rb+++ b/spec/models/topic_spec.rb@@ -556,6 +556,14 @@ RSpec.describe Topic doendend+ describe "#markdown_link_title" do+ it "escapes markdown metacharacters that can break a link title" do+ topic = Fabricate.build(:topic, title: "Party](https://evil.example) \\ oops")++ expect(topic.markdown_link_title).to eq("Party\\]\\(https://evil.example\\) \\\\ oops")+ end+ end+describe "fancy title" dolet(:topic) { Fabricate.build(:topic, title: %{"this topic" -- has ``fancy stuff''}) }