A platform for community discussion. Free, open, simple.
FEATURE: add livestream recording and chat transcript on event end (#44397)
Kris325879f7abef
diff --git a/db/structure.sql b/db/structure.sqlindex 82316ff3fe3..1f5c71ac8f9 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -4964,7 +4964,8 @@ CREATE TABLE public.discourse_post_event_events (max_attendees integer,all_day boolean DEFAULT false NOT NULL,image_upload_id bigint,- livestream boolean DEFAULT false NOT NULL+ livestream boolean DEFAULT false NOT NULL,+ recording_url character varying(1000));@@ -7829,7 +7830,9 @@ CREATE TABLE public.livestream_topic_chat_channels (chat_channel_id bigint NOT NULL,created_at timestamp(6) without time zone NOT NULL,updated_at timestamp(6) without time zone NOT NULL,- reference_message_id bigint+ reference_message_id bigint,+ last_transcribed_message_id bigint,+ closed_on_event_end boolean DEFAULT false NOT NULL);@@ -26177,6 +26180,7 @@ INSERT INTO "schema_migrations" (version) VALUES('20261015175355'),('20261015175340'),('20261015121116'),+('20261014231432'),('20261014224810'),('20261014145458'),('20261014065735'),@@ -26192,6 +26196,8 @@ INSERT INTO "schema_migrations" (version) VALUES('20261009130230'),('20261009121104'),('20261009113440'),+('20261008184751'),+('20261008173326'),('20261008005940'),('20261007082151'),('20261006113418'),diff --git a/plugins/chat/lib/chat/transcript_service.rb b/plugins/chat/lib/chat/transcript_service.rbindex 0edf7c00714..641394335a6 100644--- a/plugins/chat/lib/chat/transcript_service.rb+++ b/plugins/chat/lib/chat/transcript_service.rb@@ -185,7 +185,8 @@ module Chat# We are getting only the OP of the thread, let's expand it to# include all the replies for the thread.- if messages.count == 1 && thread&.original_message_id == messages.first.id+ if !@opts[:no_thread_expansion] && messages.count == 1 &&+ thread&.original_message_id == messages.first.id@messages = [messages.first] + messages.first.thread.repliesenddiff --git a/plugins/chat/spec/lib/chat/transcript_service_spec.rb b/plugins/chat/spec/lib/chat/transcript_service_spec.rbindex c34f31ee519..0db36458764 100644--- a/plugins/chat/spec/lib/chat/transcript_service_spec.rb+++ b/plugins/chat/spec/lib/chat/transcript_service_spec.rb@@ -361,6 +361,26 @@ describe Chat::TranscriptService doMARKDOWNend+ it "expands a lone thread opener into its replies" do+ thread = Fabricate(:chat_thread, channel:, original_message_user: user1)+ reply = Fabricate(:chat_message, chat_channel: channel, user: user2, thread:, message: "done")+ thread.update!(replies_count: 1)++ expect(service(thread.original_message_id).generate_markdown).to include(reply.message)+ end++ it "renders only the given thread opener when thread expansion is off" do+ thread = Fabricate(:chat_thread, channel:, original_message_user: user1)+ reply = Fabricate(:chat_message, chat_channel: channel, user: user2, thread:, message: "done")+ thread.update!(replies_count: 1)++ rendered =+ service(thread.original_message_id, opts: { no_thread_expansion: true }).generate_markdown++ expect(rendered).to include("quote=\"#{user1.username};#{thread.original_message_id};")+ expect(rendered).not_to include(reply.message)+ end+it "generates a chat transcript for threaded messages" dothread =Fabricate(diff --git a/plugins/discourse-events/app/models/discourse_events/events/event.rb b/plugins/discourse-events/app/models/discourse_events/events/event.rbindex 4a88308dbae..507a2c4324f 100644--- a/plugins/discourse-events/app/models/discourse_events/events/event.rb+++ b/plugins/discourse-events/app/models/discourse_events/events/event.rb@@ -45,8 +45,10 @@ module DiscourseEventsafter_save :sync_hostsafter_commit :create_livestream_chat_channel, on: %i[create update]after_commit :enqueue_warm_livestream_onebox, on: %i[create update]+ after_commit :enqueue_warm_recording_onebox, on: %i[create update]after_commit :destroy_topic_custom_field, on: %i[destroy]after_commit :create_or_update_event_date, on: %i[create update]+ after_commit :reopen_livestream_chat_channel, on: :updateafter_save doif saved_change_to_image_upload_id?UploadReference.ensure_exist!(upload_ids: [image_upload_id], target: self)@@ -63,6 +65,7 @@ module DiscourseEventsvalidates :description, length: { maximum: MAX_DESCRIPTION_LENGTH }validates :location, length: { maximum: MAX_LOCATION_LENGTH }validates :url, length: { maximum: MAX_URL_LENGTH }+ validates :recording_url, length: { maximum: MAX_URL_LENGTH }validates :max_attendees,numericality: {only_integer: true,@@ -109,6 +112,22 @@ module DiscourseEventsDiscourseEvents::Livestream.handle_topic_chat_channel_creation(post.topic)end+ # The chat closes once the event ends, so an event moved back into the+ # future, or made recurring, needs it open again.+ def reopen_livestream_chat_channel+ return unless livestream? && SiteSetting.chat_enabled+ return if !occurrences_remaining?++ topic_chat_channel =+ DiscourseEvents::Livestream::TopicChatChannel.includes(:chat_channel).find_by(+ topic_id: post&.topic_id,+ closed_on_event_end: true,+ )+ return if !topic_chat_channel&.chat_channel&.closed?++ topic_chat_channel.chat_channel.open!(Discourse.system_user)+ end+def has_cached_livestream_onebox?livestream? && livestream_url.present? && Oneboxer.cached_onebox(livestream_url).present?end@@ -123,11 +142,27 @@ module DiscourseEventsJobs.enqueue(:warm_livestream_onebox, event_id: id, url: livestream_url)end+ # The raw allows a recording without a scheme; oneboxing needs one.+ def recording_link+ return if recording_url.blank?+ recording_url.match?(%r{\Ahttps?://}i) ? recording_url : "https://#{recording_url}"+ end++ def has_cached_recording_onebox?+ recording_link.present? && Oneboxer.cached_onebox(recording_link).present?+ end++ def enqueue_warm_recording_onebox+ return if recording_link.blank? || !saved_change_to_recording_url?+ return if has_cached_recording_onebox?+ Jobs.enqueue(:warm_recording_onebox, event_id: id, url: recording_link)+ end+# Fetches the onebox and tells clients to re-render the post with it. Only- # ever called from the background job, never during a request.- def warm_livestream_onebox!- return if has_cached_livestream_onebox?- Oneboxer.onebox(livestream_url)+ # ever called from a background job, never during a request.+ def warm_onebox!(url)+ return if Oneboxer.cached_onebox(url).present?+ Oneboxer.onebox(url)post&.publish_change_to_clients!(:revised)end@@ -228,6 +263,13 @@ module DiscourseEventscurrent_event_date&.starts_at || original_starts_atend+ # Between occurrences of a recurring livestream there is nothing to chat+ # alongside, so the chat only docks around each one.+ def livestream_chat_active?+ return false if !livestream? || expired?+ !recurring? || currently_within_event_timeframe?+ end+def ends_atcurrent_event_date&.ends_at || original_ends_atend@@ -421,6 +463,14 @@ module DiscourseEventsrecurrence.present?end+ # Unlike `expired?`, also false for a series whose cutoff falls after its+ # last occurrence.+ def occurrences_remaining?(after: Time.current)+ return false if expired?+ return true if !recurring?+ calculate_next_occurrence_from(after).present?+ end+def most_likely_going(limit = SiteSetting.displayed_invitees_limit)going = invitees.order(%i[status created_at user_id]).limit(limit).to_a@@ -835,6 +885,7 @@ end# original_ends_at :datetime# original_starts_at :datetime not null# raw_invitees :string is an Array+# recording_url :string(1000)# recurrence :string# recurrence_until :datetime# reminders :stringdiff --git a/plugins/discourse-events/app/models/discourse_events/events/event_date.rb b/plugins/discourse-events/app/models/discourse_events/events/event_date.rbindex d5cdffa9fd7..159042e40f1 100644--- a/plugins/discourse-events/app/models/discourse_events/events/event_date.rb+++ b/plugins/discourse-events/app/models/discourse_events/events/event_date.rb@@ -25,6 +25,12 @@ module DiscourseEventsSQLend+ # Mirrors the opening of Event#currently_within_event_timeframe?.+ def opens_at+ return starts_at.beginning_of_day if event.all_day+ starts_at - Event::EARLY_ACCESS_MINUTES.minutes+ end+after_commit :upsert_topic_custom_field, on: %i[create update]def upsert_topic_custom_fieldif event.post && event.post.is_first_post?diff --git a/plugins/discourse-events/app/models/discourse_events/livestream/topic_chat_channel.rb b/plugins/discourse-events/app/models/discourse_events/livestream/topic_chat_channel.rbindex 8935b8a8274..2553c39d24c 100644--- a/plugins/discourse-events/app/models/discourse_events/livestream/topic_chat_channel.rb+++ b/plugins/discourse-events/app/models/discourse_events/livestream/topic_chat_channel.rb@@ -6,6 +6,16 @@ module DiscourseEventsself.table_name = "livestream_topic_chat_channels"belongs_to :topicbelongs_to :chat_channel, class_name: "Chat::Channel", dependent: :destroy++ def untranscribed_messages(before: nil)+ messages =+ chat_channel+ .chat_messages+ .where.not(id: reference_message_id)+ .where("chat_messages.id > ?", last_transcribed_message_id.to_i)+ .includes(:user, :chat_channel)+ before ? messages.where("chat_messages.created_at < ?", before) : messages+ endendendend@@ -14,12 +24,14 @@ 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-# reference_message_id :bigint-# topic_id :bigint not null+# id :bigint not null, primary key+# closed_on_event_end :boolean default(FALSE), not null+# created_at :datetime not null+# updated_at :datetime not null+# chat_channel_id :bigint not null+# last_transcribed_message_id :bigint+# reference_message_id :bigint+# topic_id :bigint not null## Indexes#diff --git a/plugins/discourse-events/app/serializers/discourse_events/events/event_serializer.rb b/plugins/discourse-events/app/serializers/discourse_events/events/event_serializer.rbindex 83dc9e13c02..7c03b4a8277 100644--- a/plugins/discourse-events/app/serializers/discourse_events/events/event_serializer.rb+++ b/plugins/discourse-events/app/serializers/discourse_events/events/event_serializer.rb@@ -39,6 +39,8 @@ module DiscourseEvents# comes from chat_enabled on the event, we dont need 2 channels per eventattributes :livestream_chat_channel_idattributes :is_zoom_livestream+ attributes :recording_url+ attributes :recording_oneboxattributes :channelattributes :rruleattributes :max_attendees@@ -205,6 +207,19 @@ module DiscourseEventsobject.url.present?end+ def include_recording_url?+ object.recording_url.present?+ end++ def include_recording_onebox?+ include_recording_url?+ end++ # Cache only, as with `livestream_onebox`; `warm_recording_onebox` fills it.+ def recording_onebox+ Oneboxer.cached_onebox(object.recording_link).presence+ end+def include_description_html?object.description.present?enddiff --git a/plugins/discourse-events/app/services/discourse_events/events/event/action/attributes_from_raw.rb b/plugins/discourse-events/app/services/discourse_events/events/event/action/attributes_from_raw.rbindex 6dc476c42f8..a1841c9ba2d 100644--- a/plugins/discourse-events/app/services/discourse_events/events/event/action/attributes_from_raw.rb+++ b/plugins/discourse-events/app/services/discourse_events/events/event/action/attributes_from_raw.rb@@ -26,6 +26,7 @@ module DiscourseEventsclosed: raw_event[:closed] || false,chat_enabled: raw_event[:"chat-enabled"]&.downcase == "true",livestream: raw_event[:livestream]&.downcase == "true",+ recording_url: raw_event[:recording],max_attendees: raw_event[:"max-attendees"]&.to_i,all_day: all_day?,custom_fields: custom_fields,diff --git a/plugins/discourse-events/app/services/discourse_events/livestream/chat_transcript.rb b/plugins/discourse-events/app/services/discourse_events/livestream/chat_transcript.rbnew file mode 100644index 00000000000..6a4560db84b--- /dev/null+++ b/plugins/discourse-events/app/services/discourse_events/livestream/chat_transcript.rb@@ -0,0 +1,142 @@+# frozen_string_literal: true++# Renders the most recent chat messages of a livestream occurrence, keeping only+# as many as fit in `max_length` and pointing to the channel for earlier ones.+# A recurring event's transcript is dated to tell its occurrences apart.+class DiscourseEvents::Livestream::ChatTranscript+ # A quoted message is never shorter than this, which bounds how many could+ # ever fit in a post and so how many need loading.+ MIN_QUOTED_MESSAGE_LENGTH = 50++ WRAP_NAME = "livestream-chat-transcript"++ # A message closing the quote or wrap around it, or opening one that takes+ # their closing tag, would have the rest of its text cooked as part of a post+ # authored by someone else.+ CONTAINER_TAGS = %r{\[/?(?:chat|wrap)(?=[\s=\]])}i++ # Sizing renders the same messages over and over, and each rendering of a+ # message queries its uploads.+ class QuotedMessage < SimpleDelegator+ def to_markdown+ @to_markdown ||= __getobj__.to_markdown+ end+ end++ def initialize(channel:, messages:, event_date:, max_length:)+ @channel = channel+ @messages = messages+ @event_date = event_date+ @max_length = max_length+ end++ def messages?+ candidates.any?+ end++ def last_message_id+ candidates.last&.id+ end++ def raw+ @raw ||= render(included_count)+ end++ # Even without any messages, the heading and the pointer to the channel may+ # not fit what is left of a post.+ def within_length?+ raw.length <= @max_length+ end++ private++ def candidates+ @candidates ||=+ @messages+ .reorder(id: :desc)+ .limit([@max_length / MIN_QUOTED_MESSAGE_LENGTH, 0].max + 1)+ .to_a+ .reverse+ .map { |message| contained(message) }+ end++ def total_count+ @total_count ||= @messages.count+ end++ # The largest number of most recent messages whose rendering fits, found by+ # bisection since the quote markup makes the length hard to predict. Zero+ # leaves just the pointer to the channel.+ def included_count+ (0..candidates.size).bsearch { |count| !fits?(count + 1) }+ end++ def fits?(count)+ count <= candidates.size && render(count).length <= @max_length+ end++ def render(count)+ I18n.with_locale(SiteSetting.default_locale) do+ [+ heading,+ earlier_messages_notice(total_count - count),+ quotes(candidates.last(count)),+ ].compact.join("\n\n")+ end+ end++ def heading+ if @event_date.event.recurring?+ I18n.t("discourse_events.livestream.chat.transcript_heading_dated", date: occurrence_date)+ else+ I18n.t("discourse_events.livestream.chat.transcript_heading")+ end+ end++ def occurrence_date+ event = @event_date.event+ starts_at = @event_date.starts_at.in_time_zone(event.timezone.presence || "UTC")+ return I18n.l(starts_at.to_date, format: :long) if !SiteSetting.discourse_local_dates_enabled++ time = event.all_day ? "" : " time=#{starts_at.strftime("%H:%M:%S")}"+ "[date=#{starts_at.strftime("%Y-%m-%d")}#{time} timezone=\"#{starts_at.time_zone.tzinfo.name}\"]"+ end++ # Done once per message, as escaping again would stack backslashes. Read-only+ # so the escaped text can never be saved back to the message.+ def contained(message)+ # An upload-only message has no text.+ message.message = message.message.to_s.gsub(CONTAINER_TAGS) { "\\#{it}" }+ message.readonly!+ QuotedMessage.new(message)+ end++ def earlier_messages_notice(count)+ return if count.zero?++ I18n.t(+ "discourse_events.livestream.chat.transcript_earlier_messages",+ count:,+ url: @channel.relative_url,+ )+ end++ # Wrapped so the quotes, one block per speaker, can scroll as a whole.+ def quotes(messages)+ return if messages.empty?++ transcript =+ Chat::TranscriptService.new(+ @channel,+ Discourse.system_user,+ messages_or_ids: messages,+ # Replies outside the given messages may belong to another occurrence,+ # and would skip the escaping applied to these.+ opts: {+ no_thread_expansion: true,+ },+ ).generate_markdown++ "[wrap=#{WRAP_NAME}]\n#{transcript}\n[/wrap]"+ end+enddiff --git a/plugins/discourse-events/app/services/discourse_events/livestream/chat_transcript_audience.rb b/plugins/discourse-events/app/services/discourse_events/livestream/chat_transcript_audience.rbnew file mode 100644index 00000000000..a50b169493e--- /dev/null+++ b/plugins/discourse-events/app/services/discourse_events/livestream/chat_transcript_audience.rb@@ -0,0 +1,96 @@+# frozen_string_literal: true++# Decides whether a livestream's chat can be posted to its topic: only when+# everyone able to read the topic could already read the chat. Compares groups+# rather than members, so it errs towards keeping the chat out of the topic.+class DiscourseEvents::Livestream::ChatTranscriptAudience+ AUTO_GROUPS = Group::AUTO_GROUPS+ ALL_LOGGED_IN_USERS = AUTO_GROUPS.values_at(:everyone, :logged_in_users, :trust_level_0)+ TRUST_LEVEL_GROUPS = AUTO_GROUPS.values_at(*(0..4).map { |level| :"trust_level_#{level}" })+ POSTING_PERMISSIONS = CategoryGroup.permission_types.values_at(:full, :create_post)++ def initialize(event, channel:)+ @event = event+ @channel = channel+ end++ def matches_topic_readers?+ topic_reader_group_ids.all? do |group_id|+ chat_audiences.all? { |allowed_ids| covers?(allowed_ids, group_id) }+ end+ end++ private++ # Everyone is split into its anonymous and logged in halves, since chat can+ # admit one without the other.+ def topic_reader_group_ids+ category = @event.post.topic.category+ group_ids = category&.read_restricted? ? category.secure_group_ids : [AUTO_GROUPS[:everyone]]++ group_ids.flat_map do |id|+ case id+ when AUTO_GROUPS[:everyone]+ [AUTO_GROUPS[:logged_in_users], *anonymous_readers]+ when AUTO_GROUPS[:anonymous_users]+ anonymous_readers+ else+ [id]+ end+ end+ end++ def anonymous_readers+ SiteSetting.login_required ? [] : [AUTO_GROUPS[:anonymous_users]]+ end++ # Each set must allow a reader for them to have seen the chat. The channel+ # keeps the category it was created in, even if the topic has since moved.+ def chat_audiences+ audiences = [SiteSetting.chat_allowed_groups_map]+ audiences << invited_group_ids if @event.private?+ audiences << channel_category_group_ids if channel_category+ audiences+ end++ def channel_category+ @channel.chatable if @channel.chatable.is_a?(Category)+ end++ # Mirrors `Guardian#can_join_chat_channel?`: members read the chat only when+ # they can post in its category, while anonymous users read a public+ # channel as long as they can see the category.+ def channel_category_group_ids+ category_groups = channel_category.category_groups+ group_ids =+ if category_groups.empty?+ [AUTO_GROUPS[:everyone]]+ else+ category_groups.where(permission_type: POSTING_PERMISSIONS).pluck(:group_id)+ end+ group_ids << AUTO_GROUPS[:anonymous_users] if !channel_category.read_restricted?+ group_ids+ end++ def invited_group_ids+ Group.where(name: @event.raw_invitees).pluck(:id)+ end++ def covers?(allowed_ids, group_id)+ # Mirrors `Chat.anonymous_public_channel_access_allowed?`.+ if group_id == AUTO_GROUPS[:anonymous_users]+ return SiteSetting.enable_public_channels && allowed_ids.include?(group_id)+ end++ return true if allowed_ids.include?(group_id) || allowed_ids.intersect?(ALL_LOGGED_IN_USERS)++ case group_id+ when *TRUST_LEVEL_GROUPS+ allowed_ids.any? { |id| TRUST_LEVEL_GROUPS.include?(id) && id <= group_id }+ when AUTO_GROUPS[:staff]+ allowed_ids.include?(AUTO_GROUPS[:admins]) && allowed_ids.include?(AUTO_GROUPS[:moderators])+ else+ false+ end+ end+enddiff --git a/plugins/discourse-events/app/services/discourse_events/livestream/publish_chat_transcript.rb b/plugins/discourse-events/app/services/discourse_events/livestream/publish_chat_transcript.rbnew file mode 100644index 00000000000..36f150446c1--- /dev/null+++ b/plugins/discourse-events/app/services/discourse_events/livestream/publish_chat_transcript.rb@@ -0,0 +1,188 @@+# frozen_string_literal: true++# Once a livestream occurrence ends, its chat is preserved in the event topic,+# provided everyone who can read the topic could already read the chat: in the+# event post for a one-off event, as a dated reply per occurrence otherwise, or+# when the event post has no room left for it.+# The channel is closed when no further occurrences will reuse it.+class DiscourseEvents::Livestream::PublishChatTranscript+ include Service::Base++ # The transcript was sized for the raw it was rendered against, so an edit+ # made meanwhile means rendering it again.+ class EventPostChanged < StandardError+ end++ params do+ attribute :event_date_id, :integer++ validates :event_date_id, presence: true+ end++ policy :chat_enabled+ model :event_date+ model :event+ model :topic_chat_channel++ lock(:topic_chat_channel) do+ transaction do+ step :reload_records++ only_if(:chat_audience_matches_topic_readers) do+ model :event_post_transcript, :render_event_post_transcript, optional: true+ model :transcript, :render_transcript++ only_if(:new_chat_messages) do+ only_if(:appending_to_event_post) { step :append_transcript_to_event_post }+ only_if(:replying) { step :reply_with_transcript }+ step :mark_messages_transcribed+ end+ end+ end+ end++ only_if(:livestream_finished) { step :close_chat_channel }++ private++ def chat_enabled+ SiteSetting.chat_enabled+ end++ def fetch_event_date(params:)+ DiscourseEvents::Events::EventDate.includes(event: { post: :topic }).find_by(+ id: params.event_date_id,+ )+ end++ def fetch_event(event_date:)+ event_date.event if event_date.event&.livestream?+ end++ def fetch_topic_chat_channel(event:)+ DiscourseEvents::Livestream::TopicChatChannel.includes(:chat_channel).find_by(+ topic: event.post.topic,+ )+ end++ def chat_audience_matches_topic_readers(event:, topic_chat_channel:)+ DiscourseEvents::Livestream::ChatTranscriptAudience.new(+ event,+ channel: topic_chat_channel.chat_channel,+ ).matches_topic_readers?+ end++ # Fetched before the lock, so a job that held it may have moved them on.+ # Locking the topic holds off a move to another category, which would change+ # who reads the transcript, until it is written.+ def reload_records(event:, topic_chat_channel:)+ event.post.reload.topic.lock!+ topic_chat_channel.reload+ end++ # Appended to the event post, it shares the length limit with what is there.+ def render_event_post_transcript(event:, event_date:, topic_chat_channel:)+ return if event.recurring?++ transcript =+ build_transcript(+ event:,+ event_date:,+ topic_chat_channel:,+ max_length: SiteSetting.max_post_length - event.post.raw.rstrip.length - 2,+ )+ transcript if transcript.within_length?+ end++ def render_transcript(event_post_transcript:, event:, event_date:, topic_chat_channel:)+ event_post_transcript ||+ build_transcript(+ event:,+ event_date:,+ topic_chat_channel:,+ max_length: SiteSetting.max_post_length,+ )+ end++ def build_transcript(event:, event_date:, topic_chat_channel:, max_length:)+ DiscourseEvents::Livestream::ChatTranscript.new(+ channel: topic_chat_channel.chat_channel,+ messages:+ topic_chat_channel.untranscribed_messages(+ before: next_occurrence_opens_at(event:, event_date:),+ ),+ event_date:,+ max_length:,+ )+ end++ # A late job must leave the chat of the next occurrence to its own transcript.+ def next_occurrence_opens_at(event:, event_date:)+ next_starts_at =+ event.calculate_next_occurrence_from(event_date.starts_at + 1.second)&.dig(:starts_at)+ return if !next_starts_at++ DiscourseEvents::Events::EventDate.new(event:, starts_at: next_starts_at).opens_at+ end++ def new_chat_messages(transcript:)+ transcript.messages?+ end++ def appending_to_event_post(event_post_transcript:)+ event_post_transcript.present?+ end++ def replying(event_post_transcript:)+ event_post_transcript.blank?+ end++ # A record of the stream rather than news, so neither notifies nor bumps.+ def reply_with_transcript(event:, transcript:)+ PostCreator.create!(+ Discourse.system_user,+ topic_id: event.post.topic_id,+ raw: transcript.raw,+ skip_validations: true,+ import_mode: true,+ silent: true,+ )+ end++ def append_transcript_to_event_post(event:, transcript:)+ expected_raw = event.post.raw+ revised =+ PostRevisor.new(event.post).revise!(+ Discourse.system_user,+ {+ raw: "#{expected_raw.rstrip}\n\n#{transcript.raw}",+ edit_reason: I18n.t("discourse_events.livestream.chat.transcript_edit_reason"),+ },+ bypass_bump: true,+ silent: true,+ skip_validations: true,+ skip_staff_log: true,+ expected_raw:,+ )+ raise EventPostChanged if event.post.errors.of_kind?(:base, :edit_conflict)+ fail!(event.post.errors.full_messages.to_sentence) if !revised+ end++ def mark_messages_transcribed(topic_chat_channel:, transcript:)+ topic_chat_channel.update!(last_transcribed_message_id: transcript.last_message_id)+ end++ # Asked of the occurrence that ended rather than of now, as the job may run late.+ def livestream_finished(event:, event_date:)+ !event.occurrences_remaining?(after: event_date.starts_at + 1.second)+ end++ # Only an open channel, so a status set by moderators is kept and the event+ # can tell its own closing apart if it resumes.+ def close_chat_channel(topic_chat_channel:)+ return if !topic_chat_channel.chat_channel.open?++ topic_chat_channel.chat_channel.closed!(Discourse.system_user)+ topic_chat_channel.update!(closed_on_event_end: true)+ end+enddiff --git a/plugins/discourse-events/assets/javascripts/discourse/components/compact-event-editor.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/compact-event-editor.gjsindex 076c84ecc00..7eaa9255c74 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/compact-event-editor.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/compact-event-editor.gjs@@ -28,6 +28,7 @@ import {isLivestreamUrl,livestreamSource,reconcileDefaultReminder,+ showRecordingField,} from "discourse/plugins/discourse-events/discourse/lib/raw-event-helper";import DiscoursePostEventEvent from "discourse/plugins/discourse-events/discourse/models/discourse-post-event-event";@@ -55,6 +56,7 @@ export default class CompactEventEditor extends Component {@tracked livestream;@tracked minimal;@tracked url;+ @tracked recording;@tracked image;@tracked allowedGroups;@tracked hosts;@@ -93,6 +95,7 @@ export default class CompactEventEditor extends Component {livestream: this.livestream,minimal: this.minimal,url: this.url,+ recording: this.recording,image: this.image,allowedGroups: this.allowedGroups,hosts: this.hosts,@@ -229,6 +232,17 @@ export default class CompactEventEditor extends Component {return this.#formatTime(this.endsAt);}+ get showRecordingRow() {+ return showRecordingField({+ recording: this.recording,+ livestream: this.livestream,+ startsAt: this.startsAt,+ endsAt: this.endsAt,+ recurrence: this.recurrence,+ recurrenceUntil: this.recurrenceUntil,+ });+ }+get livestreamDisabled() {return !this.siteSettings.chat_enabled;}@@ -290,6 +304,12 @@ export default class CompactEventEditor extends Component {this.#emitChange();}+ @action+ onRecordingInput(event) {+ this.recording = event.target.value.trim() || null;+ this.#emitChange();+ }+@actiontoggleLivestream() {if (this.livestreamDisabled) {@@ -507,6 +527,7 @@ export default class CompactEventEditor extends Component {starts_at: this.startsAt,ends_at: this.endsAt,url: this.url,+ recording_url: this.recording,recurrence: this.recurrence,recurrence_until: this.recurrenceUntil,image_upload: this.image ? { url: this.image } : null,@@ -538,6 +559,7 @@ export default class CompactEventEditor extends Component {this.recurrence = updatedEvent.recurrence || null;this.recurrenceUntil = updatedEvent.recurrenceUntil || null;this.url = updatedEvent.url || null;+ this.recording = updatedEvent.recordingUrl || null;this.#startedWithUrl ||= !!this.url;this.allowedGroups =(updatedEvent.rawInvitees || []).join(",") || null;@@ -582,6 +604,7 @@ export default class CompactEventEditor extends Component {this.livestream = s.livestream;this.minimal = s.minimal;this.url = s.url;+ this.recording = s.recording;this.#startedWithUrl ||= !!s.url;this.image = s.image;this.allowedGroups = s.allowedGroups;@@ -889,6 +912,22 @@ export default class CompactEventEditor extends Component {</section>{{/if}}+ {{#if this.showRecordingRow}}+ <section class="composer-event__recording">+ {{dIcon "video"}}+ <input+ class="composer-event__recording-input"+ placeholder={{i18n+ "discourse_post_event.composer.recording_placeholder"+ }}+ type="url"+ value={{this.recording}}+ {{on "input" this.onRecordingInput}}+ {{on "focus" this.handleTextInputFocus}}+ />+ </section>+ {{/if}}+<section class="composer-event__attendees">{{dIcon "users"}}<inputdiff --git a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/index.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/index.gjsindex 3aae74a595b..eac21d033c0 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/index.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/index.gjs@@ -9,6 +9,7 @@ import routeAction from "discourse/helpers/route-action";import { popupAjaxError } from "discourse/lib/ajax-error";import getURL from "discourse/lib/get-url";import DButton from "discourse/ui-kit/d-button";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dIcon from "discourse/ui-kit/helpers/d-icon";import dReplaceEmoji from "discourse/ui-kit/helpers/d-replace-emoji";import { i18n } from "discourse-i18n";@@ -26,6 +27,7 @@ import Invitees from "./invitees.gjs";import Livestream from "./livestream.gjs";import DiscoursePostEventLocation from "./location.gjs";import MoreMenu from "./more-menu.gjs";+import Recording from "./recording.gjs";import Status from "./status.gjs";import Url from "./url.gjs";@@ -124,6 +126,23 @@ export default class DiscoursePostEvent extends Component {return !this.args.event?.creator;}+ // Once the event is over and a recording exists, the stream link is stale.+ get livestreamSuperseded() {+ return !!(+ this.event?.livestream &&+ this.event.isExpired &&+ this.event.recordingUrl+ );+ }++ get locationSuperseded() {+ return this.livestreamSuperseded && !!this.event.location?.trim();+ }++ get urlSuperseded() {+ return this.livestreamSuperseded && !this.locationSuperseded;+ }+get displayUrl() {if (this.event?.urlRestatesLocation ||@@ -252,7 +271,12 @@ export default class DiscoursePostEvent extends Component {<template>{{#let this.event as |event|}}<div class="discourse-post-event" ...attributes>- <div class="discourse-post-event-widget">+ <div+ class={{dConcatClass+ "discourse-post-event-widget"+ (if event.isExpired "is-ended")+ }}+ >{{#if event}}<Image@alt={{this.eventName}}@@ -330,13 +354,19 @@ export default class DiscoursePostEvent extends Component {event=eventreadOnly=this.readOnlySection=(component InfoSection event=event)- Url=(component Url url=this.displayUrl)+ Url=(component+ Url url=this.displayUrl superseded=this.urlSuperseded+ )Description=(componentDescriptiondescriptionHtml=event.descriptionHtmlclamp=this.clampDescription)- Location=(component DiscoursePostEventLocation event=event)+ Location=(component+ DiscoursePostEventLocation+ event=event+ superseded=this.locationSuperseded+ )Dates=(component Dates event=event)Recurrence=(componentInfoSection icon="arrows-rotate" class="event-recurrence"@@ -345,6 +375,7 @@ export default class DiscoursePostEvent extends Component {Invitees=(component Invitees event=event)Status=(component Status event=event)ChatChannel=(component ChatChannel event=event)+ Recording=(component Recording event=event post=@post)Image=(componentImageimageUpload=event.imageUpload@@ -361,8 +392,14 @@ export default class DiscoursePostEvent extends Component {{{this.recurrenceLabel}}</InfoSection>{{/if}}- <DiscoursePostEventLocation @event={{event}} />- <Url @url={{this.displayUrl}} />+ <DiscoursePostEventLocation+ @event={{event}}+ @superseded={{this.locationSuperseded}}+ />+ <Url+ @superseded={{this.urlSuperseded}}+ @url={{this.displayUrl}}+ /><ChatChannel @event={{event}} />{{#unless this.readOnly}}@@ -389,6 +426,7 @@ export default class DiscoursePostEvent extends Component {{{#unless @hideLivestreamVideo}}<Livestream @event={{event}} @post={{@post}} />+ <Recording @event={{event}} @post={{@post}} />{{/unless}}{{/unless}}</PluginOutlet>diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/invitees.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/invitees.gjsindex 12fa9155ba6..5d31b008e2c 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/invitees.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/invitees.gjs@@ -61,6 +61,7 @@ export default class DiscoursePostEventInvitees extends Component {{{else}}{{#unless @event.isStandalone}}<section class="event__section event-invitees no-rsvp">+ {{dIcon "users"}}<p class="no-rsvp-description">{{i18n"discourse_post_event.models.invitee.status.going_count.other"count="0"diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/livestream.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/livestream.gjsindex cf5012e69da..ddf69ff760f 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/livestream.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/livestream.gjs@@ -1,23 +1,21 @@import Component from "@glimmer/component";-import { action } from "@ember/object";import { service } from "@ember/service";-import { trustHTML } from "@ember/template";import { isEmpty } from "@ember/utils";-import { withPluginApi } from "discourse/lib/plugin-api";-import { optionalRequire } from "discourse/lib/utilities";import { eventHasLivestream } from "../../lib/livestream-utils.js";import LivestreamZoomEntry from "../livestream/zoom-entry.gjs";+import OneboxEmbed from "./onebox-embed.gjs";-// Renders the event's livestream as a playable video at the bottom of the event-// card, from the cooked onebox served on the event (EventSerializer#livestream_-// onebox). For supported providers we hand the resolved attributes to lazy--// videos' LazyVideo component (the post-stream decorator that normally does this-// doesn't reach our card); otherwise we render the onebox as-is.+// Renders the event's livestream at the bottom of the event card, from the+// cooked onebox served on the event (EventSerializer#livestream_onebox).export default class Livestream extends Component {@service siteSettings;+ // Once over, a recording supersedes the stream, which has nothing left to show.get show() {- return eventHasLivestream(this.args.event);+ const { event } = this.args;+ return (+ eventHasLivestream(event) && !(event.isExpired && event.recordingUrl)+ );}get isZoomLivestream() {@@ -27,71 +25,17 @@ export default class Livestream extends Component {);}- // Resolved at runtime: lazy-videos may not be installed, and resolving at- // module load can return false before the plugin's modules are registered.- get lazyVideo() {- return optionalRequire(- "discourse/plugins/discourse-lazy-videos/discourse/components/lazy-video"- );- }-- get videoAttributes() {- const html = this.args.event?.livestreamOnebox;- const getVideoAttributes = optionalRequire(- "discourse/plugins/discourse-lazy-videos/lib/lazy-video-attributes"- );- if (!html || !getVideoAttributes || !this.lazyVideo) {- return null;- }-- const container = new DOMParser()- .parseFromString(html, "text/html")- .querySelector(".lazy-video-container");- if (!container) {- return null;- }-- const attributes = getVideoAttributes(container);- return this.siteSettings[`lazy_${attributes.providerName}_enabled`]- ? attributes- : null;- }-get hasLivestreamOnebox() {return !isEmpty(this.args.event?.livestreamOnebox);}- get oneboxHtml() {- return this.videoAttributes- ? null- : trustHTML(this.args.event?.livestreamOnebox ?? "");- }-- // Once playback starts the post has to stay rendered: cloaking it tears down- // the component holding the stream, taking any joined Zoom session with it.- @action- preventCloak() {- const postId = this.args.post?.id;-- if (postId) {- withPluginApi((api) => api.preventCloak(postId));- }- }-<template>{{#if this.show}}<section class="event__section event-livestream">{{#if this.isZoomLivestream}}<LivestreamZoomEntry @event={{@event}} />{{else if this.hasLivestreamOnebox}}- {{#if this.videoAttributes}}- <this.lazyVideo- @onLoadedVideo={{this.preventCloak}}- @videoAttributes={{this.videoAttributes}}- />- {{else}}- {{this.oneboxHtml}}- {{/if}}+ <OneboxEmbed @html={{@event.livestreamOnebox}} @post={{@post}} />{{/if}}</section>{{/if}}diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/location.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/location.gjsindex 028de5e65d4..c7ed8eaff0a 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/location.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/location.gjs@@ -1,5 +1,6 @@import Component from "@glimmer/component";import { trustHTML } from "@ember/template";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dIcon from "discourse/ui-kit/helpers/d-icon";import openLinksInNewTab from "discourse/plugins/discourse-events/discourse/modifiers/open-links-in-new-tab";@@ -26,7 +27,12 @@ export default class DiscoursePostEventLocation extends Component {<template>{{#if this.locationHtml}}- <section class="event__section event-location">+ <section+ class={{dConcatClass+ "event__section event-location"+ (if @superseded "--superseded")+ }}+ >{{dIcon this.icon}}<spandiff --git a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/more-menu.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/more-menu.gjsindex 687d395b6d7..23ff9bdfc60 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/more-menu.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/more-menu.gjs@@ -13,15 +13,12 @@ import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import { i18n } from "discourse-i18n";import addEventToCalendar from "../../lib/add-event-to-calendar.js";-import {- buildParams,- removeEvent,- replaceRaw,-} from "../../lib/raw-event-helper.js";-import PostEventBuilder from "../modal/post-event-builder.gjs";+import { buildParams, replaceRaw } from "../../lib/raw-event-helper.js";+import { showPostEventEditor } from "../../lib/show-post-event-editor.js";import PostEventBulkInvite from "../modal/post-event-bulk-invite.gjs";import PostEventInviteUserOrGroup from "../modal/post-event-invite-user-or-group.gjs";import PostEventInvitees from "../modal/post-event-invitees/index.gjs";+import PostEventRecording from "../modal/post-event-recording.gjs";export default class DiscoursePostEventMoreMenu extends Component {@service currentUser;@@ -41,10 +38,29 @@ export default class DiscoursePostEventMoreMenu extends Component {return this.currentUser && this.args.event.canActOnDiscoursePostEvent;}+ // One entry per top-level item guard in the template, e.g. an anonymous+ // visitor on an ended event passes none of them.+ get hasItems() {+ return [+ this.canAddToCalendar,+ this.canSendPmToCreator,+ this.canInvite,+ this.canSeeUpcomingEvents,+ this.shouldShowParticipants,+ this.canActOnEvent,+ ].some(Boolean);+ }++ get canAddToCalendar() {+ return !this.expiredOrClosed;+ }+get shouldShowParticipants() {return applyValueTransformer("discourse-calendar-event-more-menu-should-show-participants",- this.canActOnEvent && !this.args.isStandaloneEvent,+ this.canActOnEvent &&+ !this.args.isStandaloneEvent &&+ this.args.event.stats?.invited > 0,{event: this.args.event,}@@ -61,6 +77,15 @@ export default class DiscoursePostEventMoreMenu extends Component {return !this.args.event.isClosed && this.args.event.recurrence;}+ get canManageRecording() {+ const { event } = this.args;+ return (+ this.canActOnEvent &&+ event.livestream &&+ (event.isExpired || !!event.recordingUrl)+ );+ }+get canBulkInvite() {return !this.expiredOrClosed && !this.args.event.isStandalone;}@@ -176,51 +201,21 @@ export default class DiscoursePostEventMoreMenu extends Component {}@action- async editPostEvent() {+ editPostEvent() {this.menuApi.close();- this.modal.show(PostEventBuilder, {- model: {- event: this.args.event,- onDelete: async (event) => {- const post = await this.store.find("post", event.id);- const raw = post.raw;- const newRaw = removeEvent(raw);-- const props = {- raw: newRaw,- edit_reason: i18n("discourse_post_event.destroy_event"),- };-- const cooked = await cook(newRaw);- props.cooked = cooked.string;-- return await post.save(props);- },- onUpdate: async (startsAt, endsAt, event, siteSettings) => {- const post = await this.store.find("post", event.id);- const raw = post.raw;- const eventParams = buildParams(- startsAt,- endsAt,- event,- siteSettings- );- const newRaw = replaceRaw(eventParams, raw);- if (newRaw) {- const props = {- raw: newRaw,- edit_reason: i18n("discourse_post_event.edit_reason"),- };+ showPostEventEditor({+ modal: this.modal,+ store: this.store,+ event: this.args.event,+ });+ }- const cooked = await cook(newRaw);- props.cooked = cooked.string;+ @action+ manageRecording() {+ this.menuApi.close();- return await post.save(props);- }- },- },- });+ this.modal.show(PostEventRecording, { model: { event: this.args.event } });}@action@@ -278,135 +273,152 @@ export default class DiscoursePostEventMoreMenu extends Component {}<template>- <DMenu- @icon="ellipsis"- @identifier="discourse-post-event-more-menu"- @onRegisterApi={{this.registerMenuApi}}- @triggerClass={{dConcatClass- "more-dropdown"- "btn-small"- "btn-default"- (if this.isSavingEvent "--saving")- }}- >- <:content>- <DDropdownMenu as |dropdown|>- {{#unless this.expiredOrClosed}}- <dropdown.item class="add-to-calendar">- <DButton- @action={{this.addToCalendar}}- @icon="file"- @label="discourse_post_event.add_to_calendar"- />- </dropdown.item>- {{/unless}}-- {{#if this.canSendPmToCreator}}- <dropdown.item class="send-pm-to-creator">- <DButton- class="btn-transparent"- @action={{this.sendPMToCreator}}- @icon="envelope"- @translatedLabel={{i18n- "discourse_post_event.send_pm_to_creator"- (hash [email protected])- }}- />- </dropdown.item>- {{/if}}-- {{#if this.canInvite}}- <dropdown.item class="invite-user-or-group">- <DButton- class="btn-transparent"- @action={{this.inviteUserOrGroup}}- @icon="user-plus"- @translatedLabel={{i18n "discourse_post_event.invite"}}- />- </dropdown.item>- {{/if}}-- {{#if this.canSeeUpcomingEvents}}- <dropdown.item class="upcoming-events">- <DButton- class="btn-transparent"- @action={{this.upcomingEvents}}- @icon="far-calendar-plus"- @translatedLabel={{i18n- "discourse_post_event.upcoming_events.title"- }}- />- </dropdown.item>- {{/if}}-- {{#if this.shouldShowParticipants}}- <dropdown.item class="show-all-participants">- <DButton- class="btn-transparent"- @action={{this.showParticipants}}- @icon="user-group"- @label="discourse_post_event.show_participants"- />- </dropdown.item>-- <dropdown.divider />- {{/if}}- {{#if this.canActOnEvent}}- <dropdown.item class="export-event">- <DButton- class="btn-transparent"- @action={{this.exportPostEvent}}- @icon="file-csv"- @label="discourse_post_event.export_event"- />- </dropdown.item>-- {{#if this.canBulkInvite}}- <dropdown.item class="bulk-invite">+ {{#if this.hasItems}}+ <DMenu+ @icon="ellipsis"+ @identifier="discourse-post-event-more-menu"+ @onRegisterApi={{this.registerMenuApi}}+ @triggerClass={{dConcatClass+ "more-dropdown"+ "btn-small"+ "btn-default"+ (if this.isSavingEvent "--saving")+ }}+ >+ <:content>+ <DDropdownMenu as |dropdown|>+ {{#if this.canAddToCalendar}}+ <dropdown.item class="add-to-calendar">+ <DButton+ @action={{this.addToCalendar}}+ @icon="file"+ @label="discourse_post_event.add_to_calendar"+ />+ </dropdown.item>+ {{/if}}++ {{#if this.canSendPmToCreator}}+ <dropdown.item class="send-pm-to-creator">+ <DButton+ class="btn-transparent"+ @action={{this.sendPMToCreator}}+ @icon="envelope"+ @translatedLabel={{i18n+ "discourse_post_event.send_pm_to_creator"+ (hash [email protected])+ }}+ />+ </dropdown.item>+ {{/if}}++ {{#if this.canInvite}}+ <dropdown.item class="invite-user-or-group"><DButtonclass="btn-transparent"- @action={{this.bulkInvite}}- @icon="file-arrow-up"- @label="discourse_post_event.bulk_invite"+ @action={{this.inviteUserOrGroup}}+ @icon="user-plus"+ @translatedLabel={{i18n "discourse_post_event.invite"}}/></dropdown.item>{{/if}}- {{#if @event.isClosed}}- <dropdown.item class="open-event">+ {{#if this.canSeeUpcomingEvents}}+ <dropdown.item class="upcoming-events"><DButtonclass="btn-transparent"- @action={{this.openEvent}}- @disabled={{this.isSavingEvent}}- @icon="unlock"- @label="discourse_post_event.open_event"+ @action={{this.upcomingEvents}}+ @icon="far-calendar-plus"+ @translatedLabel={{i18n+ "discourse_post_event.upcoming_events.title"+ }}/></dropdown.item>- {{else}}- <dropdown.item class="edit-event">+ {{/if}}++ {{#if this.shouldShowParticipants}}+ <dropdown.item class="show-all-participants"><DButtonclass="btn-transparent"- @action={{this.editPostEvent}}- @icon="pencil"- @label="discourse_post_event.edit_event"+ @action={{this.showParticipants}}+ @icon="user-group"+ @label="discourse_post_event.show_participants"/></dropdown.item>- {{#unless @event.isExpired}}- <dropdown.item class="close-event">+ <dropdown.divider />+ {{/if}}+ {{#if this.canActOnEvent}}+ <dropdown.item class="export-event">+ <DButton+ class="btn-transparent"+ @action={{this.exportPostEvent}}+ @icon="file-csv"+ @label="discourse_post_event.export_event"+ />+ </dropdown.item>++ {{#if this.canBulkInvite}}+ <dropdown.item class="bulk-invite"><DButton- class="btn-transparent --danger"- @action={{this.closeEvent}}+ class="btn-transparent"+ @action={{this.bulkInvite}}+ @icon="file-arrow-up"+ @label="discourse_post_event.bulk_invite"+ />+ </dropdown.item>+ {{/if}}++ {{#if @event.isClosed}}+ <dropdown.item class="open-event">+ <DButton+ class="btn-transparent"+ @action={{this.openEvent}}@disabled={{this.isSavingEvent}}- @icon="xmark"- @label="discourse_post_event.close_event"+ @icon="unlock"+ @label="discourse_post_event.open_event"+ />+ </dropdown.item>+ {{else}}+ <dropdown.item class="edit-event">+ <DButton+ class="btn-transparent"+ @action={{this.editPostEvent}}+ @icon="pencil"+ @label="discourse_post_event.edit_event"+ />+ </dropdown.item>++ {{#unless @event.isExpired}}+ <dropdown.item class="close-event">+ <DButton+ class="btn-transparent --danger"+ @action={{this.closeEvent}}+ @disabled={{this.isSavingEvent}}+ @icon="xmark"+ @label="discourse_post_event.close_event"+ />+ </dropdown.item>+ {{/unless}}+ {{/if}}++ {{#if this.canManageRecording}}+ <dropdown.item class="manage-recording">+ <DButton+ class="btn-transparent"+ @action={{this.manageRecording}}+ @icon="video"+ @label={{if+ @event.recordingUrl+ "discourse_post_event.recording_modal.edit_title"+ "discourse_post_event.recording.add"+ }}/></dropdown.item>- {{/unless}}+ {{/if}}{{/if}}- {{/if}}- </DDropdownMenu>- </:content>- </DMenu>+ </DDropdownMenu>+ </:content>+ </DMenu>+ {{/if}}</template>}diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/onebox-embed.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/onebox-embed.gjsnew file mode 100644index 00000000000..71a9622ab94--- /dev/null+++ b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/onebox-embed.gjs@@ -0,0 +1,70 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { service } from "@ember/service";+import { trustHTML } from "@ember/template";+import { withPluginApi } from "discourse/lib/plugin-api";+import { optionalRequire } from "discourse/lib/utilities";++// Renders a server-cooked onebox inside the event card. For supported video+// providers we hand the resolved attributes to lazy-videos' LazyVideo component+// (the post-stream decorator that normally does this doesn't reach our card);+// otherwise we render the onebox as-is.+export default class DiscoursePostEventOneboxEmbed extends Component {+ @service siteSettings;++ // Resolved at runtime: lazy-videos may not be installed, and resolving at+ // module load can return false before the plugin's modules are registered.+ get lazyVideo() {+ return optionalRequire(+ "discourse/plugins/discourse-lazy-videos/discourse/components/lazy-video"+ );+ }++ get videoAttributes() {+ const html = this.args.html;+ const getVideoAttributes = optionalRequire(+ "discourse/plugins/discourse-lazy-videos/lib/lazy-video-attributes"+ );+ if (!html || !getVideoAttributes || !this.lazyVideo) {+ return null;+ }++ const container = new DOMParser()+ .parseFromString(html, "text/html")+ .querySelector(".lazy-video-container");+ if (!container) {+ return null;+ }++ const attributes = getVideoAttributes(container);+ return this.siteSettings[`lazy_${attributes.providerName}_enabled`]+ ? attributes+ : null;+ }++ get oneboxHtml() {+ return this.videoAttributes ? null : trustHTML(this.args.html ?? "");+ }++ // Once playback starts the post has to stay rendered: cloaking it tears down+ // the component holding the video, taking any joined session with it.+ @action+ preventCloak() {+ const postId = this.args.post?.id;++ if (postId) {+ withPluginApi((api) => api.preventCloak(postId));+ }+ }++ <template>+ {{#if this.videoAttributes}}+ <this.lazyVideo+ @onLoadedVideo={{this.preventCloak}}+ @videoAttributes={{this.videoAttributes}}+ />+ {{else}}+ {{this.oneboxHtml}}+ {{/if}}+ </template>+}diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/recording.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/recording.gjsnew file mode 100644index 00000000000..16283d26e0e--- /dev/null+++ b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/recording.gjs@@ -0,0 +1,60 @@+import Component from "@glimmer/component";+import { action } from "@ember/object";+import { service } from "@ember/service";+import { prefixProtocol } from "discourse/lib/url";+import DButton from "discourse/ui-kit/d-button";+import PostEventRecording from "../modal/post-event-recording.gjs";+import OneboxEmbed from "./onebox-embed.gjs";++export default class DiscoursePostEventRecording extends Component {+ @service currentUser;+ @service modal;++ get recordingUrl() {+ return prefixProtocol(this.args.event.recordingUrl);+ }++ get canAddRecording() {+ const { event } = this.args;++ return (+ !!this.currentUser &&+ event.canActOnDiscoursePostEvent &&+ event.livestream &&+ event.isExpired+ );+ }++ @action+ addRecording() {+ this.modal.show(PostEventRecording, { model: { event: this.args.event } });+ }++ <template>+ {{#if @event.recordingOnebox}}+ <section class="event__section event-recording">+ <OneboxEmbed @html={{@event.recordingOnebox}} @post={{@post}} />+ </section>+ {{else if @event.recordingUrl}}+ <section class="event__section event-recording">+ <DButton+ class="btn-primary event-recording__watch"+ rel="noopener noreferrer"+ target="_blank"+ @href={{this.recordingUrl}}+ @icon="play"+ @label="discourse_post_event.recording.watch"+ />+ </section>+ {{else if this.canAddRecording}}+ <section class="event__section event-recording">+ <DButton+ class="btn-default event-recording__add"+ @action={{this.addRecording}}+ @icon="plus"+ @label="discourse_post_event.recording.add"+ />+ </section>+ {{/if}}+ </template>+}diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/status.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/status.gjsindex 68cc9ca2239..4ec195c1c27 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/status.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/status.gjs@@ -19,6 +19,9 @@ import CalendarPrompt from "./calendar-prompt.gjs";const statusButtonClass = (selected) =>selected ? "btn-primary" : "btn-default";+const goingButtonClass = (selected) =>+ selected ? "btn-success" : "btn-default";+const GoingDropdown = <template><DDropdownMenu as |dropdown|><dropdown.item@@ -285,7 +288,7 @@ export default class DiscoursePostEventStatus extends Component {<DMenuclass={{dConcatClass"going-button"- (statusButtonClass this.isGoing)+ (goingButtonClass this.isGoing)}}@disabled={{this.goingButtonDisabled}}@icon={{this.goingTriggerIcon}}@@ -301,7 +304,7 @@ export default class DiscoursePostEventStatus extends Component {{{else}}<DComboButtonclass="going-button"- @btnTypeClass={{statusButtonClass this.isGoing}}+ @btnTypeClass={{goingButtonClass this.isGoing}}@hasMenu={{true}}as |combo|>@@ -329,7 +332,7 @@ export default class DiscoursePostEventStatus extends Component {<DButtonclass={{dConcatClass"going-button"- (statusButtonClass this.isGoing)+ (goingButtonClass this.isGoing)}}@action={{fn this.changeWatchingInviteeStatus "going"}}@ariaPressed={{this.isGoing}}diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/url.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/url.gjsindex 1842a2943cc..55905b6e497 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/url.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/url.gjs@@ -1,5 +1,6 @@import Component from "@glimmer/component";import { prefixProtocol } from "discourse/lib/url";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import dIcon from "discourse/ui-kit/helpers/d-icon";export default class DiscoursePostEventUrl extends Component {@@ -14,7 +15,12 @@ export default class DiscoursePostEventUrl extends Component {<template>{{#if @url}}- <section class="event__section event-url">+ <section+ class={{dConcatClass+ "event__section event-url"+ (if @superseded "--superseded")+ }}+ >{{dIcon "link"}}<aclass="url"diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/event-node-view.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/event-node-view.gjsindex 7374fa9a72d..03f787fb219 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/event-node-view.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/event-node-view.gjs@@ -31,6 +31,7 @@ const CLEARABLE_ATTRS = ["image","closed","hosts",+ "recording",];export default class EventNodeView extends Component {diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/modal/post-event-builder.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/modal/post-event-builder.gjsindex 1574172092d..a8f0beaf2b5 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/modal/post-event-builder.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/modal/post-event-builder.gjs@@ -34,6 +34,7 @@ import {isLivestreamUrl,livestreamSource,reconcileDefaultReminder,+ showRecordingField,} from "../../lib/raw-event-helper.js";import CompactEventEditor from "../compact-event-editor.gjs";@@ -138,6 +139,17 @@ export default class PostEventBuilder extends Component {);}+ get showRecording() {+ return showRecordingField({+ recording: this.event.recordingUrl,+ livestream: this.event.livestream,+ startsAt: this.startsAt,+ endsAt: this.endsAt,+ recurrence: this.event.recurrence,+ recurrenceUntil: this.event.recurrenceUntil,+ });+ }+get availableRecurrences() {const { weekday, ordinal } = recurrenceContext(this.startsAt || moment());@@ -234,6 +246,7 @@ export default class PostEventBuilder extends Component {livestream: !!this.event.livestream,minimal: !!this.event.minimal,url: this.event.url ?? null,+ recording: this.event.recordingUrl ?? null,image:this.event.imageUpload?.short_url ??this.event.imageUpload?.url ??@@ -388,6 +401,7 @@ export default class PostEventBuilder extends Component {this.event.livestream = state.livestream;this.event.minimal = state.minimal;this.event.url = state.url;+ this.event.recordingUrl = state.recording;this.event.recurrence = state.recurrence;this.event.recurrenceUntil = state.recurrenceUntil;this.event.reminders = state.reminders;@@ -664,6 +678,7 @@ export default class PostEventBuilder extends Component {showLocalTime: !!this.event.showLocalTime,chatEnabled: !!this.event.chatEnabled,livestream: !!this.event.livestream,+ recordingUrl: this.event.recordingUrl ?? "",attendanceMode: this.attendanceMode,maxAttendees: this.event.maxAttendees ?? null,eventType:@@ -900,6 +915,25 @@ export default class PostEventBuilder extends Component {</form.Field>{{/if}}+ {{#if this.showRecording}}+ <form.Field+ @format="full"+ @name="recordingUrl"+ @onSet={{fn this.syncFieldToEvent "recordingUrl"}}+ @title={{i18n+ "discourse_post_event.builder_modal.recording.label"+ }}+ @type="input-url"+ as |field|+ >+ <field.Control+ placeholder={{i18n+ "discourse_post_event.builder_modal.recording.placeholder"+ }}+ />+ </form.Field>+ {{/if}}+<form.Field@format="full"@name="description"diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/modal/post-event-recording.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/modal/post-event-recording.gjsnew file mode 100644index 00000000000..54284b82dbd--- /dev/null+++ b/plugins/discourse-events/assets/javascripts/discourse/components/modal/post-event-recording.gjs@@ -0,0 +1,98 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { action } from "@ember/object";+import { service } from "@ember/service";+import Form from "discourse/components/form";+import { extractError } from "discourse/lib/ajax-error";+import DModal from "discourse/ui-kit/d-modal";+import { i18n } from "discourse-i18n";+import { setEventAttribute } from "../../lib/raw-event-helper.js";+import { savePostRaw } from "../../lib/save-post-raw.js";++// Sets just the event's recording link, so adding one after the stream does+// not mean going through (and rewriting) the whole event.+export default class PostEventRecording extends Component {+ @service store;++ @tracked flash = null;++ data = { recordingUrl: this.event.recordingUrl ?? "" };++ get event() {+ return this.args.model.event;+ }++ get title() {+ return this.event.recordingUrl+ ? i18n("discourse_post_event.recording_modal.edit_title")+ : i18n("discourse_post_event.recording_modal.add_title");+ }++ @action+ async save(data) {+ await this.#update(data.recordingUrl);+ }++ @action+ async remove() {+ await this.#update(null);+ }++ async #update(recordingUrl) {+ this.flash = null;++ try {+ const post = await this.store.find("post", this.event.id);+ const raw = setEventAttribute(post.raw, "recording", recordingUrl);+ if (!raw) {+ this.flash = i18n("discourse_post_event.recording_modal.no_event");+ return;+ }++ await savePostRaw(+ post,+ raw,+ i18n("discourse_post_event.recording_modal.edit_reason")+ );+ this.args.closeModal();+ } catch (e) {+ this.flash = extractError(e);+ }+ }++ <template>+ <DModal+ class="post-event-recording-modal"+ @closeModal={{@closeModal}}+ @flash={{this.flash}}+ @inline={{@inline}}+ @title={{this.title}}+ >+ <:body>+ <Form @data={{this.data}} @onSubmit={{this.save}} as |form|>+ <form.Field+ @format="full"+ @name="recordingUrl"+ @title={{i18n "discourse_post_event.recording_modal.label"}}+ @type="input-url"+ @validation="required|url"+ as |field|+ >+ <field.Control autofocus placeholder="https://" />+ </form.Field>++ <form.Actions>+ <form.Submit @label="discourse_post_event.recording_modal.save" />+ {{#if this.event.recordingUrl}}+ <form.Button+ class="btn-transparent --danger"+ @action={{this.remove}}+ @label="discourse_post_event.recording_modal.remove"+ />+ {{/if}}+ </form.Actions>+ </Form>+ </:body>+ </DModal>+ </template>+}diff --git a/plugins/discourse-events/assets/javascripts/discourse/lib/raw-event-helper.js b/plugins/discourse-events/assets/javascripts/discourse/lib/raw-event-helper.jsindex 73ce3587abf..70dabf1218b 100644--- a/plugins/discourse-events/assets/javascripts/discourse/lib/raw-event-helper.js+++ b/plugins/discourse-events/assets/javascripts/discourse/lib/raw-event-helper.js@@ -72,6 +72,27 @@ export function livestreamSource(location, url) {return location?.trim() ? location : url;}+// Mirrors `Event#expired?` on the server.+export function hasEventEnded({+ startsAt,+ endsAt,+ recurrence,+ recurrenceUntil,+}) {+ if (recurrence) {+ return !!recurrenceUntil && moment().isAfter(moment(recurrenceUntil));+ }++ const end = endsAt || (startsAt && moment(startsAt).endOf("day"));+ return !!end && moment().isAfter(end);+}++// The recording only becomes relevant once there is something to record, but+// an existing link stays editable even if the dates move forward.+export function showRecordingField({ recording, livestream, ...dates }) {+ return !!recording || (!!livestream && hasEventEnded(dates));+}+export function eventDateInTimezone(value, timezone) {if (!value) {return null;@@ -249,6 +270,10 @@ export function buildParams(startsAt, endsAt, event, siteSettings) {params.url = event.url;}+ if (event.recordingUrl && event.recordingUrl.trim()) {+ params.recording = event.recordingUrl.trim();+ }+if (event.timezone) {params.timezone = event.timezone;}@@ -381,6 +406,26 @@ export function buildEventBlock(params, description) {return `[event ${buildBBCodeAttrs(attrs)}]\n${desc}[/event]`;}+// Changes a single attribute of the event block, leaving everything else in+// the raw as written. A blank value removes the attribute.+export function setEventAttribute(raw, name, value) {+ const parsed = parseEventBlock(raw);+ if (!parsed) {+ return false;+ }++ const attrs = { ...parsed.attrs };+ if (value?.trim()) {+ attrs[name] = value.trim();+ } else {+ delete attrs[name];+ }++ return raw.replace(parsed.full, () =>+ buildEventBlock(attrs, parsed.description)+ );+}+export function getCustomFieldNames(siteSettings) {return siteSettings.discourse_post_event_allowed_custom_fields.split("|")@@ -411,6 +456,7 @@ export function defaultEventState() {livestream: false,minimal: false,url: null,+ recording: null,image: null,allowedGroups: null,closed: false,@@ -450,6 +496,7 @@ export function parseEventAttrs(livestream: attrs.livestream === "true",minimal: attrs.minimal === "true",url: attrs.url || null,+ recording: attrs.recording || null,image: attrs.image || null,allowedGroups: attrs.allowedGroups || null,closed: attrs.closed === "true",@@ -467,6 +514,7 @@ export function stateToEventInput(state) {name: state.name,location: state.location,url: state.url,+ recordingUrl: state.recording,recurrence: state.recurrence,recurrenceUntil: state.recurrenceUntil,showLocalTime: state.showLocalTime,diff --git a/plugins/discourse-events/assets/javascripts/discourse/lib/save-post-raw.js b/plugins/discourse-events/assets/javascripts/discourse/lib/save-post-raw.jsnew file mode 100644index 00000000000..b408c7d3452--- /dev/null+++ b/plugins/discourse-events/assets/javascripts/discourse/lib/save-post-raw.js@@ -0,0 +1,11 @@+import { cook } from "discourse/lib/text";++export async function savePostRaw(post, raw, editReason) {+ const cooked = await cook(raw);++ return await post.save({+ raw,+ cooked: cooked.string,+ edit_reason: editReason,+ });+}diff --git a/plugins/discourse-events/assets/javascripts/discourse/lib/show-post-event-editor.js b/plugins/discourse-events/assets/javascripts/discourse/lib/show-post-event-editor.jsnew file mode 100644index 00000000000..e9fb9f61ba0--- /dev/null+++ b/plugins/discourse-events/assets/javascripts/discourse/lib/show-post-event-editor.js@@ -0,0 +1,38 @@+import { i18n } from "discourse-i18n";+import PostEventBuilder from "../components/modal/post-event-builder.gjs";+import { buildParams, removeEvent, replaceRaw } from "./raw-event-helper.js";+import { savePostRaw } from "./save-post-raw.js";++// Opens the event builder against a published event, writing changes back to+// the post's raw.+export function showPostEventEditor({ modal, store, event }) {+ return modal.show(PostEventBuilder, {+ model: {+ event,+ onDelete: async (deletedEvent) => {+ const post = await store.find("post", deletedEvent.id);++ return await savePostRaw(+ post,+ removeEvent(post.raw),+ i18n("discourse_post_event.destroy_event")+ );+ },+ onUpdate: async (startsAt, endsAt, updatedEvent, siteSettings) => {+ const post = await store.find("post", updatedEvent.id);+ const newRaw = replaceRaw(+ buildParams(startsAt, endsAt, updatedEvent, siteSettings),+ post.raw+ );++ if (newRaw) {+ return await savePostRaw(+ post,+ newRaw,+ i18n("discourse_post_event.edit_reason")+ );+ }+ },+ },+ });+}diff --git a/plugins/discourse-events/assets/javascripts/discourse/models/discourse-post-event-event.js b/plugins/discourse-events/assets/javascripts/discourse/models/discourse-post-event-event.jsindex 8db86dce85f..0d97842a473 100644--- a/plugins/discourse-events/assets/javascripts/discourse/models/discourse-post-event-event.js+++ b/plugins/discourse-events/assets/javascripts/discourse/models/discourse-post-event-event.js@@ -93,6 +93,8 @@ export default class DiscoursePostEventEvent {@tracked livestreamUrl;@tracked livestreamChatChannelId;@tracked isZoomLivestream;+ @tracked recordingUrl;+ @tracked recordingOnebox;@tracked canUpdateAttendance;@tracked canActOnDiscoursePostEvent;@tracked shouldDisplayInvitees;@@ -148,6 +150,8 @@ export default class DiscoursePostEventEvent {this.livestreamUrl = args.livestream_url;this.livestreamChatChannelId = args.livestream_chat_channel_id;this.isZoomLivestream = args.is_zoom_livestream;+ this.recordingUrl = args.recording_url;+ this.recordingOnebox = args.recording_onebox;this.maxAttendees = args.max_attendees;this.atCapacity = args.at_capacity;this.recurrence = args.recurrence;@@ -283,6 +287,8 @@ export default class DiscoursePostEventEvent {this.livestreamUrl = this.location || this.url;this.livestreamChatChannelId = event.livestreamChatChannelId;this.isZoomLivestream = event.isZoomLivestream;+ this.recordingUrl = event.recordingUrl;+ this.recordingOnebox = event.recordingOnebox;this.rrule = event.rrule;this.maxAttendees = event.maxAttendees;this.atCapacity = event.atCapacity;diff --git a/plugins/discourse-events/assets/javascripts/discourse/pre-initializers/rich-editor-extension.js b/plugins/discourse-events/assets/javascripts/discourse/pre-initializers/rich-editor-extension.jsindex c3e97a00800..36e14acd63d 100644--- a/plugins/discourse-events/assets/javascripts/discourse/pre-initializers/rich-editor-extension.js+++ b/plugins/discourse-events/assets/javascripts/discourse/pre-initializers/rich-editor-extension.js@@ -32,6 +32,7 @@ export const EVENT_ATTRIBUTES = {allDay: { default: null },image: { default: null },hosts: { default: null },+ recording: { default: null },};/** @returns {RichEditorExtension} */diff --git a/plugins/discourse-events/assets/javascripts/discourse/services/embeddable-chat.gjs b/plugins/discourse-events/assets/javascripts/discourse/services/embeddable-chat.gjsindex 2c8ab11a561..4c7209961a9 100644--- a/plugins/discourse-events/assets/javascripts/discourse/services/embeddable-chat.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/services/embeddable-chat.gjs@@ -58,6 +58,7 @@ export default class EmbeddableChat extends Service {get showLivestreamHeaderChatIcon() {return (this.isMobileViewport &&+ this.livestreamChatActive &&!!this.chatChannelId &&!this.hasActiveZoomLivestream);@@ -90,14 +91,14 @@ export default class EmbeddableChat extends Service {return this.topic?.chat_channel_id;}- get topicHasLivestream() {- return this.topic?.has_livestream;+ get livestreamChatActive() {+ return !!this.topic?.livestream_chat_active;}get useLivestreamLayout() {return (this.router.currentRouteName?.startsWith("topic.") &&- this.topicHasLivestream &&+ this.livestreamChatActive &&!!this.chatChannelId &&!this.isChannelOpenInDrawer);@@ -117,7 +118,11 @@ export default class EmbeddableChat extends Service {this.currentUser &&this.userCanChat) {- if (this.isPathAllowed && this.chatChannelId) {+ if (+ this.isPathAllowed &&+ this.chatChannelId &&+ this.livestreamChatActive+ ) {return !this.isChannelOpenInDrawer;}}diff --git a/plugins/discourse-events/assets/stylesheets/common/composer-event-node-view.scss b/plugins/discourse-events/assets/stylesheets/common/composer-event-node-view.scssindex e1f9124a385..744e85bd671 100644--- a/plugins/discourse-events/assets/stylesheets/common/composer-event-node-view.scss+++ b/plugins/discourse-events/assets/stylesheets/common/composer-event-node-view.scss@@ -128,6 +128,7 @@.composer-event__dates,.composer-event__location,.composer-event__url,+ .composer-event__recording,.composer-event__attendees,.composer-event__reminder,.composer-event__livestream {@@ -377,7 +378,8 @@ input.composer-event__time-input[type="time"] {}.composer-event__location-input,-.composer-event__url-input {+.composer-event__url-input,+.composer-event__recording-input {width: 100%;cursor: text;}diff --git a/plugins/discourse-events/assets/stylesheets/common/discourse-post-event.scss b/plugins/discourse-events/assets/stylesheets/common/discourse-post-event.scssindex 84c2ce7aebb..b448b506cc1 100644--- a/plugins/discourse-events/assets/stylesheets/common/discourse-post-event.scss+++ b/plugins/discourse-events/assets/stylesheets/common/discourse-post-event.scss@@ -76,6 +76,34 @@ $show-interested: inherit;section:last-child {padding-bottom: 0.75em;}++ &.is-ended {+ background: var(--primary-very-low);++ .event-image img {+ filter: grayscale(1);+ opacity: 0.6;+ }++ .event-date {+ border-color: var(--primary-low-mid);++ .month,+ .day {+ color: var(--primary-medium);+ }+ }++ .event-info .name,+ .event-info .name a {+ color: var(--primary-high);+ }++ .avatar-flair,+ .event-invitees-icon .going {+ background: var(--primary-very-low);+ }+ }}.event-header {@@ -92,6 +120,10 @@ $show-interested: inherit;display: flex;gap: var(--space-2);margin-left: auto;++ &:not(:has(*)) {+ display: none;+ }}}@@ -129,6 +161,7 @@ $show-interested: inherit;flex-direction: column;min-width: 0;margin-right: 0.5rem;+ margin-top: calc(-1 * var(--space-1));.name {font-size: var(--font-up-2);@@ -411,6 +444,25 @@ $show-interested: inherit;}}+ .event-location.--superseded,+ .event-url.--superseded {+ &,+ a,+ .url,+ > .d-icon {+ color: var(--primary-medium);+ }+ }++ .event-recording {+ padding-top: 0;+ }++ .event-invitees + .event-recording {+ padding-top: var(--space-2);+ padding-left: var(--space-6);+ }+.cooked-date,.participants,.event-url .url {@@ -425,6 +477,12 @@ $show-interested: inherit;grid-template-columns: 3em 1fr;column-gap: 1em;align-items: center;++ > .d-icon {+ color: var(--primary-high);+ margin: 0 auto;+ padding: 0;+ }}p.no-rsvp-description {diff --git a/plugins/discourse-events/assets/stylesheets/common/event-calendar-prompt.scss b/plugins/discourse-events/assets/stylesheets/common/event-calendar-prompt.scssindex 9e1adbaf4ed..0acb6b6b469 100644--- a/plugins/discourse-events/assets/stylesheets/common/event-calendar-prompt.scss+++ b/plugins/discourse-events/assets/stylesheets/common/event-calendar-prompt.scss@@ -2,7 +2,7 @@.event-calendar-prompt {border-top: 1px solid var(--primary-low);- padding: 1em;+ padding: var(--space-2) var(--space-4) var(--space-4);background: var(--success-very-low);&__heading {@@ -37,6 +37,10 @@text-decoration: underline;text-underline-offset: 0.15em;}++ + .event__section.event-livestream {+ padding-top: var(--space-3);+ }}.event-reminder-preferences {diff --git a/plugins/discourse-events/assets/stylesheets/common/livestream.scss b/plugins/discourse-events/assets/stylesheets/common/livestream.scssindex cf8b8c118f7..759589deac7 100644--- a/plugins/discourse-events/assets/stylesheets/common/livestream.scss+++ b/plugins/discourse-events/assets/stylesheets/common/livestream.scss@@ -266,3 +266,17 @@ body.discourse-calendar-livestream-zoom-full {display: none;}}++.cooked .d-wrap[data-wrap="livestream-chat-transcript"] {+ max-height: min(30rem, 60vh);+ overflow-y: auto;+ overscroll-behavior: contain;++ > .chat-transcript:first-child {+ margin-top: 0;+ }++ > .chat-transcript:last-child {+ margin-bottom: 0;+ }+}diff --git a/plugins/discourse-events/config/locales/client.en.yml b/plugins/discourse-events/config/locales/client.en.ymlindex 8a1dacd8339..87da513190f 100644--- a/plugins/discourse-events/config/locales/client.en.yml+++ b/plugins/discourse-events/config/locales/client.en.yml@@ -481,7 +481,7 @@ en:one: "%{count} user invited"other: "%{count} users invited"event:- expired: "Expired"+ expired: "Ended"closed: "Closed"full: "Full"status:@@ -494,12 +494,24 @@ en:private:title: "Private"description: "A private event can only be joined by invited users."+ recording:+ watch: "Watch recording"+ add: "Add recording link"+ recording_modal:+ add_title: "Add recording"+ edit_title: "Edit recording"+ label: "Recording link"+ save: "Save"+ remove: "Remove recording"+ edit_reason: "Recording link updated"+ no_event: "The event could not be found in its post."composer:name_placeholder: "Event name"end_date_placeholder: "End date"location_or_url_placeholder: "Add location or URL"location_placeholder: "Add location"url_placeholder: "Add URL"+ recording_placeholder: "Add a link to the recording"max_attendees_placeholder: "Unlimited attendees"max_attendees_display:one: "Max %{count} attendee"@@ -611,6 +623,9 @@ en:livestream:label: "Livestream"checkbox_label: "Embed the URL as a video and open livestream chat for attendees"+ recording:+ label: "Recording"+ placeholder: "Add a link to the recording"location:label: "Location"label_or_url: "Location or URL"diff --git a/plugins/discourse-events/config/locales/server.en.yml b/plugins/discourse-events/config/locales/server.en.ymlindex 5218402343e..f66bff8791f 100644--- a/plugins/discourse-events/config/locales/server.en.yml+++ b/plugins/discourse-events/config/locales/server.en.yml@@ -149,6 +149,12 @@ en:livestream:chat:topic_reference_message: "This channel is for the event [%{title}](%{url}) — visit the topic for details and to RSVP."+ transcript_heading: "Chat transcript"+ transcript_heading_dated: "Chat transcript for %{date}"+ transcript_edit_reason: "Added the livestream chat transcript"+ transcript_earlier_messages:+ one: "%{count} earlier message is in the [chat channel](%{url})."+ other: "%{count} earlier messages are in the [chat channel](%{url})."zoom:frame_title: "Zoom webinar"frame_join: "Join webinar"@@ -193,6 +199,7 @@ en:invalid_recurrence: "Recurrence must be one of: %{recurrences}."invalid_timezone: "Timezone not recognized."invalid_url: "URL must be a valid web address."+ invalid_recording_url: "Recording must be a valid web address."acting_user_not_allowed_to_create_event: "Current user is not allowed to create events."acting_user_not_allowed_to_act_on_this_event: "Current user is not allowed to act on this event."invalid_allowed_groups: "Invalid allowed groups."@@ -210,6 +217,8 @@ en:length: "Event URL is limited to %{maximum} characters."location:length: "Event location is limited to %{maximum} characters."+ recording:+ length: "Event recording link is limited to %{maximum} characters."discourse_push_notifications:popup:event_reminder: "Event Reminder"diff --git a/plugins/discourse-events/db/migrate/20261008173326_add_recording_url_to_discourse_post_event_events.rb b/plugins/discourse-events/db/migrate/20261008173326_add_recording_url_to_discourse_post_event_events.rbnew file mode 100644index 00000000000..9da13238c15--- /dev/null+++ b/plugins/discourse-events/db/migrate/20261008173326_add_recording_url_to_discourse_post_event_events.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++class AddRecordingUrlToDiscoursePostEventEvents < ActiveRecord::Migration[8.0]+ def change+ add_column :discourse_post_event_events, :recording_url, :string, limit: 1000+ end+enddiff --git a/plugins/discourse-events/db/migrate/20261008184751_add_last_transcribed_message_id_to_livestream_topic_chat_channels.rb b/plugins/discourse-events/db/migrate/20261008184751_add_last_transcribed_message_id_to_livestream_topic_chat_channels.rbnew file mode 100644index 00000000000..c6019c6884f--- /dev/null+++ b/plugins/discourse-events/db/migrate/20261008184751_add_last_transcribed_message_id_to_livestream_topic_chat_channels.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++class AddLastTranscribedMessageIdToLivestreamTopicChatChannels < ActiveRecord::Migration[8.0]+ def change+ add_column :livestream_topic_chat_channels, :last_transcribed_message_id, :bigint+ end+enddiff --git a/plugins/discourse-events/db/migrate/20261014231432_add_closed_on_event_end_to_livestream_topic_chat_channels.rb b/plugins/discourse-events/db/migrate/20261014231432_add_closed_on_event_end_to_livestream_topic_chat_channels.rbnew file mode 100644index 00000000000..fbce00af2a5--- /dev/null+++ b/plugins/discourse-events/db/migrate/20261014231432_add_closed_on_event_end_to_livestream_topic_chat_channels.rb@@ -0,0 +1,11 @@+# frozen_string_literal: true++class AddClosedOnEventEndToLivestreamTopicChatChannels < ActiveRecord::Migration[8.0]+ def change+ add_column :livestream_topic_chat_channels,+ :closed_on_event_end,+ :boolean,+ default: false,+ null: false+ end+enddiff --git a/plugins/discourse-events/jobs/regular/discourse_post_event/publish_livestream_chat_transcript.rb b/plugins/discourse-events/jobs/regular/discourse_post_event/publish_livestream_chat_transcript.rbnew file mode 100644index 00000000000..23b63507326--- /dev/null+++ b/plugins/discourse-events/jobs/regular/discourse_post_event/publish_livestream_chat_transcript.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++module Jobs+ class PublishLivestreamChatTranscript < ::Jobs::Base+ MAX_ATTEMPTS = 3++ def execute(args)+ attempts = 0+ begin+ DiscourseEvents::Livestream::PublishChatTranscript.call(+ params: {+ event_date_id: args[:event_date_id],+ },+ )+ rescue DiscourseEvents::Livestream::PublishChatTranscript::EventPostChanged+ retry if (attempts += 1) < MAX_ATTEMPTS+ raise+ end+ end+ end+enddiff --git a/plugins/discourse-events/jobs/regular/discourse_post_event/warm_event_onebox.rb b/plugins/discourse-events/jobs/regular/discourse_post_event/warm_event_onebox.rbnew file mode 100644index 00000000000..66683fa99c4--- /dev/null+++ b/plugins/discourse-events/jobs/regular/discourse_post_event/warm_event_onebox.rb@@ -0,0 +1,22 @@+# frozen_string_literal: true++module Jobs+ # Warms the cached onebox of one of an event's links so the event card can embed+ # it, skipping links the event no longer has by the time the job runs.+ class WarmEventOnebox < ::Jobs::Base+ def execute(args)+ url = args[:url]+ return if url.blank?++ event = DiscourseEvents::Events::Event.find_by(id: args[:event_id])+ return if event.blank? || link(event) != url+ event.warm_onebox!(url)+ end++ private++ def link(event)+ raise NotImplementedError+ end+ end+enddiff --git a/plugins/discourse-events/jobs/regular/discourse_post_event/warm_livestream_onebox.rb b/plugins/discourse-events/jobs/regular/discourse_post_event/warm_livestream_onebox.rbindex 4919de10e6c..2302ab56a82 100644--- a/plugins/discourse-events/jobs/regular/discourse_post_event/warm_livestream_onebox.rb+++ b/plugins/discourse-events/jobs/regular/discourse_post_event/warm_livestream_onebox.rb@@ -1,16 +1,12 @@# frozen_string_literal: truemodule Jobs- # Warms the cached onebox for a livestream event's URL so the event card can- # render the embedded (lazy) video from EventSerializer#livestream_onebox.- class WarmLivestreamOnebox < ::Jobs::Base- def execute(args)- url = args[:url]- return if url.blank?+ # Feeds EventSerializer#livestream_onebox.+ class WarmLivestreamOnebox < WarmEventOnebox+ private- event = DiscourseEvents::Events::Event.find_by(id: args[:event_id])- return if event.blank? || event.livestream_url != url- event.warm_livestream_onebox!+ def link(event)+ event.livestream_url if event.livestream?endendenddiff --git a/plugins/discourse-events/jobs/regular/discourse_post_event/warm_recording_onebox.rb b/plugins/discourse-events/jobs/regular/discourse_post_event/warm_recording_onebox.rbnew file mode 100644index 00000000000..823b0782b9a--- /dev/null+++ b/plugins/discourse-events/jobs/regular/discourse_post_event/warm_recording_onebox.rb@@ -0,0 +1,12 @@+# frozen_string_literal: true++module Jobs+ # Feeds EventSerializer#recording_onebox.+ class WarmRecordingOnebox < WarmEventOnebox+ private++ def link(event)+ event.recording_link+ end+ end+enddiff --git a/plugins/discourse-events/jobs/scheduled/monitor_event_dates.rb b/plugins/discourse-events/jobs/scheduled/monitor_event_dates.rbindex d85d8d974e4..b9bdccb9513 100644--- a/plugins/discourse-events/jobs/scheduled/monitor_event_dates.rb+++ b/plugins/discourse-events/jobs/scheduled/monitor_event_dates.rb@@ -12,6 +12,7 @@ module Jobs.find_each do |event_date|send_reminder(event_date)trigger_events(event_date)+ open_livestream_chat(event_date)finish(event_date)endend@@ -41,6 +42,25 @@ module Jobsendend+ # A recurring livestream's chat only docks around each occurrence, so open+ # pages are told to reload once the next one opens; `finish` does the+ # same when it ends.+ def open_livestream_chat(event_date)+ event = event_date.event+ return if !event.livestream? || !event.recurring?+ return if event_date.opens_at > Time.current+ if !Discourse.redis.set("livestream_chat_opened:#{event_date.id}", 1, nx: true, ex: 2.days)+ return+ end++ topic = event.post.topic+ MessageBus.publish(+ "/topic/#{topic.id}",+ { reload_topic: true },+ topic.secure_audience_publish_messages,+ )+ end+def finish(event_date)return if !event_date.ended?diff --git a/plugins/discourse-events/lib/discourse_events/events/parser.rb b/plugins/discourse-events/lib/discourse_events/events/parser.rbindex 511b9a20532..91a93f1a4e6 100644--- a/plugins/discourse-events/lib/discourse_events/events/parser.rb+++ b/plugins/discourse-events/lib/discourse_events/events/parser.rb@@ -24,6 +24,7 @@ module DiscourseEvents:"all-day",:image,:hosts,+ :recording,]LEGACY_ESCAPED_ATTRS = %w[data-location]@@ -59,11 +60,13 @@ module DiscourseEventsevent ||= {}value = CGI.unescapeHTML(value) if LEGACY_ESCAPED_ATTRS.include?(name)event[name.sub("data-", "").to_sym] = case name- when "data-name", "data-url", "data-image", "data-location"+ when "data-name", "data-url", "data-image", "data-location", "data-recording"valueelseCGI.escapeHTML(value)end+ # A custom field sharing the name would overwrite the parsed value.+ nextendvalid_custom_fields.each do |valid_custom_field|@@ -158,6 +161,15 @@ module DiscourseEventsfalseend+ # Stricter than `valid_url?`: a recording is only ever opened in a+ # browser tab, so mailto and custom schemes have no business here.+ def self.valid_web_url?(value)+ value = value.to_s.strip+ return true if value.blank?+ return false if !valid_url?(value)+ !value.match?(SCHEME_PREFIX) || value.match?(%r{\Ahttps?://}i)+ end+def self.normalize_link(value)value.to_s.strip.downcase.sub(%r{\Ahttps?://}, "").sub(%r{/+\z}, "")enddiff --git a/plugins/discourse-events/lib/discourse_events/events/validator.rb b/plugins/discourse-events/lib/discourse_events/events/validator.rbindex 8cb48752223..555f6f48252 100644--- a/plugins/discourse-events/lib/discourse_events/events/validator.rb+++ b/plugins/discourse-events/lib/discourse_events/events/validator.rb@@ -7,6 +7,7 @@ module DiscourseEventsdescription: Event::MAX_DESCRIPTION_LENGTH,url: Event::MAX_URL_LENGTH,location: Event::MAX_LOCATION_LENGTH,+ recording: Event::MAX_URL_LENGTH,}def initialize(post)@@ -119,6 +120,7 @@ module DiscourseEventsendadd_error("invalid_url") if !Parser.valid_url?(extracted_event[:url])+ add_error("invalid_recording_url") if !Parser.valid_web_url?(extracted_event[:recording])endprivatediff --git a/plugins/discourse-events/plugin.rb b/plugins/discourse-events/plugin.rbindex eb03b53e146..7af5052103e 100644--- a/plugins/discourse-events/plugin.rb+++ b/plugins/discourse-events/plugin.rb@@ -296,7 +296,10 @@ after_initialize dorequire_relative "app/jobs/regular/discourse_post_event_bulk_invite"require_relative "jobs/regular/discourse_post_event/bump_topic"require_relative "jobs/regular/discourse_post_event/send_reminder"+ require_relative "jobs/regular/discourse_post_event/warm_event_onebox"require_relative "jobs/regular/discourse_post_event/warm_livestream_onebox"+ require_relative "jobs/regular/discourse_post_event/warm_recording_onebox"+ require_relative "jobs/regular/discourse_post_event/publish_livestream_chat_transcript"require_relative "lib/discourse_events/events/chat_channel_sync"require_relative "lib/discourse_events/events/email_renderer"require_relative "lib/discourse_events/events/excerpt"@@ -986,6 +989,25 @@ after_initialize doadd_to_serializer(:topic_view, :has_livestream) { object.topic.first_post&.event&.livestream? }+ add_to_serializer(:topic_view, :livestream_chat_active) do+ !!object.topic.first_post&.event&.livestream_chat_active?+ end++ on(:discourse_post_event_event_ended) do |event, event_date|+ if event.livestream?+ Jobs.enqueue(:publish_livestream_chat_transcript, event_date_id: event_date.id)+ end+ end++ # Any status set since the event closed the chat is deliberate, so a resumed+ # event leaves it be.+ on(:chat_channel_status_change) do |channel:, **|+ DiscourseEvents::Livestream::TopicChatChannel.where(+ chat_channel_id: channel.id,+ closed_on_event_end: true,+ ).update_all(closed_on_event_end: false)+ end+add_to_serializer(:topic_view,:event_watching_invitee_status,diff --git a/plugins/discourse-events/spec/integration/post_spec.rb b/plugins/discourse-events/spec/integration/post_spec.rbindex 5e0f11cc451..1cb1088a174 100644--- a/plugins/discourse-events/spec/integration/post_spec.rb+++ b/plugins/discourse-events/spec/integration/post_spec.rb@@ -213,6 +213,14 @@ describe Post doexpect(post.event.url).to eq(url)end+ it "works with recording attribute" do+ Jobs.run_later!+ recording = "https://www.youtube.com/watch?v=abc123&t=10"++ post = create_post_with_event(user, "recording=\"#{recording}\"").reload+ expect(post.event.recording_url).to eq(recording)+ end+it "works with status attribute" dopost = create_post_with_event(user, 'status="private"').reloadexpect(post.event.status).to eq(DiscourseEvents::Events::Event.statuses[:private])@@ -556,6 +564,16 @@ describe Post doendend+ context "when recording is not a web address" do+ it "raises an error" do+ expect {+ create_post_with_event(user, 'recording="javascript:alert(1)"')+ }.to raise_error(+ I18n.t("discourse_post_event.errors.models.event.invalid_recording_url"),+ )+ end+ end+context "when location is too long" doit "raises an error" dolocation = "a" * (DiscourseEvents::Events::Event::MAX_LOCATION_LENGTH + 1)diff --git a/plugins/discourse-events/spec/jobs/regular/discourse_post_event/publish_livestream_chat_transcript_spec.rb b/plugins/discourse-events/spec/jobs/regular/discourse_post_event/publish_livestream_chat_transcript_spec.rbnew file mode 100644index 00000000000..457dee05b1e--- /dev/null+++ b/plugins/discourse-events/spec/jobs/regular/discourse_post_event/publish_livestream_chat_transcript_spec.rb@@ -0,0 +1,24 @@+# frozen_string_literal: true++RSpec.describe Jobs::PublishLivestreamChatTranscript do+ subject(:job) { described_class.new }++ let(:service) { DiscourseEvents::Livestream::PublishChatTranscript }+ let(:conflict) { DiscourseEvents::Livestream::PublishChatTranscript::EventPostChanged }++ it "publishes again from a fresh post when the event post changed meanwhile" do+ calls = 0+ allow(service).to receive(:call) { (calls += 1) == 1 ? raise(conflict) : nil }++ job.execute(event_date_id: 1)++ expect(service).to have_received(:call).twice+ end++ it "gives up once the event post keeps changing" do+ allow(service).to receive(:call).and_raise(conflict)++ expect { job.execute(event_date_id: 1) }.to raise_error(conflict)+ expect(service).to have_received(:call).exactly(described_class::MAX_ATTEMPTS).times+ end+enddiff --git a/plugins/discourse-events/spec/jobs/scheduled/monitor_event_dates_spec.rb b/plugins/discourse-events/spec/jobs/scheduled/monitor_event_dates_spec.rbindex 8aaf9e3c97e..7b570a59f90 100644--- a/plugins/discourse-events/spec/jobs/scheduled/monitor_event_dates_spec.rb+++ b/plugins/discourse-events/spec/jobs/scheduled/monitor_event_dates_spec.rb@@ -367,4 +367,57 @@ describe Jobs::DiscourseCalendar::MonitorEventDates doexpect(job.due_reminders(valid_event.event_dates.first).length).to eq(1)endend++ describe "livestream chat transcript" do+ before do+ Jobs.run_later!+ SiteSetting.discourse_events_enabled = true+ past_event.update_columns(livestream: true)+ end++ it "publishes the transcript once a livestream ends" do+ freeze_time 8.days.after++ expect_enqueued_with(+ job: :publish_livestream_chat_transcript,+ args: {+ event_date_id: past_date.id,+ },+ ) { job.execute({}) }+ end++ it "does not publish a transcript for events that aren't livestreams" do+ past_event.update_columns(livestream: false)+ freeze_time 8.days.after++ expect_not_enqueued_with(job: :publish_livestream_chat_transcript) { job.execute({}) }+ end+ end++ describe "#open_livestream_chat" do+ let(:topic) { past_event.post.topic }+ let(:messages) { MessageBus.track_publish("/topic/#{topic.id}") { job.execute({}) } }++ before { past_event.update_columns(livestream: true, recurrence: "every_week") }++ it "waits until the occurrence's chat window opens" do+ freeze_time(past_date.starts_at - 31.minutes)++ expect(messages).to be_empty+ end++ it "tells open pages to reload once the window opens" do+ freeze_time(past_date.starts_at - 29.minutes)++ expect(messages.map(&:data)).to contain_exactly({ reload_topic: true })+ expect(MessageBus.track_publish("/topic/#{topic.id}") { job.execute({}) }).to be_empty+ end++ it "leaves one-off livestreams alone, whose chat docks throughout" do+ past_event.update_columns(recurrence: nil)+ freeze_time(past_date.starts_at - 29.minutes)++ expect(messages).to be_empty+ end+ endenddiff --git a/plugins/discourse-events/spec/lib/discourse_events/events/parser_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/events/parser_spec.rbindex 63c27292f28..372f5ad1429 100644--- a/plugins/discourse-events/spec/lib/discourse_events/events/parser_spec.rb+++ b/plugins/discourse-events/spec/lib/discourse_events/events/parser_spec.rb@@ -261,6 +261,18 @@ describe DiscourseEvents::Events::Parser doexpect(events[0][:bar]).to eq("2")end+ it "keeps a built-in attribute's value when a custom field shares its name" do+ # Saved before the attribute became built-in; the setting now rejects it.+ SiteSetting.stubs(:discourse_post_event_allowed_custom_fields).returns("recording")+ post_event = build_post user, <<~TXT+ [event start="2020" recording="https://example.com/watch?v=1&t=2"]+ [/event]+ TXT++ events = parser.extract_events(post_event)+ expect(events[0][:recording]).to eq("https://example.com/watch?v=1&t=2")+ end+it "doesn’t parse not allowed custom fields" dopost_event = build_post user, <<~TXT[event start="2020" baz="1"]@@ -314,6 +326,20 @@ describe DiscourseEvents::Events::Parser doendend+ describe ".valid_web_url?" do+ it "accepts http(s) links, with or without a scheme" do+ expect(described_class.valid_web_url?("https://youtu.be/abc")).to eq(true)+ expect(described_class.valid_web_url?("vimeo.com/123")).to eq(true)+ expect(described_class.valid_web_url?(nil)).to eq(true)+ end++ it "rejects other schemes" do+ expect(described_class.valid_web_url?("mailto:[email protected]")).to eq(false)+ expect(described_class.valid_web_url?("javascript:alert(1)")).to eq(false)+ expect(described_class.valid_web_url?("Room 5")).to eq(false)+ end+ end+describe ".url_restates_location?" doit "ignores scheme and a trailing slash" doexpect(described_class.url_restates_location?("https://zoom.us/j/1/", "zoom.us/j/1")).to eq(diff --git a/plugins/discourse-events/spec/models/discourse_events/events/event_spec.rb b/plugins/discourse-events/spec/models/discourse_events/events/event_spec.rbindex 47ab0ed2510..6019c37fb67 100644--- a/plugins/discourse-events/spec/models/discourse_events/events/event_spec.rb+++ b/plugins/discourse-events/spec/models/discourse_events/events/event_spec.rb@@ -100,6 +100,42 @@ RSpec.describe DiscourseEvents::Events::Event doendend+ describe "#warm_recording_onebox" do+ fab!(:topic) { Fabricate(:topic, category: nil) }+ fab!(:post) { Fabricate(:post, topic: topic) }++ before { Jobs.run_later! }++ it "enqueues onebox warming when a recording is added" do+ event = Fabricate(:event, post: post)++ expect_enqueued_with(+ job: :warm_recording_onebox,+ args: {+ event_id: event.id,+ url: "https://youtu.be/abc",+ },+ ) { event.update!(recording_url: "youtu.be/abc") }+ end++ it "skips onebox warming when the onebox is cached" do+ Discourse.cache.write(+ Oneboxer.onebox_cache_key("https://youtu.be/abc"),+ { onebox: "<aside>cached</aside>" },+ )++ expect_not_enqueued_with(job: :warm_recording_onebox) do+ Fabricate(:event, post: post, recording_url: "https://youtu.be/abc")+ end+ end++ it "does not warm the onebox when an unrelated attribute changes" do+ event = Fabricate(:event, post: post, recording_url: "https://youtu.be/abc")++ expect_not_enqueued_with(job: :warm_recording_onebox) { event.update!(name: "Renamed") }+ end+ end+describe "#livestream_url" dofab!(:topic) { Fabricate(:topic, category: nil) }fab!(:post) { Fabricate(:post, topic: topic) }@@ -181,6 +217,79 @@ RSpec.describe DiscourseEvents::Events::Event doendend+ describe "#reopen_livestream_chat_channel" do+ fab!(:category)+ fab!(:topic) { Fabricate(:topic, category:) }+ fab!(:post) { Fabricate(:post, topic:) }++ before do+ SiteSetting.chat_enabled = true+ Jobs.run_later!+ end++ let!(:event) do+ Fabricate(+ :event,+ post:,+ livestream: true,+ location: "https://www.youtube.com/live/abc123",+ original_starts_at: 2.days.ago,+ original_ends_at: 2.days.ago + 1.hour,+ )+ end+ let(:topic_chat_channel) { DiscourseEvents::Livestream::TopicChatChannel.find_by(topic:) }+ let(:chat_channel) { topic_chat_channel.chat_channel }++ before do+ chat_channel.closed!(Discourse.system_user)+ topic_chat_channel.update!(closed_on_event_end: true)+ end++ it "reopens the chat the event closed once it is moved into the future" do+ event.update!(original_starts_at: 1.day.from_now, original_ends_at: 1.day.from_now + 1.hour)++ expect(chat_channel.reload).to be_open+ expect(topic_chat_channel.reload.closed_on_event_end).to eq(false)+ end++ it "reopens the chat once the event is made recurring" do+ event.update!(recurrence: "every_week")++ expect(chat_channel.reload).to be_open+ end++ it "reopens the chat once a finished recurring series is extended" do+ event.update_columns(recurrence: "every_week", recurrence_until: 1.day.ago)++ event.update!(recurrence_until: 1.month.from_now)++ expect(chat_channel.reload).to be_open+ end++ it "keeps the chat closed when the series cutoff falls after its last occurrence" do+ event.update_columns(recurrence: "every_week", recurrence_until: 2.days.from_now)++ event.update!(name: "Renamed event")++ expect(chat_channel.reload).to be_closed+ end++ it "keeps the chat closed while the event is still over" do+ event.update!(name: "Renamed event")++ expect(chat_channel.reload).to be_closed+ end++ it "keeps a status moderators set since the event closed the chat" do+ chat_channel.open!(Discourse.system_user)+ chat_channel.closed!(Discourse.system_user)++ event.update!(original_starts_at: 1.day.from_now, original_ends_at: 1.day.from_now + 1.hour)++ expect(chat_channel.reload).to be_closed+ end+ end+describe "#create_livestream_chat_channel" dofab!(:category)fab!(:topic) { Fabricate(:topic, category: category) }@@ -795,6 +904,46 @@ RSpec.describe DiscourseEvents::Events::Event doendend+ describe "#livestream_chat_active?" do+ before { Jobs.run_later! }++ # Not `fab!`: the dates must be relative to the time frozen for this file.+ let!(:event) do+ Fabricate(+ :event,+ livestream: true,+ location: "https://www.youtube.com/live/abc123",+ original_starts_at: 1.hour.from_now,+ original_ends_at: 2.hours.from_now,+ )+ end++ it "is true for an upcoming livestream" do+ expect(event.livestream_chat_active?).to eq(true)+ end++ it "is false once the livestream has ended" do+ freeze_time 3.hours.from_now++ expect(event.livestream_chat_active?).to eq(false)+ end++ it "is false for events that aren't livestreams" do+ event.update_columns(livestream: false)++ expect(event.livestream_chat_active?).to eq(false)+ end++ it "is only true around each occurrence of a recurring livestream" do+ event.update_columns(recurrence: "every_week")++ expect(event.livestream_chat_active?).to eq(false)++ freeze_time 50.minutes.from_now+ expect(event.livestream_chat_active?).to eq(true)+ end+ end+describe "#currently_within_event_timeframe?" dofab!(:user) { Fabricate(:user, admin: true, refresh_auto_groups: true) }fab!(:topic) { Fabricate(:topic, user: user) }diff --git a/plugins/discourse-events/spec/requests/api/schemas/json/events_index_detailed_response.json b/plugins/discourse-events/spec/requests/api/schemas/json/events_index_detailed_response.jsonindex 6da61db9d30..adcd518e1a0 100644--- a/plugins/discourse-events/spec/requests/api/schemas/json/events_index_detailed_response.json+++ b/plugins/discourse-events/spec/requests/api/schemas/json/events_index_detailed_response.json@@ -282,6 +282,15 @@"is_zoom_livestream": {"type": "boolean"},+ "recording_url": {+ "type": "string"+ },+ "recording_onebox": {+ "type": [+ "string",+ "null"+ ]+ },"max_attendees": {"type": ["integer",diff --git a/plugins/discourse-events/spec/serializers/discourse_events/events/event_serializer_spec.rb b/plugins/discourse-events/spec/serializers/discourse_events/events/event_serializer_spec.rbindex 25b17dad25b..e2fceec9f4c 100644--- a/plugins/discourse-events/spec/serializers/discourse_events/events/event_serializer_spec.rb+++ b/plugins/discourse-events/spec/serializers/discourse_events/events/event_serializer_spec.rb@@ -31,6 +31,34 @@ describe DiscourseEvents::Events::EventSerializer doendend+ context "with a recording" do+ fab!(:event) { Fabricate(:event, post:, recording_url: "https://youtu.be/abc") }++ it "serializes recording_url" do+ json = described_class.new(event, scope: Guardian.new).as_json++ expect(json[:event][:recording_url]).to eq("https://youtu.be/abc")+ end++ it "serializes the cached recording onebox" do+ Discourse.cache.write(+ Oneboxer.onebox_cache_key("https://youtu.be/abc"),+ { onebox: "<aside>recording</aside>" },+ )+ json = described_class.new(event, scope: Guardian.new).as_json++ expect(json[:event][:recording_onebox]).to eq("<aside>recording</aside>")+ end++ it "omits recording_url without a recording" do+ event.update_columns(recording_url: nil)+ json = described_class.new(event, scope: Guardian.new).as_json++ expect(json[:event]).not_to have_key(:recording_url)+ expect(json[:event]).not_to have_key(:recording_onebox)+ end+ end+context "with reminders" dodef serialized_reminders(reminders)event = Fabricate(:event, post: post, reminders: reminders)diff --git a/plugins/discourse-events/spec/services/discourse_events/livestream/chat_transcript_audience_spec.rb b/plugins/discourse-events/spec/services/discourse_events/livestream/chat_transcript_audience_spec.rbnew file mode 100644index 00000000000..b0f575c0b69--- /dev/null+++ b/plugins/discourse-events/spec/services/discourse_events/livestream/chat_transcript_audience_spec.rb@@ -0,0 +1,148 @@+# frozen_string_literal: true++RSpec.describe DiscourseEvents::Livestream::ChatTranscriptAudience do+ subject(:audience) { described_class.new(event, channel:) }++ fab!(:members, :group)+ fab!(:guests, :group)+ fab!(:category)++ let(:event) do+ Fabricate(+ :event,+ post: Fabricate(:post, topic: Fabricate(:topic, category:)),+ status: DiscourseEvents::Events::Event.statuses[event_status],+ raw_invitees: invited_groups.map(&:name),+ )+ end+ let(:channel) { Fabricate(:category_channel, chatable: category) }+ let(:event_status) { :public }+ let(:invited_groups) { [] }++ before { SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:trust_level_1].to_s }++ describe "#matches_topic_readers?" do+ context "when anonymous users can read the topic" do+ it { is_expected.not_to be_matches_topic_readers }++ context "when anonymous users can read public chat channels too" do+ before do+ SiteSetting.chat_allowed_groups =+ Group::AUTO_GROUPS.values_at(:anonymous_users, :trust_level_0).join("|")+ end++ it { is_expected.to be_matches_topic_readers }++ it "does not match when public channels are disabled" do+ SiteSetting.enable_public_channels = false++ expect(audience).not_to be_matches_topic_readers+ end++ context "when the event is invite-only" do+ let(:event_status) { :private }+ let(:invited_groups) { [members] }++ it { is_expected.not_to be_matches_topic_readers }+ end+ end+ end++ context "when the site requires login" do+ before { SiteSetting.login_required = true }++ it "does not match while new users cannot chat" do+ expect(audience).not_to be_matches_topic_readers+ end++ it "matches once every logged in user can chat" do+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:trust_level_0].to_s++ expect(audience).to be_matches_topic_readers+ end+ end++ context "when the category is restricted to groups that can chat" do+ before do+ category.set_permissions(members => :full)+ category.save!+ SiteSetting.chat_allowed_groups = members.id.to_s+ end++ it { is_expected.to be_matches_topic_readers }++ context "when the topic has moved away from the channel's category" do+ let(:channel) do+ Fabricate(:category_channel, chatable: Fabricate(:private_category, group: guests))+ end++ it { is_expected.not_to be_matches_topic_readers }+ end++ context "when the event is invite-only" do+ let(:event_status) { :private }++ context "when every reader group is invited" do+ let(:invited_groups) { [members] }++ it { is_expected.to be_matches_topic_readers }+ end++ context "when some reader groups are not invited" do+ let(:invited_groups) { [guests] }++ it { is_expected.not_to be_matches_topic_readers }+ end+ end+ end++ context "when the category is restricted to a group that cannot chat" do+ before do+ category.set_permissions(guests => :readonly)+ category.save!+ end++ it { is_expected.not_to be_matches_topic_readers }+ end++ context "when some readers of the category can only read it" do+ before do+ SiteSetting.login_required = true+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:trust_level_0].to_s+ category.set_permissions(guests => :readonly, members => :full)+ category.save!+ end++ it { is_expected.not_to be_matches_topic_readers }++ it "matches once they can post too" do+ category.set_permissions(guests => :create_post, members => :full)+ category.save!++ expect(audience).to be_matches_topic_readers+ end+ end++ context "when everyone can read the category but only some can post" do+ before do+ SiteSetting.login_required = true+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:trust_level_0].to_s+ category.set_permissions(:everyone => :readonly, members => :full)+ category.save!+ end++ it { is_expected.not_to be_matches_topic_readers }+ end++ context "when the category is restricted by trust level" do+ before do+ category.set_permissions(Group::AUTO_GROUPS[:trust_level_2] => :full)+ category.save!+ end++ it "matches when a lower trust level can chat" do+ expect(audience).to be_matches_topic_readers+ end+ end+ end+enddiff --git a/plugins/discourse-events/spec/services/discourse_events/livestream/chat_transcript_spec.rb b/plugins/discourse-events/spec/services/discourse_events/livestream/chat_transcript_spec.rbnew file mode 100644index 00000000000..e2caf28dd30--- /dev/null+++ b/plugins/discourse-events/spec/services/discourse_events/livestream/chat_transcript_spec.rb@@ -0,0 +1,193 @@+# frozen_string_literal: true++RSpec.describe DiscourseEvents::Livestream::ChatTranscript do+ subject(:transcript) { described_class.new(channel:, messages:, event_date:, max_length:) }++ fab!(:channel, :category_channel)+ fab!(:alice, :user)+ fab!(:bob, :user)+ fab!(:chat_messages) do+ %w[first second third].each_with_index.map do |text, index|+ Fabricate(:chat_message, chat_channel: channel, user: [alice, bob][index % 2], message: text)+ end+ end+ fab!(:event) do+ Fabricate(+ :event,+ timezone: "America/New_York",+ original_starts_at: Time.utc(2026, 10, 8, 19, 0),+ original_ends_at: Time.utc(2026, 10, 8, 20, 0),+ )+ end++ let(:event_date) { event.event_dates.first }+ let(:messages) { channel.chat_messages }+ let(:max_length) { 32_000 }++ describe "#raw" do+ it "heads the chat quotes for a one-off event without a date" do+ expect(transcript.raw).to start_with("Chat transcript\n\n[wrap=livestream-chat-transcript]")+ expect(transcript.raw).to include("[chat quote=", "first", "second", "third")+ expect(transcript.raw).not_to include("earlier")+ end++ context "when the event is recurring" do+ before { event.update_columns(recurrence: "every_week") }++ it "dates the transcript with the occurrence's local start" do+ expect(transcript.raw).to start_with(+ 'Chat transcript for [date=2026-10-08 time=15:00:00 timezone="America/New_York"]',+ )+ end++ it "writes the date out when local dates are disabled" do+ SiteSetting.discourse_local_dates_enabled = false++ expect(transcript.raw).to start_with("Chat transcript for October 8, 2026")+ end+ end++ context "when a message tries to close its quote" do+ let(:messages) { channel.chat_messages.where(id: escaping_message.id) }+ let(:escaping_message) do+ Fabricate(+ :chat_message,+ chat_channel: channel,+ user: alice,+ message: "hi\n[/chat]\n\n[poll]\n* a\n* b\n[/poll]\n[/WRAP]",+ )+ end++ it "keeps the rest of the message inside the quote" do+ cooked = PrettyText.cook(transcript.raw)++ expect(cooked).not_to include('class="poll"')+ expect(cooked).to include("[/chat]", "[/WRAP]")+ expect(cooked.scan("d-wrap").size).to eq(1)+ end++ it "escapes each closing tag once however many renders fitting takes" do+ expect(transcript.raw).to include("\\[/chat]", "\\[/WRAP]")+ expect(transcript.raw).not_to include("\\\\[/")+ end++ it "leaves the stored message untouched" do+ transcript.raw++ expect(escaping_message.reload.message).to include("\n[/chat]\n")+ end+ end++ context "when a message opens a tag to swallow its quote's closing one" do+ let(:messages) { channel.chat_messages.where(id: escaping_message.id) }+ let(:escaping_message) do+ Fabricate(+ :chat_message,+ chat_channel: channel,+ user: alice,+ message: "hi\n\n[poll]\n* a\n* b\n[/poll]\n\n#{opening_tag}",+ )+ end+ let(:opening_tag) { "[chat][wrap=x]" }++ %w[[chat] [CHAT\ quote="bob;1;2026-10-08T19:00:00Z"] [wrap] [wrap=other]].each do |tag|+ context "with #{tag}" do+ let(:opening_tag) { tag }++ it "keeps the rest of the message inside the quote" do+ cooked = PrettyText.cook(transcript.raw)++ expect(cooked).not_to include('class="poll"')+ expect(cooked).to include(tag[/\A\[\w+/])+ expect(cooked.scan("d-wrap").size).to eq(1)+ end+ end+ end++ it "escapes each opening tag once however many renders fitting takes" do+ expect(transcript.raw).to include("\\[chat]", "\\[wrap=x]")+ expect(transcript.raw).not_to include("\\\\[")+ end+ end++ context "when the only message opens a thread" do+ let(:messages) { channel.chat_messages.where(id: thread.original_message_id) }+ let(:thread) { Fabricate(:chat_thread, channel:, original_message_user: alice) }++ before do+ channel.update!(threading_enabled: true)+ Fabricate(:chat_message, chat_channel: channel, user: bob, thread:, message: "later reply")+ thread.update!(replies_count: 1)+ end++ it "leaves out the replies it was not given" do+ expect(transcript.raw).to include(+ "quote=\"#{alice.username};#{thread.original_message_id};",+ )+ expect(transcript.raw).not_to include("later reply")+ end+ end++ context "with a message that only has uploads" do+ fab!(:upload)++ before do+ upload_only = Fabricate(:chat_message, chat_channel: channel, user: alice)+ UploadReference.create!(target: upload_only, upload:)+ upload_only.update_columns(message: nil)+ end++ it "quotes the uploads" do+ expect(transcript.raw).to include(upload.short_url, "third")+ end+ end++ context "when the messages do not fit" do+ let(:max_length) do+ described_class.new(channel:, messages:, event_date:, max_length: 32_000).raw.length - 1+ end++ it "keeps the most recent messages and links to the channel for the rest" do+ expect(transcript.raw).to include("second", "third")+ expect(transcript.raw).not_to include("first")+ expect(transcript.raw).to include(+ "1 earlier message is in the [chat channel](#{channel.relative_url}).",+ )+ expect(transcript.raw.length).to be <= max_length+ end++ it "looks up each message's uploads once however many renders fitting takes" do+ # Built first, as sizing max_length renders a transcript of its own.+ transcript+ queries = track_sql_queries { transcript.raw }++ expect(queries.grep(/upload_references/).size).to eq(chat_messages.size)+ end+ end++ context "when there is no room for any message" do+ let(:max_length) { 0 }++ it "only points to the channel" do+ expect(transcript.raw).to include("3 earlier messages are in the [chat channel]")+ expect(transcript.raw).not_to include("[chat quote=")+ end+ end+ end++ describe "#last_message_id" do+ it "is the most recent message" do+ expect(transcript.last_message_id).to eq(chat_messages.last.id)+ end+ end++ describe "#messages?" do+ it { is_expected.to be_messages }++ context "without messages" do+ let(:messages) { channel.chat_messages.none }++ it { is_expected.not_to be_messages }+ end+ end+enddiff --git a/plugins/discourse-events/spec/services/discourse_events/livestream/publish_chat_transcript_spec.rb b/plugins/discourse-events/spec/services/discourse_events/livestream/publish_chat_transcript_spec.rbnew file mode 100644index 00000000000..328cbc820a7--- /dev/null+++ b/plugins/discourse-events/spec/services/discourse_events/livestream/publish_chat_transcript_spec.rb@@ -0,0 +1,331 @@+# frozen_string_literal: true++RSpec.describe DiscourseEvents::Livestream::PublishChatTranscript do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of(:event_date_id) }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:) }++ fab!(:group)+ fab!(:category) { Fabricate(:private_category, group:) }+ fab!(:starts_at) { 2.hours.ago.beginning_of_minute }+ fab!(:ends_at) { 1.hour.ago.beginning_of_minute }+ # The raw carries the event too: editing the post re-syncs the event from it.+ fab!(:event_post) do+ Fabricate(+ :post,+ user: Fabricate(:admin, refresh_auto_groups: true),+ topic: Fabricate(:topic, category:),+ raw: <<~RAW,+ [event start="#{starts_at.strftime("%Y-%m-%d %H:%M")}" end="#{ends_at.strftime("%Y-%m-%d %H:%M")}" status="public" timezone="UTC" livestream="true" location="https://www.youtube.com/live/abc123"]+ [/event]++ Come along!+ RAW+ )+ end+ fab!(:event) do+ Fabricate(+ :event,+ post: event_post,+ livestream: true,+ location: "https://www.youtube.com/live/abc123",+ timezone: "UTC",+ original_starts_at: starts_at,+ original_ends_at: ends_at,+ raw_invitees: ["trust_level_0"],+ description: "",+ )+ end+ fab!(:viewer, :user)++ let(:params) { { event_date_id: } }+ let(:event_date_id) { event.event_dates.first.id }+ let(:topic) { event.post.topic }+ let(:topic_chat_channel) { DiscourseEvents::Livestream::TopicChatChannel.find_by(topic:) }+ let(:chat_channel) { topic_chat_channel.chat_channel }++ before do+ SiteSetting.chat_enabled = true+ SiteSetting.discourse_events_enabled = true+ SiteSetting.discourse_post_event_enabled = true+ SiteSetting.chat_allowed_groups = group.id.to_s+ DiscourseEvents::Livestream.handle_topic_chat_channel_creation(topic)+ end++ context "when contract is invalid" do+ let(:event_date_id) { nil }++ it { is_expected.to fail_a_contract }+ end++ context "when chat is disabled" do+ before { SiteSetting.chat_enabled = false }++ it { is_expected.to fail_a_policy(:chat_enabled) }+ end++ context "when the event date does not exist" do+ let(:event_date_id) { 0 }++ it { is_expected.to fail_to_find_a_model(:event_date) }+ end++ context "when the event is not a livestream" do+ before { event.update_columns(livestream: false) }++ it { is_expected.to fail_to_find_a_model(:event) }+ end++ context "when the topic has no livestream chat channel" do+ before { topic_chat_channel.destroy! }++ it { is_expected.to fail_to_find_a_model(:topic_chat_channel) }+ end++ context "without any chat messages" do+ it { is_expected.to run_successfully }++ it "leaves the topic alone" do+ expect { result }.not_to change { [topic.posts.count, event_post.reload.raw] }+ end++ it "closes the chat channel" do+ expect { result }.to change { chat_channel.reload.status }.to("closed")+ end+ end++ context "with chat messages" do+ let!(:messages) do+ [+ Fabricate(:chat_message, chat_channel:, user: viewer, message: "Hello stream"),+ Fabricate(:chat_message, chat_channel:, user: viewer, message: "Great talk"),+ ]+ end++ it { is_expected.to run_successfully }++ it "appends the transcript to the event post" do+ result++ expect(event_post.reload.raw).to start_with(event_post.raw.rstrip)+ expect(event_post.raw).to include("Chat transcript", "Hello stream", "Great talk")+ expect(event_post.last_editor_id).to eq(Discourse::SYSTEM_USER_ID)+ end++ it "does not reply to the topic" do+ expect { result }.not_to change { topic.posts.count }+ end++ it "keeps the event as it was" do+ expect { result }.not_to change { event.reload.attributes.except("updated_at") }+ end++ it "leaves out the pinned reference message" do+ reference_message = Chat::Message.find(topic_chat_channel.reference_message_id)+ result++ expect(event_post.reload.raw).not_to include(reference_message.message)+ end++ it "records how far the chat has been transcribed" do+ expect { result }.to change { topic_chat_channel.reload.last_transcribed_message_id }.to(+ messages.last.id,+ )+ end++ it "only transcribes messages sent since the previous transcript" do+ topic_chat_channel.update!(last_transcribed_message_id: messages.first.id)+ result++ expect(event_post.reload.raw).to include("Great talk")+ expect(event_post.raw).not_to include("Hello stream")+ end++ it "does not notify anyone or bump the topic" do+ expect_not_enqueued_with(job: :post_alert) { result }+ expect(topic.reload.bumped_at).to eq_time(topic.bumped_at)+ end++ context "when another job transcribed the messages while this one waited" do+ before do+ allow(DistributedMutex).to receive(+ :synchronize,+ ).and_wrap_original do |original, *args, **kwargs, &block|+ topic_chat_channel.update!(last_transcribed_message_id: messages.last.id)+ original.call(*args, **kwargs, &block)+ end+ end++ it "does not transcribe them again" do+ expect { result }.not_to change { [topic.posts.count, event_post.reload.raw] }+ end+ end++ context "when the topic moves to a wider audience while this job waits" do+ fab!(:public_category, :category)++ before do+ allow(DistributedMutex).to receive(+ :synchronize,+ ).and_wrap_original do |original, *args, **kwargs, &block|+ topic.update!(category: public_category)+ original.call(*args, **kwargs, &block)+ end+ end++ it "keeps the chat out of the topic" do+ expect { result }.not_to change { [topic.posts.count, event_post.reload.raw] }+ end+ end++ context "when the event post is edited while the transcript is rendered" do+ let(:edited_raw) { "#{event_post.raw.rstrip}\n\nRecording: https://example.com/recording" }++ before do+ allow(DiscourseEvents::Livestream::ChatTranscript).to receive(+ :new,+ ).and_wrap_original do |original, **kwargs|+ event_post.update_columns(raw: edited_raw)+ original.call(**kwargs)+ end+ end++ # The edit shares the service's transaction here, so the rollback also+ # undoes it; what matters is that the transcript does not replace it.+ it "writes nothing and asks to render again" do+ expect { result }.to raise_error(described_class::EventPostChanged)++ expect(event_post.reload.raw).not_to include("Chat transcript")+ expect(topic_chat_channel.reload.last_transcribed_message_id).to be_nil+ end+ end++ it "keeps the event post within the length limit" do+ SiteSetting.max_post_length = event_post.raw.length + 120+ result++ expect(event_post.reload.raw.length).to be <= SiteSetting.max_post_length+ expect(event_post.raw).to include("earlier message")+ end++ context "when the event post has no room left for the transcript" do+ before do+ padding = "a" * (SiteSetting.max_post_length - event_post.raw.length - 10)+ event_post.update_columns(raw: "#{event_post.raw}#{padding}")+ end++ it "replies with the transcript instead" do+ expect { result }.to change { topic.posts.count }.by(1)++ expect(topic.posts.last.raw).to include("Chat transcript", "Hello stream", "Great talk")+ expect(event_post.reload.raw.length).to be <= SiteSetting.max_post_length+ expect(event_post.raw).not_to include("Chat transcript")+ end+ end++ context "when the event is recurring" do+ before { event.update_columns(recurrence: "every_week") }++ it "replies with a dated transcript instead" do+ expect { result }.to change { topic.posts.count }.by(1)++ reply = topic.posts.last+ expect(reply.user).to eq(Discourse.system_user)+ expect(reply.raw).to start_with("Chat transcript for [date=")+ expect(reply.raw).to include("Hello stream", "Great talk")+ expect(event_post.reload.raw).not_to include("Hello stream")+ end++ it "does not notify anyone or bump the topic" do+ expect_not_enqueued_with(job: :post_alert) { result }+ expect(topic.reload.bumped_at).to eq_time(topic.bumped_at)+ end+ end++ context "when some topic readers could not read the chat" do+ before { SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:admins].to_s }++ it { is_expected.to run_successfully }++ it "keeps the chat out of the topic" do+ expect { result }.not_to change { [topic.posts.count, event_post.reload.raw] }+ end++ it "still closes the chat channel" do+ expect { result }.to change { chat_channel.reload.status }.to("closed")+ end+ end+ end++ context "when the job runs once the next occurrence has opened" do+ let!(:closing_message) do+ Fabricate(+ :chat_message,+ chat_channel:,+ user: viewer,+ message: "Thanks everyone",+ created_at: ends_at + 5.minutes,+ )+ end+ let!(:next_occurrence_message) do+ Fabricate(+ :chat_message,+ chat_channel:,+ user: viewer,+ message: "Starting soon?",+ created_at: starts_at + 1.day - 10.minutes,+ )+ end++ before do+ event.update_columns(recurrence: "every_day")+ freeze_time(starts_at + 1.day)+ end++ it "transcribes only the chat of the occurrence that ended" do+ result++ expect(topic.posts.last.raw).to include("Thanks everyone")+ expect(topic.posts.last.raw).not_to include("Starting soon?")+ expect(topic_chat_channel.reload.last_transcribed_message_id).to eq(closing_message.id)+ end+ end++ context "when the livestream is over" do+ it "closes the chat channel and remembers having done so" do+ result++ expect(chat_channel.reload).to be_closed+ expect(topic_chat_channel.reload.closed_on_event_end).to eq(true)+ end++ it "keeps a status moderators set" do+ chat_channel.read_only!(Discourse.system_user)++ expect { result }.not_to change { chat_channel.reload.status }+ expect(topic_chat_channel.reload.closed_on_event_end).to eq(false)+ end+ end++ context "when a recurring livestream's cutoff falls after its last occurrence" do+ before { event.update_columns(recurrence: "every_week", recurrence_until: 2.days.from_now) }++ it "closes the chat channel" do+ expect { result }.to change { chat_channel.reload.status }.to("closed")+ end+ end++ context "when a recurring livestream has more occurrences" do+ before { event.update_columns(recurrence: "every_week") }++ it { is_expected.to run_successfully }++ it "keeps the chat channel open for the next occurrence" do+ expect { result }.not_to change { chat_channel.reload.status }+ end+ end+ end+enddiff --git a/plugins/discourse-events/spec/system/page_objects/discourse_events/post_event.rb b/plugins/discourse-events/spec/system/page_objects/discourse_events/post_event.rbindex a3b2c2bcf81..79fa715fd04 100644--- a/plugins/discourse-events/spec/system/page_objects/discourse_events/post_event.rb+++ b/plugins/discourse-events/spec/system/page_objects/discourse_events/post_event.rb@@ -67,11 +67,11 @@ module PageObjectsenddef has_selected_status?(status)- has_css?(status_button_selector(status, ".btn-primary"))+ has_css?(status_button_selector(status, selected_status_class(status)))enddef has_no_selected_status?(status)- has_no_css?(status_button_selector(status, ".btn-primary"))+ has_no_css?(status_button_selector(status, selected_status_class(status)))enddef has_pressed_status?(status, pressed: true)@@ -222,6 +222,10 @@ module PageObjectsprivate+ def selected_status_class(status)+ status.to_sym == :going ? ".btn-success" : ".btn-primary"+ end+def status_button_selector(status, state)button = ".event-status #{STATUS_BUTTONS.fetch(status)}""#{button}#{state}, #{button} #{state}"diff --git a/plugins/discourse-events/test/javascripts/integration/components/compact-event-editor-test.gjs b/plugins/discourse-events/test/javascripts/integration/components/compact-event-editor-test.gjsindex 7200fbd6642..89177a19f43 100644--- a/plugins/discourse-events/test/javascripts/integration/components/compact-event-editor-test.gjs+++ b/plugins/discourse-events/test/javascripts/integration/components/compact-event-editor-test.gjs@@ -47,6 +47,46 @@ module("Integration | Component | CompactEventEditor", function (hooks) {);});+ test("offers a recording field once a livestream has ended", async function (assert) {+ await renderEditor(+ stateWith({+ livestream: true,+ startsAt: moment("2020-07-01T10:00:00Z"),+ endsAt: moment("2020-07-01T11:00:00Z"),+ })+ );++ assert.dom(".composer-event__recording-input").exists();+ });++ test("offers no recording field before a livestream has ended", async function (assert) {+ await renderEditor(+ stateWith({+ livestream: true,+ startsAt: moment("2099-07-01T10:00:00Z"),+ endsAt: moment("2099-07-01T11:00:00Z"),+ })+ );++ assert.dom(".composer-event__recording-input").doesNotExist();+ });++ test("emits the recording as it is typed", async function (assert) {+ let state;+ await renderEditor(+ stateWith({+ livestream: true,+ startsAt: moment("2020-07-01T10:00:00Z"),+ endsAt: moment("2020-07-01T11:00:00Z"),+ }),+ (newState) => (state = newState)+ );++ await fillIn(".composer-event__recording-input", "https://youtu.be/abc");++ assert.strictEqual(state.recording, "https://youtu.be/abc");+ });+test("offers no url row for an event that has none", async function (assert) {const initialState = stateWith({ location: "Room 5" });await renderEditor(initialState);diff --git a/plugins/discourse-events/test/javascripts/integration/components/livestream-test.gjs b/plugins/discourse-events/test/javascripts/integration/components/livestream-test.gjsindex 43ad8e9f47c..093621ddbb3 100644--- a/plugins/discourse-events/test/javascripts/integration/components/livestream-test.gjs+++ b/plugins/discourse-events/test/javascripts/integration/components/livestream-test.gjs@@ -6,6 +6,7 @@ import sinon from "sinon";import { withPluginApi } from "discourse/lib/plugin-api";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import Livestream from "discourse/plugins/discourse-events/discourse/components/discourse-post-event/livestream";+import OneboxEmbed from "discourse/plugins/discourse-events/discourse/components/discourse-post-event/onebox-embed";const ZOOM_URL = "https://us06web.zoom.us/j/123456789?pwd=secret";const ZOOM_ENTRY_SELECTOR = ".discourse-calendar-livestream-zoom-entry";@@ -58,6 +59,24 @@ module(assert.dom(".event-livestream").doesNotExist();});+ test("renders nothing once a recording supersedes the stream", async function (assert) {+ this.event.recordingUrl = "https://youtu.be/abc";+ this.event.isExpired = true;++ await render(<template><Livestream @event={{this.event}} /></template>);++ assert.dom(".event-livestream").doesNotExist();+ });++ test("keeps the stream while the event has not ended", async function (assert) {+ this.event.recordingUrl = "https://youtu.be/abc";+ this.event.isExpired = false;++ await render(<template><Livestream @event={{this.event}} /></template>);++ assert.dom(".event-livestream").exists();+ });+test("renders the Zoom entry for a Zoom livestream", async function (assert) {await render(<template><Livestream @event={{this.event}} /></template>);@@ -110,9 +129,9 @@ module(this.event.livestreamOnebox ="<div class='lazy-video-container'></div>";- sinon.stub(Livestream.prototype, "lazyVideo").get(() => FakeLazyVideo);+ sinon.stub(OneboxEmbed.prototype, "lazyVideo").get(() => FakeLazyVideo);sinon- .stub(Livestream.prototype, "videoAttributes")+ .stub(OneboxEmbed.prototype, "videoAttributes").get(() => ({ providerName: "youtube", id: "dQw4w9WgXcQ" }));withPluginApi((api) => {diff --git a/plugins/discourse-events/test/javascripts/integration/components/more-menu-test.gjs b/plugins/discourse-events/test/javascripts/integration/components/more-menu-test.gjsindex 89dfec9e7dd..d3531fbd203 100644--- a/plugins/discourse-events/test/javascripts/integration/components/more-menu-test.gjs+++ b/plugins/discourse-events/test/javascripts/integration/components/more-menu-test.gjs@@ -56,4 +56,70 @@ module("Integration | Component | MoreMenu", function (hooks) {await click(".discourse-post-event-more-menu-trigger");assert.dom(".show-all-participants").exists();});++ test("offers editors the recording once a livestream has ended", async function (assert) {+ const store = getOwner(this).lookup("service:store");+ const creator = store.createRecord("user", {+ username: "gabriel",+ id: 322,+ });+ const event = {+ isExpired: true,+ livestream: true,+ creator,+ canActOnDiscoursePostEvent: true,+ };++ await render(<template><MoreMenu @event={{event}} /></template>);+ await click(".discourse-post-event-more-menu-trigger");++ assert.dom(".manage-recording").hasText("Add recording link");+ });++ test("does not offer the recording before a livestream ends", async function (assert) {+ const store = getOwner(this).lookup("service:store");+ const creator = store.createRecord("user", {+ username: "gabriel",+ id: 322,+ });+ const event = {+ isExpired: false,+ livestream: true,+ creator,+ canActOnDiscoursePostEvent: true,+ };++ await render(<template><MoreMenu @event={{event}} /></template>);+ await click(".discourse-post-event-more-menu-trigger");++ assert.dom(".manage-recording").doesNotExist();+ });++ test("renders nothing when there is nothing to offer", async function (assert) {+ getOwner(this).unregister("service:current-user");+ const event = { isExpired: true, creator: { username: "gabriel" } };++ await render(<template><MoreMenu @event={{event}} /></template>);++ assert.dom(".discourse-post-event-more-menu-trigger").doesNotExist();+ });++ test("offers the participants only once there are some", async function (assert) {+ const store = getOwner(this).lookup("service:store");+ const creator = store.createRecord("user", {+ username: "gabriel",+ id: 322,+ });+ const event = {+ isExpired: false,+ creator,+ canActOnDiscoursePostEvent: true,+ stats: { invited: 0 },+ };++ await render(<template><MoreMenu @event={{event}} /></template>);+ await click(".discourse-post-event-more-menu-trigger");++ assert.dom(".show-all-participants").doesNotExist();+ });});diff --git a/plugins/discourse-events/test/javascripts/integration/components/post-event-builder-test.gjs b/plugins/discourse-events/test/javascripts/integration/components/post-event-builder-test.gjsindex 13d44db5050..ae94936d190 100644--- a/plugins/discourse-events/test/javascripts/integration/components/post-event-builder-test.gjs+++ b/plugins/discourse-events/test/javascripts/integration/components/post-event-builder-test.gjs@@ -229,6 +229,26 @@ module("Integration | Component | Modal | PostEventBuilder", function (hooks) {);});+ test("advanced screen offers a recording field once a livestream has ended", async function (assert) {+ const event = eventWith({ livestream: true });+ await renderAdvanced(event);++ await fillIn(`[data-name="recordingUrl"] input`, "https://youtu.be/abc");++ assert.strictEqual(event.recordingUrl, "https://youtu.be/abc");+ });++ test("advanced screen hides the recording field before a livestream ends", async function (assert) {+ const event = eventWith({+ livestream: true,+ starts_at: "2099-07-01T10:00:00Z",+ ends_at: "2099-07-01T11:00:00Z",+ });+ await renderAdvanced(event);++ assert.dom(`[data-name="recordingUrl"]`).doesNotExist();+ });+test("offers livestream when the url field carries the livestream link", async function (assert) {this.siteSettings.chat_enabled = true;diff --git a/plugins/discourse-events/test/javascripts/integration/components/post-event-recording-test.gjs b/plugins/discourse-events/test/javascripts/integration/components/post-event-recording-test.gjsnew file mode 100644index 00000000000..c2836b8c015--- /dev/null+++ b/plugins/discourse-events/test/javascripts/integration/components/post-event-recording-test.gjs@@ -0,0 +1,85 @@+import { getOwner } from "@ember/owner";+import { click, fillIn, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import PostEventRecording from "discourse/plugins/discourse-events/discourse/components/modal/post-event-recording";++const RAW = `[event start="2026-10-08 15:00" status="public" livestream="true" location="https://www.youtube.com/live/abc"]+Description+[/event]++Come along!`;++module(+ "Integration | Component | Modal | PostEventRecording",+ function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.post = { raw: RAW, save: sinon.stub().resolves() };+ sinon+ .stub(getOwner(this).lookup("service:store"), "find")+ .resolves(this.post);+ this.closeModal = sinon.spy();+ });++ async function renderModal(context, event) {+ const model = { event };+ const closeModal = context.closeModal;++ await render(+ <template>+ <PostEventRecording+ @closeModal={{closeModal}}+ @inline={{true}}+ @model={{model}}+ />+ </template>+ );+ }++ test("adds the recording to the event without touching the rest", async function (assert) {+ await renderModal(this, { id: 42 });++ assert.dom(".d-modal__title-text").hasText("Add recording");+ assert.dom(".form-kit__button.--danger").doesNotExist();++ await fillIn("[name='recordingUrl']", "https://youtu.be/abc");+ await click(".form-kit__button[type='submit']");++ const { raw, edit_reason } = this.post.save.firstCall.args[0];+ assert.true(raw.includes("recording=https://youtu.be/abc"));+ assert.true(raw.includes("Description\n[/event]\n\nCome along!"));+ assert.true(raw.includes("location=https://www.youtube.com/live/abc"));+ assert.strictEqual(edit_reason, "Recording link updated");+ assert.true(this.closeModal.calledOnce);+ });++ test("edits or removes an existing recording", async function (assert) {+ this.post.raw = RAW.replace(+ 'status="public"',+ 'status="public" recording="https://youtu.be/old"'+ );+ await renderModal(this, { id: 42, recordingUrl: "https://youtu.be/old" });++ assert.dom(".d-modal__title-text").hasText("Edit recording");+ assert.dom("[name='recordingUrl']").hasValue("https://youtu.be/old");++ await click(".form-kit__button.--danger");++ const { raw } = this.post.save.firstCall.args[0];+ assert.false(raw.includes("recording="));+ assert.true(raw.includes("status=public"));+ });++ test("requires a web address", async function (assert) {+ await renderModal(this, { id: 42 });++ await fillIn("[name='recordingUrl']", "not a link");+ await click(".form-kit__button[type='submit']");++ assert.false(this.post.save.called);+ });+ }+);diff --git a/plugins/discourse-events/test/javascripts/integration/components/recording-test.gjs b/plugins/discourse-events/test/javascripts/integration/components/recording-test.gjsnew file mode 100644index 00000000000..777e60cf51d--- /dev/null+++ b/plugins/discourse-events/test/javascripts/integration/components/recording-test.gjs@@ -0,0 +1,75 @@+import { render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import Recording from "discourse/plugins/discourse-events/discourse/components/discourse-post-event/recording";++module(+ "Integration | Component | DiscoursePostEvent::Recording",+ function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.event = {+ livestream: true,+ isExpired: true,+ canActOnDiscoursePostEvent: true,+ recordingUrl: null,+ };+ });++ test("links to the recording for everyone once it exists", async function (assert) {+ this.event.canActOnDiscoursePostEvent = false;+ this.event.recordingUrl = "youtu.be/abc";++ await render(<template><Recording @event={{this.event}} /></template>);++ assert+ .dom(".event-recording__watch")+ .hasAttribute("href", "https://youtu.be/abc")+ .hasAttribute("target", "_blank")+ .hasText("Watch recording");+ assert.dom(".event-recording__add").doesNotExist();+ });++ test("embeds the recording when it has a onebox", async function (assert) {+ this.event.recordingUrl = "https://example.com/recording";+ this.event.recordingOnebox =+ '<aside class="onebox recording-onebox">Recording</aside>';++ await render(<template><Recording @event={{this.event}} /></template>);++ assert.dom(".event-recording .recording-onebox").exists();+ assert.dom(".event-recording__watch").doesNotExist();+ });++ test("prompts an editor to add a recording after a livestream ends", async function (assert) {+ await render(<template><Recording @event={{this.event}} /></template>);++ assert.dom(".event-recording__add").hasText("Add recording link");+ });++ test("does not prompt users who can't edit the event", async function (assert) {+ this.event.canActOnDiscoursePostEvent = false;++ await render(<template><Recording @event={{this.event}} /></template>);++ assert.dom(".event-recording").doesNotExist();+ });++ test("does not prompt before the event has ended", async function (assert) {+ this.event.isExpired = false;++ await render(<template><Recording @event={{this.event}} /></template>);++ assert.dom(".event-recording").doesNotExist();+ });++ test("does not prompt for events that weren't livestreamed", async function (assert) {+ this.event.livestream = false;++ await render(<template><Recording @event={{this.event}} /></template>);++ assert.dom(".event-recording").doesNotExist();+ });+ }+);diff --git a/plugins/discourse-events/test/javascripts/lib/raw-event-helper-test.js b/plugins/discourse-events/test/javascripts/lib/raw-event-helper-test.jsindex 35318c0ab63..d9d153cbb84 100644--- a/plugins/discourse-events/test/javascripts/lib/raw-event-helper-test.js+++ b/plugins/discourse-events/test/javascripts/lib/raw-event-helper-test.js@@ -16,6 +16,7 @@ import {reminderToBBCode,removeEvent,replaceRaw,+ setEventAttribute,stateToEventInput,} from "discourse/plugins/discourse-events/discourse/lib/raw-event-helper";@@ -647,6 +648,50 @@ module("Unit | Lib | raw-event-helper", function (hooks) {);});+ test("recording round-trips through state, params and parsing", function (assert) {+ const startsAt = "2024-06-15T10:00:00Z";+ const siteSettings = { discourse_post_event_allowed_custom_fields: "" };+ const url = "https://youtu.be/abc";++ assert.strictEqual(+ buildParams(startsAt, null, { recordingUrl: ` ${url} ` }, siteSettings)+ .recording,+ url,+ "buildParams emits a trimmed recording"+ );+ assert.strictEqual(+ buildParams(startsAt, null, { recordingUrl: " " }, siteSettings)+ .recording,+ undefined,+ "buildParams omits a blank recording"+ );+ assert.strictEqual(+ stateToEventInput({ recording: url }).recordingUrl,+ url,+ "stateToEventInput maps recording to recordingUrl"+ );+ assert.strictEqual(+ parseEventAttrs({ recording: url }).recording,+ url,+ "parseEventAttrs reads recording"+ );+ });++ test("setEventAttribute changes one attribute and keeps the rest", function (assert) {+ const raw =+ '[event start="2024-06-15 10:00" status="public"]\nHello\n[/event]\n\nAfter';++ const added = setEventAttribute(raw, "recording", " https://youtu.be/a ");+ assert.true(added.includes("recording=https://youtu.be/a"));+ assert.true(added.includes('start="2024-06-15 10:00"'));+ assert.true(added.endsWith("Hello\n[/event]\n\nAfter"));++ const removed = setEventAttribute(added, "recording", "");+ assert.false(removed.includes("recording="));++ assert.false(setEventAttribute("No event here", "recording", "x"));+ });+test("isLivestreamUrl only accepts https URLs for major livestreaming platforms", function (assert) {const siteSettings = getOwner(this).lookup("service:site-settings");diff --git a/plugins/discourse-events/test/javascripts/unit/services/embeddable-chat-test.js b/plugins/discourse-events/test/javascripts/unit/services/embeddable-chat-test.jsindex 892ff45f76a..62f7f4fcc66 100644--- a/plugins/discourse-events/test/javascripts/unit/services/embeddable-chat-test.js+++ b/plugins/discourse-events/test/javascripts/unit/services/embeddable-chat-test.js@@ -8,7 +8,9 @@ module("Unit | Service | embeddable-chat", function (hooks) {hooks.beforeEach(function () {const owner = getOwner(this);- this.topicController = { model: { chat_channel_id: 9 } };+ this.topicController = {+ model: { chat_channel_id: 9, livestream_chat_active: true },+ };owner.register("controller:topic", this.topicController, {instantiate: false,});@@ -102,6 +104,22 @@ module("Unit | Service | embeddable-chat", function (hooks) {assert.false(this.subject.showLivestreamHeaderChatIcon);});+ test("stops docking the chat once the livestream is over", function (assert) {+ this.capabilities.viewport.lg = false;+ this.router.currentRouteName = "topic.fromParams";+ this.topicController.model = {+ chat_channel_id: 9,+ livestream_chat_active: false,+ };++ assert.false(this.subject.showLivestreamHeaderChatIcon);+ assert.false(this.subject.useLivestreamLayout);+ assert.false(+ this.subject.canRenderChatChannel(true),+ "the chat is not embedded in the page either"+ );+ });+test("does not show the header chat icon without a channel", function (assert) {this.capabilities.viewport.lg = false;this.topicController.model = {};@@ -117,6 +135,7 @@ module("Unit | Service | embeddable-chat", function (hooks) {const event = { is_zoom_livestream: true, ends_at: null };this.topicController.model = {chat_channel_id: 9,+ livestream_chat_active: true,// The join button lives on the first post, which is not necessarily the// first post loaded into the stream.postStream: { posts: [{ post_number: 4 }, { post_number: 1, event }] },