Skip to content

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

FEATURE: Embedded Zoom webinar for livestream events (#40973)

Martin Brennan2ff5b99a4db3
diff --git a/AI-AGENTS.md b/AI-AGENTS.md
index 40c571de4a5..dd448063050 100644
--- a/AI-AGENTS.md
+++ b/AI-AGENTS.md
@@ -19,6 +19,7 @@ Discourse is large with long history. Understand context before changes.
- Use BEM for CSS, see ./docs/developer-guides/docs/03-code-internals/25-css-guidelines-bem.md
- Make display strings translatable (use placeholders, not split strings)
- Use "Sentence case" for strings, not "Proper Case" or "lower case"
+- Plugins/themes can't import npm modules directly; add the dependency to core and expose a `frontend/discourse/app/lib/load-*.js` wrapper that does the `import()` (see `load-morphlex.js`).
### Comments & Types
- Prefer self-documenting code. Comments should only be added when future misunderstanding is likely. They should be terse, and should describe 'why', not 'what'. They should not be used to describe history.
diff --git a/frontend/discourse/app/lib/load-zoom-meeting-sdk.js b/frontend/discourse/app/lib/load-zoom-meeting-sdk.js
new file mode 100644
index 00000000000..3808cc576d0
--- /dev/null
+++ b/frontend/discourse/app/lib/load-zoom-meeting-sdk.js
@@ -0,0 +1,14 @@
+/*
+Plugins & themes are unable to async-import npm modules directly.
+This wrapper provides them with a way to use the Zoom Meeting SDK, while keeping the `import()` in core's codebase.
+*/
+
+// Client View (`ZoomMtg`) - renders the full Zoom client UI.
+export async function loadZoomMeetingSdk() {
+ return (await import("@zoom/meetingsdk")).ZoomMtg;
+}
+
+// Component View (`ZoomMtgEmbedded`) - embeds Zoom inside a container element.
+export async function loadZoomMeetingSdkEmbedded() {
+ return (await import("@zoom/meetingsdk/embedded")).default;
+}
diff --git a/frontend/discourse/app/ui-kit/d-modal.gts b/frontend/discourse/app/ui-kit/d-modal.gts
index 7a43511e877..328dc464365 100644
--- a/frontend/discourse/app/ui-kit/d-modal.gts
+++ b/frontend/discourse/app/ui-kit/d-modal.gts
@@ -429,17 +429,25 @@ export default class DModal extends Component<DModalSignature> {
while (element && element !== this.#modalContainer) {
if (element.scrollHeight > element.clientHeight) {
- const { overflowY } = window.getComputedStyle(element);
-
- if (overflowY === "auto" || overflowY === "scroll") {
- if (swipeState.direction === "down" && element.scrollTop > 0) {
+ const style = window.getComputedStyle(element);
+
+ if (style.overflowY === "auto" || style.overflowY === "scroll") {
+ // column-reverse scrollers (e.g. chat messages) rest at scrollTop 0
+ // and go negative when scrolled back, so normalize scrollTop to a
+ // distance from the top edge before checking for remaining room
+ const maxScroll = element.scrollHeight - element.clientHeight;
+ const reversed =
+ style.display.includes("flex") &&
+ style.flexDirection === "column-reverse";
+ const distanceFromTop = reversed
+ ? maxScroll + element.scrollTop
+ : element.scrollTop;
+
+ if (swipeState.direction === "down" && distanceFromTop > 0) {
return true;
}
- if (
- swipeState.direction === "up" &&
- element.scrollTop + element.clientHeight < element.scrollHeight
- ) {
+ if (swipeState.direction === "up" && distanceFromTop < maxScroll) {
return true;
}
}
diff --git a/frontend/discourse/package.json b/frontend/discourse/package.json
index eb5f2d8485f..d39c17a0ce5 100644
--- a/frontend/discourse/package.json
+++ b/frontend/discourse/package.json
@@ -56,6 +56,7 @@
"@lezer/highlight": "^1.2.3",
"@lezer/javascript": "^1.5.4",
"@lezer/lr": "^1.4.8",
+ "@zoom/meetingsdk": "6.2.0",
"ace-builds": "^1.44.0",
"chart.js": "4.5.1",
"chartjs-adapter-moment": "^1.0.1",
@@ -94,6 +95,11 @@
"prosemirror-state": "^1.4.4",
"prosemirror-transform": "^1.12.0",
"prosemirror-view": "^1.41.8",
+ "react": "18.2.0",
+ "react-dom": "18.2.0",
+ "react-redux": "8.1.2",
+ "redux": "4.2.1",
+ "redux-thunk": "2.4.2",
"rete": "^2.0.6",
"rete-area-plugin": "^2.1.5",
"rete-connection-plugin": "^2.0.5",
diff --git a/package.json b/package.json
index ccab7aaace9..a9b5cccd18e 100644
--- a/package.json
+++ b/package.json
@@ -71,7 +71,8 @@
"@fullcalendar/moment-timezone>moment-timezone": "*"
},
"ignoreMissing": [
- "webpack"
+ "webpack",
+ "@types/react"
]
},
"overrides": {
diff --git a/plugins/discourse-calendar/app/controllers/discourse_calendar/livestream_controller.rb b/plugins/discourse-calendar/app/controllers/discourse_calendar/livestream_controller.rb
new file mode 100644
index 00000000000..0e1c9c6ef6b
--- /dev/null
+++ b/plugins/discourse-calendar/app/controllers/discourse_calendar/livestream_controller.rb
@@ -0,0 +1,21 @@
+# frozen_string_literal: true
+
+module DiscourseCalendar
+ class LivestreamController < ::ApplicationController
+ requires_plugin DiscourseCalendar::PLUGIN_NAME
+ requires_login
+
+ def prepare_zoom_signature
+ DiscourseCalendar::Livestream::PrepareZoomJoin.call(
+ service_params.deep_merge(params: { topic_id: params[:topic_id] }),
+ ) do |result|
+ on_success { |zoom_join_payload:| render json: zoom_join_payload }
+
+ on_model_not_found(:topic) { raise Discourse::NotFound }
+ on_failed_policy(:can_see_topic) { raise Discourse::NotFound }
+ on_failed_contract { raise Discourse::InvalidParameters }
+ on_failure { raise Discourse::NotFound }
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-calendar/app/models/discourse_post_event/event.rb b/plugins/discourse-calendar/app/models/discourse_post_event/event.rb
index b97a75ee5bd..4dd163fdf51 100644
--- a/plugins/discourse-calendar/app/models/discourse_post_event/event.rb
+++ b/plugins/discourse-calendar/app/models/discourse_post_event/event.rb
@@ -3,6 +3,10 @@
module DiscoursePostEvent
class Event < ActiveRecord::Base
PUBLIC_GROUP = "trust_level_0"
+ # Keep in sync with the constants of the same name in the
+ # DiscoursePostEventEvent JS model.
+ EARLY_ACCESS_MINUTES = 30
+ GRACE_PERIOD_MINUTES = 10
MIN_NAME_LENGTH = 5
MAX_NAME_LENGTH = 255
MAX_DESCRIPTION_LENGTH = 1000
@@ -27,7 +31,7 @@ module DiscoursePostEvent
# prepend so it runs before `dependent: :delete_all` wipes the invitees
before_destroy :reset_invitees_topic_tracking, prepend: true
after_commit :create_livestream_chat_channel, on: %i[create update]
- after_commit :warm_livestream_onebox, on: %i[create update]
+ after_commit :enqueue_warm_livestream_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_save do
@@ -72,12 +76,24 @@ module DiscoursePostEvent
DiscourseCalendar::Livestream.handle_topic_chat_channel_creation(post.topic)
end
- def warm_livestream_onebox
- return if !livestream? || location.blank?
- return if !saved_change_to_livestream? && !saved_change_to_location?
- return if Oneboxer.cached_onebox(location).present?
+ def has_cached_livestream_onebox?
+ livestream? && livestream_url.present? && Oneboxer.cached_onebox(livestream_url).present?
+ end
+
+ # Happens after the event record is saved to prepare the onebox
+ def enqueue_warm_livestream_onebox
+ return if !livestream? || livestream_url.blank?
+ return if !saved_change_to_livestream? && !saved_change_to_location? && !saved_change_to_url?
+ return if has_cached_livestream_onebox?
+ Jobs.enqueue(:warm_livestream_onebox, event_id: id, url: livestream_url)
+ end
- Jobs.enqueue(:warm_livestream_onebox, event_id: id, url: location)
+ # 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)
+ post&.publish_change_to_clients!(:revised)
end
def destroy_topic_custom_field
@@ -147,6 +163,24 @@ module DiscoursePostEvent
(ends_at || starts_at.end_of_day) <= Time.now
end
+ # Mirrors `currentlyWithinEventTimeframe` in the DiscoursePostEventEvent JS
+ # model: joining opens EARLY_ACCESS_MINUTES before the start and, when the
+ # event has an end time, closes GRACE_PERIOD_MINUTES after it.
+ def currently_within_event_timeframe?
+ return false if starts_at.nil?
+
+ now = Time.zone.now
+
+ if all_day
+ opens_at = starts_at.beginning_of_day
+ closes_at = starts_at.end_of_day
+ return opens_at <= now && now <= closes_at
+ end
+
+ return false if now < starts_at - EARLY_ACCESS_MINUTES.minutes
+ ends_at.nil? || now < ends_at + GRACE_PERIOD_MINUTES.minutes
+ end
+
def starts_at
return nil if recurring? && recurrence_until.present? && recurrence_until < Time.current
current_event_date&.starts_at || original_starts_at
@@ -525,6 +559,16 @@ module DiscoursePostEvent
timezone || DEFAULT_TIMEZONE
end
+ def livestream_url
+ location || url
+ end
+
+ def is_zoom_livestream?
+ return false unless SiteSetting.livestream_zoom_enabled
+ return false unless livestream?
+ DiscourseCalendar::Livestream::ZoomUrlParser.zoom_url?(livestream_url)
+ end
+
private
def reset_invitees_topic_tracking
diff --git a/plugins/discourse-calendar/app/serializers/discourse_post_event/event_serializer.rb b/plugins/discourse-calendar/app/serializers/discourse_post_event/event_serializer.rb
index 9904bc3a825..63de3564d2d 100644
--- a/plugins/discourse-calendar/app/serializers/discourse_post_event/event_serializer.rb
+++ b/plugins/discourse-calendar/app/serializers/discourse_post_event/event_serializer.rb
@@ -30,6 +30,11 @@ module DiscoursePostEvent
attributes :chat_enabled
attributes :livestream
attributes :livestream_onebox
+ attributes :livestream_url
+ # TODO (martin) We need to merge this and the event channel ID which
+ # comes from chat_enabled on the event, we dont need 2 channels per event
+ attributes :livestream_chat_channel_id
+ attributes :is_zoom_livestream
attributes :channel
attributes :rrule
attributes :max_attendees
@@ -37,12 +42,35 @@ module DiscoursePostEvent
has_one :image_upload, embed: :object, serializer: UploadSerializer
+ def livestream_enabled
+ object.livestream? && object.livestream_url.present?
+ end
+
def include_livestream_onebox?
- object.livestream? && object.location.present?
+ livestream_enabled && !object.is_zoom_livestream?
+ end
+
+ def include_livestream_chat_channel_id?
+ livestream_enabled
+ end
+
+ def include_livestream_url?
+ livestream_enabled
+ end
+
+ def is_zoom_livestream
+ object.is_zoom_livestream?
end
+ # Only ever reads the cache. Fetching here would put a blocking outbound
+ # request in the middle of serialization, once per event in a list. The
+ # `warm_livestream_onebox` job fills the cache and republishes the post.
def livestream_onebox
- Oneboxer.cached_onebox(object.location).presence
+ Oneboxer.cached_onebox(object.livestream_url).presence
+ end
+
+ def livestream_chat_channel_id
+ object.post.topic.topic_chat_channel&.id
end
def channel
diff --git a/plugins/discourse-calendar/app/serializers/discourse_post_event/event_topic_serializer.rb b/plugins/discourse-calendar/app/serializers/discourse_post_event/event_topic_serializer.rb
index 5094433caf3..48c81ce1330 100644
--- a/plugins/discourse-calendar/app/serializers/discourse_post_event/event_topic_serializer.rb
+++ b/plugins/discourse-calendar/app/serializers/discourse_post_event/event_topic_serializer.rb
@@ -6,5 +6,6 @@ module DiscoursePostEvent
attributes :id
attributes :title
+ attributes :slug
end
end
diff --git a/plugins/discourse-calendar/app/services/discourse_calendar/livestream/prepare_zoom_join.rb b/plugins/discourse-calendar/app/services/discourse_calendar/livestream/prepare_zoom_join.rb
new file mode 100644
index 00000000000..64f5a895067
--- /dev/null
+++ b/plugins/discourse-calendar/app/services/discourse_calendar/livestream/prepare_zoom_join.rb
@@ -0,0 +1,71 @@
+# frozen_string_literal: true
+
+class DiscourseCalendar::Livestream::PrepareZoomJoin
+ include Service::Base
+
+ params do
+ attribute :topic_id, :integer
+ # TODO (martin) ignore_timeframe backs the showzoom testing workaround,
+ # remove before merge
+ attribute :ignore_timeframe, :boolean, default: false
+
+ validates :topic_id, presence: true
+ end
+
+ policy :livestream_available
+ policy :zoom_enabled
+ model :topic
+ policy :can_see_topic
+ model :event
+ policy :event_has_livestream
+ policy :event_within_timeframe
+ model :zoom_join_data, :build_zoom_join_data
+ model :zoom_join_payload, :build_zoom_join_payload
+
+ private
+
+ def livestream_available
+ SiteSetting.chat_enabled && SiteSetting.calendar_enabled &&
+ SiteSetting.discourse_post_event_enabled
+ end
+
+ def zoom_enabled
+ SiteSetting.livestream_zoom_enabled && SiteSetting.livestream_zoom_sdk_key.present? &&
+ SiteSetting.livestream_zoom_sdk_secret.present?
+ end
+
+ def fetch_topic(params:)
+ Topic.includes(:tags, first_post: :event).find_by(id: params.topic_id)
+ end
+
+ def can_see_topic(topic:, guardian:)
+ guardian.can_see?(topic)
+ end
+
+ def fetch_event(topic:)
+ topic.first_post&.event
+ end
+
+ def event_has_livestream(event:)
+ event.livestream? && event.livestream_url.present?
+ end
+
+ def event_within_timeframe(event:, params:, guardian:)
+ # TODO (martin) showzoom is for testing only, remove before merge
+ return true if params.ignore_timeframe && guardian.is_staff?
+
+ event.currently_within_event_timeframe?
+ end
+
+ def build_zoom_join_data(event:)
+ DiscourseCalendar::Livestream::ZoomUrlParser.parse(event.livestream_url)
+ end
+
+ def build_zoom_join_payload(topic:, zoom_join_data:, guardian:)
+ DiscourseCalendar::Livestream::ZoomPayloadBuilder.call(
+ topic:,
+ zoom_join_data:,
+ user: guardian.user,
+ )
+ end
+end
diff --git a/plugins/discourse-calendar/app/services/discourse_calendar/livestream/zoom_payload_builder.rb b/plugins/discourse-calendar/app/services/discourse_calendar/livestream/zoom_payload_builder.rb
new file mode 100644
index 00000000000..3ca86934349
--- /dev/null
+++ b/plugins/discourse-calendar/app/services/discourse_calendar/livestream/zoom_payload_builder.rb
@@ -0,0 +1,70 @@
+# frozen_string_literal: true
+
+module DiscourseCalendar
+ module Livestream
+ # Builds the payload the client needs to join a Zoom meeting through the
+ # Meeting SDK, including a signed JWT auth token.
+ # See https://developers.zoom.us/docs/meeting-sdk/auth/ for details on each
+ # of the token fields.
+ class ZoomPayloadBuilder < Service::ActionBase
+ ROLE_PARTICIPANT = 0
+ TOKEN_ISSUE_LEEWAY = 30.seconds
+ TOKEN_VALIDITY = 2.hours
+
+ option :topic
+
+ # The user joining the zoom meeting as an attendee
+ option :user
+
+ # Parsed from a zoom URL via DiscourseCalendar::Livestream::ZoomUrlParser
+ option :zoom_join_data
+
+ def call
+ {
+ sdk_key: sdk_key,
+ signature: signature,
+ meeting_number: zoom_join_data[:meeting_number],
+ password: zoom_join_data[:password],
+ user_name: user.display_name,
+ user_email: user.email,
+ leave_url: topic.relative_url,
+ }
+ end
+
+ private
+
+ def signature
+ JWT.encode(
+ jwt_payload,
+ SiteSetting.livestream_zoom_sdk_secret,
+ "HS256",
+ { alg: "HS256", typ: "JWT" },
+ )
+ end
+
+ def jwt_payload
+ {
+ sdkKey: sdk_key,
+ appKey: sdk_key,
+ mn: zoom_join_data[:meeting_number],
+ role: ROLE_PARTICIPANT,
+ iat: issued_at,
+ exp: expires_at,
+ tokenExp: expires_at,
+ }
+ end
+
+ def issued_at
+ @issued_at ||= Time.zone.now.to_i - TOKEN_ISSUE_LEEWAY.to_i
+ end
+
+ def expires_at
+ issued_at + TOKEN_VALIDITY.to_i
+ end
+
+ def sdk_key
+ SiteSetting.livestream_zoom_sdk_key
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/index.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/index.gjs
index b89f9d0073e..9f87e582803 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/index.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/index.gjs
@@ -402,10 +402,12 @@ export default class DiscoursePostEvent extends Component {
<StatusPlaceholder />
{{/if}}
- {{#if event.livestream}}
- {{bodyClass "livestream-topic"}}
- {{/if}}
- <Livestream @event={{event}} />
+ {{#unless @hideLivestreamVideo}}
+ {{#if event.livestream}}
+ {{bodyClass "livestream-topic"}}
+ {{/if}}
+ <Livestream @event={{event}} />
+ {{/unless}}
</PluginOutlet>
{{/if}}
</div>
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/livestream.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/livestream.gjs
index 4ca6f9804e6..ad2c45d8672 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/livestream.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/discourse-post-event/livestream.gjs
@@ -1,7 +1,10 @@
import Component from "@glimmer/component";
import { service } from "@ember/service";
import { trustHTML } from "@ember/template";
+import { isEmpty } from "@ember/utils";
import { optionalRequire } from "discourse/lib/utilities";
+import { eventHasLivestream } from "../../lib/livestream-utils";
+import LivestreamZoomEntry from "../livestream/zoom-entry";
// 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_
@@ -12,10 +15,13 @@ export default class Livestream extends Component {
@service siteSettings;
get show() {
+ return eventHasLivestream(this.args.event);
+ }
+
+ get isZoomLivestream() {
return (
- this.args.event?.livestream &&
- this.args.event?.location &&
- this.args.event?.livestreamOnebox
+ this.siteSettings.livestream_zoom_enabled &&
+ this.args.event?.isZoomLivestream
);
}
@@ -49,6 +55,10 @@ export default class Livestream extends Component {
: null;
}
+ get hasLivestreamOnebox() {
+ return !isEmpty(this.args.event?.livestreamOnebox);
+ }
+
get oneboxHtml() {
return this.videoAttributes
? null
@@ -58,10 +68,14 @@ export default class Livestream extends Component {
<template>
{{#if this.show}}
<section class="event__section event-livestream">
- {{#if this.videoAttributes}}
- <this.lazyVideo @videoAttributes={{this.videoAttributes}} />
- {{else}}
- {{this.oneboxHtml}}
+ {{#if this.isZoomLivestream}}
+ <LivestreamZoomEntry @event={{@event}} />
+ {{else if this.hasLivestreamOnebox}}
+ {{#if this.videoAttributes}}
+ <this.lazyVideo @videoAttributes={{this.videoAttributes}} />
+ {{else}}
+ {{this.oneboxHtml}}
+ {{/if}}
{{/if}}
</section>
{{/if}}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/embeddable-chat-channel.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/embeddable-chat-channel.gjs
index 49a52e52a2b..25e45ea824d 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/embeddable-chat-channel.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/embeddable-chat-channel.gjs
@@ -1,6 +1,7 @@
import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
import { array } from "@ember/helper";
+import { action } from "@ember/object";
import { service } from "@ember/service";
import { modifier } from "ember-modifier";
import { bind } from "discourse/lib/decorators";
@@ -54,6 +55,20 @@ export default class EmbedableChatChannel extends Component {
this.activeChannel.currentUserMembership = membership;
}
+ get showCloseButton() {
+ return this.args.onClose || !this.embeddableChat.isMobileModal;
+ }
+
+ @action
+ close() {
+ if (this.args.onClose) {
+ this.args.onClose();
+ return;
+ }
+
+ this.embeddableChat.toggleChatVisibility();
+ }
+
<template>
<div
id="custom-chat-container"
@@ -63,17 +78,17 @@ export default class EmbedableChatChannel extends Component {
}}
{{this.updateChannel}}
>
- {{#unless this.embeddableChat.isMobileModal}}
+ {{#if this.showCloseButton}}
<div class="c-navbar-container livestream-chat-close">
<DButton
@icon="xmark"
- @action={{this.embeddableChat.toggleChatVisibility}}
+ @action={{this.close}}
@title="chat.close"
class="btn-transparent no-text c-navbar__close-drawer-button"
/>
</div>
- {{/unless}}
+ {{/if}}
<div class="chat-drawer">
{{#if (and this.activeChannel ChatChannel)}}
{{#each (array this.activeChannel) as |channel|}}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/modal/mobile-embeddable-chat-modal.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/modal/mobile-embeddable-chat-modal.gjs
index 192fadeaa08..7b0388f4116 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/modal/mobile-embeddable-chat-modal.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/modal/mobile-embeddable-chat-modal.gjs
@@ -1,14 +1,14 @@
import Component from "@glimmer/component";
-import { inject as controller } from "@ember/controller";
import didUpdate from "@ember/render-modifiers/modifiers/did-update";
import { service } from "@ember/service";
+import { modifier } from "ember-modifier";
+import { lock, unlock } from "discourse/lib/body-scroll-lock";
import DModal from "discourse/ui-kit/d-modal";
import EmbeddableChatChannel from "../embeddable-chat-channel";
export default class MobileEmbeddableChatModal extends Component {
@service embeddableChat;
@service capabilities;
- @controller("topic") topicController;
checkAndCloseModal = () => {
if (this.capabilities.viewport.lg) {
@@ -16,8 +16,54 @@ export default class MobileEmbeddableChatModal extends Component {
}
};
+ // DModal locks body scrolling while open, and on iOS that lock blocks touch
+ // scrolling everywhere except elements registered with `lock()`. The modal
+ // registers its own body, but the element that actually scrolls here is
+ // chat's nested `.chat-messages-scroller`, so it has to be registered too —
+ // as `reverseColumn`, since it's a column-reverse scroller.
+ lockChatScroller = modifier((element) => {
+ if (!this.capabilities.isIOS) {
+ return;
+ }
+
+ let scroller = null;
+
+ const lockScroller = () => {
+ const currentScroller = element.querySelector(".chat-messages-scroller");
+
+ if (currentScroller === scroller) {
+ return;
+ }
+
+ if (scroller) {
+ unlock(scroller);
+ }
+
+ scroller = currentScroller;
+
+ if (scroller) {
+ lock(scroller, { reverseColumn: true });
+ }
+ };
+
+ lockScroller();
+
+ const observer = new MutationObserver(lockScroller);
+ observer.observe(element, { childList: true, subtree: true });
+
+ return () => {
+ observer.disconnect();
+
+ if (scroller) {
+ unlock(scroller);
+ }
+ };
+ });
+
get shouldRender() {
- return this.embeddableChat.canRenderChatChannel(this.topicController, true);
+ return this.embeddableChat.canRenderChatChannel(
+ this.embeddableChat.isMobileViewport
+ );
}
<template>
@@ -26,11 +72,13 @@ export default class MobileEmbeddableChatModal extends Component {
class="livestream-chat-modal"
@hideHeader={{true}}
{{didUpdate this.checkAndCloseModal this.capabilities.viewport.lg}}
+ {{this.lockChatScroller}}
>
<:body>
{{#if this.shouldRender}}
<EmbeddableChatChannel
@chatChannelId={{this.embeddableChat.chatChannelId}}
+ @onClose={{@closeModal}}
/>
{{/if}}
</:body>
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/responsive-livestream-chat-icon.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/responsive-livestream-chat-icon.gjs
index 1102409e82f..95b1442a799 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/responsive-livestream-chat-icon.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/responsive-livestream-chat-icon.gjs
@@ -1,16 +1,13 @@
import Component from "@glimmer/component";
-import { inject as controller } from "@ember/controller";
import { service } from "@ember/service";
import MobileLivestreamChatIcon from "./mobile-livestream-chat-icon";
export default class ResponsiveLivestreamChatIcon extends Component {
- @service capabilities;
- @controller("topic") topicController;
+ @service embeddableChat;
get shouldShow() {
return (
- !this.capabilities.viewport.lg &&
- this.topicController?.model?.chat_channel_id
+ this.embeddableChat.isMobileViewport && this.embeddableChat.chatChannelId
);
}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/zoom-entry.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/zoom-entry.gjs
new file mode 100644
index 00000000000..484b6d47303
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/zoom-entry.gjs
@@ -0,0 +1,179 @@
+import Component from "@glimmer/component";
+import { array } from "@ember/helper";
+import { action } from "@ember/object";
+import { getOwner } from "@ember/owner";
+import { service } from "@ember/service";
+import { isEmpty } from "@ember/utils";
+import { bind } from "discourse/lib/decorators";
+import DButton from "discourse/ui-kit/d-button";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
+import { i18n } from "discourse-i18n";
+import ZoomMeetingSession from "../../lib/zoom-meeting-session";
+import zoomComponentViewLayout from "../../modifiers/zoom-component-view-layout";
+
+export default class LivestreamZoomEntry extends Component {
+ @service appEvents;
+ @service capabilities;
+ @service currentUser;
+ @service discoursePostEventApi;
+ @service siteSettings;
+
+ session = new ZoomMeetingSession(getOwner(this), {
+ topicId: this.topic.id,
+ canJoin: () => this.canJoinNow,
+ onBeforeJoinAttempt: this.markAsGoing,
+ });
+
+ willDestroy() {
+ super.willDestroy(...arguments);
+ this.session.teardown();
+ }
+
+ get topic() {
+ return this.args.event.post.topic;
+ }
+
+ get shouldRender() {
+ return (
+ this.siteSettings.livestream_zoom_enabled &&
+ this.currentUser &&
+ this.args.event.livestreamChatChannelId &&
+ !this.args.event.pastEventTimeframe
+ );
+ }
+
+ get canJoinNow() {
+ return (
+ this.args.event.currentlyWithinEventTimeframe ||
+ // TODO (martin) showzoom is for testing only, remove before merge
+ new URLSearchParams(window.location.search).get("showzoom")
+ );
+ }
+
+ get isDesktop() {
+ return this.capabilities.viewport.lg;
+ }
+
+ get showFallbackLink() {
+ return !isEmpty(this.session.errorMessage);
+ }
+
+ get joinDisabled() {
+ return (
+ this.session.isJoining ||
+ this.session.isWaitingForStart ||
+ !this.canJoinNow
+ );
+ }
+
+ // Attendance is what follows a user into the livestream chat channel, so
+ // someone who joins the webinar without ever answering the RSVP would sit in
+ // front of a read-only chat. Anyone who has already made a choice, including
+ // an explicit "not going", keeps it.
+ @bind
+ async markAsGoing() {
+ const event = this.args.event;
+
+ if (!event.canUpdateAttendance || event.watchingInvitee?.status) {
+ return;
+ }
+
+ const payload = { status: "going" };
+ const appEventData = { status: payload.status, postId: event.id };
+
+ if (event.watchingInvitee) {
+ await this.discoursePostEventApi.updateEventAttendance(event, payload);
+ this.appEvents.trigger("calendar:update-invitee-status", appEventData);
+ } else {
+ await this.discoursePostEventApi.joinEvent(event, payload);
+ this.appEvents.trigger("calendar:create-invitee-status", appEventData);
+ }
+ }
+
+ @action
+ joinZoom() {
+ this.session.join();
+ }
+
+ <template>
+ {{#if this.shouldRender}}
+ <div class="discourse-calendar-livestream-zoom-entry">
+ {{#if this.isDesktop}}
+ <div class="discourse-calendar-livestream-zoom-entry__actions">
+ {{#unless this.session.isJoined}}
+ <DButton
+ @action={{this.joinZoom}}
+ @label="discourse_calendar.livestream.zoom.join"
+ @icon="video"
+ class="btn-primary"
+ @disabled={{this.joinDisabled}}
+ />
+ {{/unless}}
+
+ {{#unless this.canJoinNow}}
+ <p class="discourse-calendar-livestream-zoom-entry__waiting">
+ {{i18n "discourse_calendar.livestream.zoom.too_early"}}
+ </p>
+ {{/unless}}
+
+ {{#if this.session.isWaitingForStart}}
+ <p class="discourse-calendar-livestream-zoom-entry__waiting">
+ {{i18n
+ "discourse_calendar.livestream.zoom.not_started_retrying"
+ count=this.session.retryCountdown
+ }}
+ </p>
+ {{else if this.session.isRetryingNow}}
+ <p class="discourse-calendar-livestream-zoom-entry__waiting">
+ {{i18n
+ "discourse_calendar.livestream.zoom.not_started_trying_again"
+ }}
+ </p>
+ {{/if}}
+
+ {{#if this.session.errorMessage}}
+ <p class="discourse-calendar-livestream-zoom-entry__error">
+ {{this.session.errorMessage}}
+ </p>
+ {{/if}}
+
+ {{#if this.showFallbackLink}}
+ <DButton
+ class="btn-default"
+ @href={{@event.livestreamUrl}}
+ @label="discourse_calendar.livestream.zoom.open_in_zoom"
+ @icon="up-right-from-square"
+ />
+ {{/if}}
+ </div>
+
+ <div
+ class={{dConcatClass
+ "discourse-calendar-livestream-zoom-entry__frame"
+ (if this.session.showZoomFrame "--visible")
+ (if this.session.isJoined "--joined")
+ }}
+ {{zoomComponentViewLayout this.session this.isDesktop}}
+ ></div>
+ {{else}}
+ <div class="discourse-calendar-livestream-zoom-entry__actions">
+ <DButton
+ @route="topic-zoom"
+ @routeModels={{array this.topic.slug this.topic.id}}
+ @label="discourse_calendar.livestream.zoom.join"
+ @icon="video"
+ class="btn-primary"
+ @disabled={{this.joinDisabled}}
+ />
+
+ {{#unless this.canJoinNow}}
+ <p class="discourse-calendar-livestream-zoom-entry__waiting">
+ {{i18n "discourse_calendar.livestream.zoom.too_early"}}
+ </p>
+ {{/unless}}
+ </div>
+ {{/if}}
+ </div>
+ {{/if}}
+ </template>
+}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/zoom-page.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/zoom-page.gjs
new file mode 100644
index 00000000000..e7015f1902e
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/components/livestream/zoom-page.gjs
@@ -0,0 +1,218 @@
+import Component from "@glimmer/component";
+import { tracked } from "@glimmer/tracking";
+import { on } from "@ember/modifier";
+import { action } from "@ember/object";
+import { service } from "@ember/service";
+import { modifier } from "ember-modifier";
+import bodyClass from "discourse/helpers/body-class";
+import getURL from "discourse/lib/get-url";
+import { wantsNewWindow } from "discourse/lib/intercept-click";
+import { loadZoomMeetingSdk } from "discourse/lib/load-zoom-meeting-sdk";
+import DButton from "discourse/ui-kit/d-button";
+import { i18n } from "discourse-i18n";
+import DiscoursePostEvent from "discourse/plugins/discourse-calendar/discourse/components/discourse-post-event";
+import DiscoursePostEventEvent from "discourse/plugins/discourse-calendar/discourse/models/discourse-post-event-event";
+import fetchZoomJoinPayload from "../../lib/fetch-zoom-join-payload";
+import { isWithinEventTimeframe } from "../../models/discourse-post-event-event";
+import MobileEmbeddableChatModal from "./modal/mobile-embeddable-chat-modal";
+
+export default class LivestreamZoomPage extends Component {
+ @service modal;
+ @service siteSettings;
+
+ @tracked errorMessage;
+
+ // Plain (non-tracked) guard so the modifier can read and set it within the
+ // same render without triggering a tracked-property backtracking assertion.
+ // It is only used to ensure the SDK is set up once, never rendered.
+ hasLoaded = false;
+
+ setupZoom = modifier(async () => {
+ if (this.hasLoaded || !this.canJoinNow) {
+ return;
+ }
+
+ this.hasLoaded = true;
+ await this.loadZoom();
+ });
+
+ get post() {
+ return this.args.topic?.postStream?.posts?.[0];
+ }
+
+ get event() {
+ if (!this.post?.event) {
+ return null;
+ }
+
+ return DiscoursePostEventEvent.create(this.post.event);
+ }
+
+ // The join button on the topic page is disabled outside this window, but the
+ // route can be reached directly at any time, so the gate has to be applied
+ // here too. The server enforces the same window when issuing a signature.
+ get canJoinNow() {
+ return (
+ isWithinEventTimeframe(
+ this.event?.allDay,
+ this.event?.startsAt,
+ this.event?.endsAt
+ ) ||
+ // TODO (martin) showzoom is for testing only, remove before merge
+ new URLSearchParams(window.location.search).get("showzoom")
+ );
+ }
+
+ get zoomUrl() {
+ return this.event?.livestreamUrl;
+ }
+
+ get mobileLeaveUrl() {
+ return getURL(
+ `/t/${this.args.topic.slug}/${this.args.topic.id}/zoom?zoom_left=1`
+ );
+ }
+
+ get retryZoomRoute() {
+ return getURL(`/t/${this.args.topic.slug}/${this.args.topic.id}/zoom`);
+ }
+
+ get topicUrl() {
+ return getURL(
+ this.args.topic.url || `/t/${this.args.topic.slug}/${this.args.topic.id}`
+ );
+ }
+
+ get returnedFromZoom() {
+ return new URLSearchParams(window.location.search).has("zoom_left");
+ }
+
+ @action
+ async loadZoom() {
+ if (this.returnedFromZoom) {
+ this.errorMessage = i18n("discourse_calendar.livestream.zoom.load_error");
+ return;
+ }
+
+ try {
+ const payload = await fetchZoomJoinPayload(this.args.topic.id);
+ const ZoomMtg = await loadZoomMeetingSdk();
+
+ ZoomMtg.preLoadWasm();
+ ZoomMtg.prepareWebSDK();
+ ZoomMtg.i18n.load("en-US");
+ ZoomMtg.i18n.reload("en-US");
+
+ await new Promise((resolve, reject) => {
+ ZoomMtg.init({
+ leaveUrl: this.mobileLeaveUrl,
+ patchJsMedia: true,
+ disableCallOut: true,
+ success: resolve,
+ error: reject,
+ });
+ });
+
+ await new Promise((resolve, reject) => {
+ ZoomMtg.join({
+ signature: payload.signature,
+ sdkKey: payload.sdk_key,
+ meetingNumber: payload.meeting_number,
+ passWord: payload.password || "",
+ userName: payload.user_name,
+ userEmail: payload.user_email,
+ success: resolve,
+ error: reject,
+ });
+ });
+ } catch {
+ this.errorMessage = i18n("discourse_calendar.livestream.zoom.load_error");
+ }
+ }
+
+ get canOpenChat() {
+ return this.args.topic?.chat_channel_id && this.siteSettings.chat_enabled;
+ }
+
+ @action
+ openChat() {
+ this.modal.show(MobileEmbeddableChatModal);
+ }
+
+ @action
+ retryZoom() {
+ window.location.assign(this.retryZoomRoute);
+ }
+
+ @action
+ viewTopic(event) {
+ if (wantsNewWindow(event)) {
+ return;
+ }
+
+ event.preventDefault();
+ window.location.assign(this.topicUrl);
+ }
+
+ <template>
+ {{bodyClass "discourse-calendar-livestream-zoom-full"}}
+ <div class="discourse-calendar-livestream-zoom-page">
+ {{#if this.canJoinNow}}
+ {{#if this.errorMessage}}
+ <div class="discourse-calendar-livestream-zoom-page__fallback">
+ <p>{{this.errorMessage}}</p>
+
+ <DButton
+ @href={{this.zoomUrl}}
+ @label="discourse_calendar.livestream.zoom.open_in_zoom"
+ @icon="up-right-from-square"
+ />
+
+ {{#if this.returnedFromZoom}}
+ <DButton
+ @action={{this.retryZoom}}
+ @label="discourse_calendar.livestream.zoom.join"
+ @icon="video"
+ class="btn-primary"
+ />
+ {{/if}}
+ </div>
+ {{/if}}
+
+ <div
+ class="discourse-calendar-livestream-zoom-page__frame"
+ {{this.setupZoom}}
+ ></div>
+ {{else}}
+ <div class="discourse-calendar-livestream-zoom-page__waiting-wrapper">
+ <p class="discourse-calendar-livestream-zoom-page__waiting">
+ {{i18n "discourse_calendar.livestream.zoom.too_early"}}
+ <a
+ href={{this.topicUrl}}
+ class="raw-link"
+ {{on "click" this.viewTopic}}
+ >
+ {{i18n "discourse_calendar.livestream.zoom.view_topic"}}
+ </a>
+ </p>
+
+ <DiscoursePostEvent
+ @event={{this.event}}
+ @post={{this.post}}
+ @hideLivestreamVideo={{true}}
+ />
+ </div>
+
+ {{/if}}
+
+ {{#if this.canOpenChat}}
+ <DButton
+ class="discourse-calendar-livestream-zoom-page__chat-button btn-primary"
+ @action={{this.openChat}}
+ @label="discourse_calendar.livestream.zoom.chat"
+ @icon="comments"
+ />
+ {{/if}}
+ </div>
+ </template>
+}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/connectors/before-main-outlet/embeddable-chat-channel-connector.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/connectors/before-main-outlet/embeddable-chat-channel-connector.gjs
index fca2e82b0d1..3295a7afcc3 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/connectors/before-main-outlet/embeddable-chat-channel-connector.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/connectors/before-main-outlet/embeddable-chat-channel-connector.gjs
@@ -1,5 +1,4 @@
import Component from "@glimmer/component";
-import { inject as controller } from "@ember/controller";
import { service } from "@ember/service";
import EmbeddableChatChannel from "../../components/livestream/embeddable-chat-channel";
@@ -7,7 +6,7 @@ export default class EmbedableChatChannelConnector extends Component {
@service embeddableChat;
@service siteSettings;
@service capabilities;
- @controller("topic") topicController;
+ @service router;
get shouldRender() {
const mobileViewport =
@@ -18,10 +17,15 @@ export default class EmbedableChatChannelConnector extends Component {
return false;
}
- return this.embeddableChat.canRenderChatChannel(
- this.topicController,
- mobileViewport
- );
+ if (this.isZoomRoute) {
+ return false;
+ }
+
+ return this.embeddableChat.canRenderChatChannel(mobileViewport);
+ }
+
+ get isZoomRoute() {
+ return this.router.currentRouteName === "topic-zoom";
}
<template>
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/connectors/chat-join-channel-button/join-channel-message.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/connectors/chat-join-channel-button/join-channel-message.gjs
index b33a58f1401..3dfdccc8600 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/connectors/chat-join-channel-button/join-channel-message.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/connectors/chat-join-channel-button/join-channel-message.gjs
@@ -14,12 +14,14 @@ export default class JoinChannelMessage extends Component {
<template>
{{#if this.shouldRenderJoinText}}
- <h2>
- {{i18n "discourse_calendar.livestream.chat.join_channel_header"}}
- </h2>
- <p>
- {{i18n "discourse_calendar.livestream.chat.join_channel_message"}}
- </p>
+ <div class="livestream-join-channel-message">
+ <h2>
+ {{i18n "discourse_calendar.livestream.chat.join_channel_header"}}
+ </h2>
+ <p>
+ {{i18n "discourse_calendar.livestream.chat.join_channel_message"}}
+ </p>
+ </div>
{{else}}
{{yield}}
{{/if}}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/discourse-calendar-topic-zoom-route-map.js b/plugins/discourse-calendar/assets/javascripts/discourse/discourse-calendar-topic-zoom-route-map.js
new file mode 100644
index 00000000000..3a3fe17bb19
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/discourse-calendar-topic-zoom-route-map.js
@@ -0,0 +1,6 @@
+// Registered as a top-level route (rather than nested under `topic`) because the
+// core topic template has no router `{{outlet}}` for a child route to render
+// into. This renders the full-page Zoom view into the application's main outlet.
+export default function () {
+ this.route("topic-zoom", { path: "/t/:slug/:topic_id/zoom" });
+}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/initializers/discourse-post-event-decorator.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/initializers/discourse-post-event-decorator.gjs
index 0d3a8a54409..76ee09c97aa 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/initializers/discourse-post-event-decorator.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/initializers/discourse-post-event-decorator.gjs
@@ -55,6 +55,15 @@ function initializeDiscoursePostEventDecorator(api) {
return;
}
+ let hideLivestreamVideo = false;
+ if (
+ postEventNode.parentElement.classList.contains(
+ "post__contents-cooked-quote"
+ )
+ ) {
+ hideLivestreamVideo = true;
+ }
+
const wrapper = document.createElement("div");
postEventNode.before(wrapper);
@@ -63,7 +72,11 @@ function initializeDiscoursePostEventDecorator(api) {
helper.renderGlimmer(
wrapper,
<template>
- <DiscoursePostEvent @event={{event}} @post={{post}} />
+ <DiscoursePostEvent
+ @event={{event}}
+ @post={{post}}
+ @hideLivestreamVideo={{hideLivestreamVideo}}
+ />
</template>
);
}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/lib/fetch-zoom-join-payload.js b/plugins/discourse-calendar/assets/javascripts/discourse/lib/fetch-zoom-join-payload.js
new file mode 100644
index 00000000000..4d248ab82ed
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/lib/fetch-zoom-join-payload.js
@@ -0,0 +1,14 @@
+import { ajax } from "discourse/lib/ajax";
+
+export default function fetchZoomJoinPayload(topicId) {
+ const data = { topic_id: topicId };
+
+ // TODO (martin) showzoom is for testing only, remove before merge
+ if (new URLSearchParams(window.location.search).get("showzoom")) {
+ data.ignore_timeframe = true;
+ }
+
+ return ajax("/discourse-calendar/livestream/zoom/signature.json", {
+ data,
+ });
+}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/lib/livestream-utils.js b/plugins/discourse-calendar/assets/javascripts/discourse/lib/livestream-utils.js
new file mode 100644
index 00000000000..f68a1e8348c
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/lib/livestream-utils.js
@@ -0,0 +1,9 @@
+import { isEmpty } from "@ember/utils";
+
+export function eventHasLivestream(event) {
+ if (!event) {
+ return false;
+ }
+
+ return event.livestream && !isEmpty(event.livestreamUrl);
+}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/lib/raw-event-helper.js b/plugins/discourse-calendar/assets/javascripts/discourse/lib/raw-event-helper.js
index 6ae205c991d..57f09a9aac2 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/lib/raw-event-helper.js
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/lib/raw-event-helper.js
@@ -1,6 +1,12 @@
-// must be an https link to livestream
-export function isLivestreamUrl(location) {
- return /^https?:\/\//i.test(location ?? "");
+// `([\w-]+\.)*` allows any subdomain, since livestream hosts routinely use them
+// (us06web.zoom.us, www.youtube.com). It cannot match a host that merely ends in
+// one of these names, because each captured label must be followed by a dot:
+// "notzoom.us" and "zoom.us.evil.com" are both rejected.
+const LIVESTREAM_URL =
+ /^(https?:\/\/)?([\w-]+\.)*(youtube\.com|youtu\.be|twitch\.tv|zoom\.us|kick\.com|tiktok\.com|instagram\.com|facebook\.com)\//i;
+
+export function isLivestreamUrl(url) {
+ return LIVESTREAM_URL.test(url ?? "");
}
export function defaultReminderFor({ startsAt, endsAt, allDay } = {}) {
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/lib/zoom-component-view-dom.js b/plugins/discourse-calendar/assets/javascripts/discourse/lib/zoom-component-view-dom.js
new file mode 100644
index 00000000000..75e4f5339cd
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/lib/zoom-component-view-dom.js
@@ -0,0 +1,108 @@
+// Workarounds for the DOM that Zoom's embedded (component view) SDK renders
+// into our app root. Everything in here reaches into Zoom's internal MUI
+// markup, which the SDK offers no supported hooks for, so all of it is flaky
+// by nature if the SDK changes.
+
+const VIDEO_ASPECT_RATIO = 16 / 9;
+const MIN_VIDEO_WIDTH = 240;
+const MAX_VIDEO_WIDTH = 1440;
+const MIN_VIDEO_HEIGHT = 135;
+const MAX_VIDEO_HEIGHT = 810;
+
+export function computeZoomViewSize(root) {
+ const width = Math.max(
+ MIN_VIDEO_WIDTH,
+ Math.min(
+ MAX_VIDEO_WIDTH,
+ Math.floor(root?.getBoundingClientRect().width || 0)
+ )
+ );
+
+ const height = Math.max(
+ MIN_VIDEO_HEIGHT,
+ Math.min(MAX_VIDEO_HEIGHT, Math.floor(width / VIDEO_ASPECT_RATIO))
+ );
+
+ return { width, height };
+}
+
+// `title` is Zoom's translated `toolbar_leave` string, stable only because
+// the component view is pinned to en-US when it is initialized. The button
+// carries no
+// other distinguishing attribute.
+export function isZoomLeaveButtonClick(event) {
+ return event.target.closest("button.zoom-MuiButton-root")?.title === "Leave";
+}
+
+function setInlineStyleValue(element, property, value) {
+ if (!element || element.style[property] === value) {
+ return;
+ }
+
+ element.style[property] = value;
+}
+
+function setInlineHeight(element, height) {
+ setInlineStyleValue(element, "height", `${height}px`);
+}
+
+export function syncZoomLayout(root) {
+ if (!root) {
+ return;
+ }
+
+ const widget = root.querySelector(
+ '[role="region"][aria-label="Zoom Web SDK Widget"]'
+ );
+ const widgetHeight = Math.ceil(widget?.getBoundingClientRect().height || 0);
+
+ if (widgetHeight > 0) {
+ setInlineHeight(root, widgetHeight);
+ }
+
+ const playerContainers = root.querySelectorAll("video-player-container");
+ const galleryPanel = root.querySelector(
+ '[id^="suspension-view-tabpanel-gallery"]'
+ );
+
+ if (!galleryPanel || playerContainers.length !== 1) {
+ return;
+ }
+
+ const player = playerContainers[0];
+ const playerWrapper = player.parentElement;
+ const gridWrapper = playerWrapper?.parentElement;
+ const innerPaper = galleryPanel.parentElement;
+ const outerPaper = innerPaper?.parentElement;
+ const resizable = outerPaper?.parentElement;
+ const absoluteBox = resizable?.parentElement;
+ const toolbar = innerPaper?.querySelector(".zoom-MuiToolbar-root");
+ const footer = Array.from(outerPaper?.children || []).find(
+ (element) => element !== innerPaper
+ );
+
+ const playerHeight = Math.ceil(player.getBoundingClientRect().height || 0);
+ const toolbarHeight = Math.ceil(toolbar?.getBoundingClientRect().height || 0);
+ const footerHeight = Math.ceil(footer?.getBoundingClientRect().height || 0);
+ const innerHeight = toolbarHeight + playerHeight;
+ const outerHeight = innerHeight + footerHeight + 4;
+
+ if (!playerHeight || !innerHeight || !outerHeight) {
+ return;
+ }
+
+ // Zoom's component view currently centers a single tile inside the
+ // gallery-limited panel. Collapse that wrapper so the lone presenter tile
+ // sits directly below the toolbar instead of midway down the component view.
+ setInlineStyleValue(player, "top", "0px");
+ setInlineStyleValue(player, "bottom", "auto");
+
+ [playerWrapper, gridWrapper, galleryPanel].forEach((element) => {
+ setInlineHeight(element, playerHeight);
+ });
+
+ setInlineHeight(innerPaper, innerHeight);
+ [outerPaper, resizable, absoluteBox, root].forEach((element) => {
+ setInlineHeight(element, outerHeight);
+ });
+}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/lib/zoom-error.js b/plugins/discourse-calendar/assets/javascripts/discourse/lib/zoom-error.js
new file mode 100644
index 00000000000..d54e6de56f0
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/lib/zoom-error.js
@@ -0,0 +1,31 @@
+export const MEETING_NOT_STARTED_ERROR_CODE = 3008;
+
+export function serializeZoomError(error) {
+ if (!error) {
+ return { message: "Unknown Zoom error" };
+ }
+
+ if (typeof error === "string") {
+ return { message: error };
+ }
+
+ // The reason string is what the SDK returns today, the code is the stable
+ // identifier.
+ const meetingNotStarted =
+ error.reason === "Meeting has not started" ||
+ error.errorCode === MEETING_NOT_STARTED_ERROR_CODE;
+
+ return {
+ name: error.name,
+ message: error.message,
+ type: error.type,
+ reason: error.reason,
+ errorCode: error.errorCode,
+ status: error.status,
+ stack: error.stack,
+ meetingNotStarted,
+ ...Object.fromEntries(
+ Object.entries(error).filter(([, value]) => typeof value !== "function")
+ ),
+ };
+}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/lib/zoom-meeting-session.js b/plugins/discourse-calendar/assets/javascripts/discourse/lib/zoom-meeting-session.js
new file mode 100644
index 00000000000..c50dcb655a4
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/lib/zoom-meeting-session.js
@@ -0,0 +1,243 @@
+import { tracked } from "@glimmer/tracking";
+import { setOwner } from "@ember/owner";
+import { loadZoomMeetingSdkEmbedded } from "discourse/lib/load-zoom-meeting-sdk";
+import { i18n } from "discourse-i18n";
+import fetchZoomJoinPayload from "./fetch-zoom-join-payload";
+import { computeZoomViewSize, syncZoomLayout } from "./zoom-component-view-dom";
+import { serializeZoomError } from "./zoom-error";
+
+const DEFAULT_VIEW_TYPE = "speaker";
+export const RETRY_DELAY_SECONDS = 30;
+export const MAX_RETRY_ATTEMPTS = 40;
+
+// Owns the Zoom embedded SDK client for one livestream entry: joining and
+// leaving the meeting, plus the "meeting has not started" retry countdown.
+// The component that creates it is purely presentational and reads the
+// tracked state here; the modifier attached to the element Zoom renders its
+// component view into registers that element via `registerRoot`.
+export default class ZoomMeetingSession {
+ @tracked errorMessage;
+ @tracked isJoining = false;
+ @tracked isJoined = false;
+ @tracked showZoomFrame = false;
+ @tracked retryCountdown = null;
+ @tracked isRetryingNow = false;
+
+ element = null;
+ retryAttempts = 0;
+ retryTimer = null;
+ zoomClient = null;
+ zoomClientInitialized = false;
+ layoutFrame = null;
+ videoSyncFrame = null;
+
+ #tornDown = false;
+
+ constructor(owner, { topicId, canJoin, onBeforeJoinAttempt }) {
+ setOwner(this, owner);
+ this.topicId = topicId;
+ this.canJoin = canJoin;
+ this.onBeforeJoinAttempt = onBeforeJoinAttempt;
+ }
+
+ teardown() {
+ this.#tornDown = true;
+ clearInterval(this.retryTimer);
+ cancelAnimationFrame(this.layoutFrame);
+ cancelAnimationFrame(this.videoSyncFrame);
+ this.zoomClient?.leaveMeeting?.();
+ }
+
+ registerRoot(element) {
+ this.element = element;
+ }
+
+ unregisterRoot(element) {
+ if (this.element === element) {
+ this.element = null;
+ }
+ }
+
+ get isWaitingForStart() {
+ return this.retryCountdown !== null;
+ }
+
+ async join() {
+ if (
+ this.isJoining ||
+ this.isJoined ||
+ this.isWaitingForStart ||
+ !this.canJoin()
+ ) {
+ return;
+ }
+
+ this.errorMessage = null;
+ this.isJoining = true;
+ this.showZoomFrame = true;
+
+ try {
+ // The callback is a convenience (RSVPing the user), not a precondition.
+ // A user for whom it fails should still get to watch the webinar.
+ await this.onBeforeJoinAttempt?.();
+ } catch (err) {
+ // eslint-disable-next-line no-console
+ console.error("Error marking the user as going", err);
+ }
+
+ try {
+ await this.performJoin();
+
+ if (this.#tornDown) {
+ return;
+ }
+
+ this.isJoined = true;
+ this.stopRetrying();
+ } catch (err) {
+ const serializedError = serializeZoomError(err);
+ // eslint-disable-next-line no-console
+ console.error("Error joining Zoom meeting", serializedError);
+
+ // The user navigated away while the join was in flight, so there is
+ // nothing left to retry into.
+ if (this.#tornDown) {
+ return;
+ }
+
+ if (serializedError.meetingNotStarted) {
+ this.retryAttempts += 1;
+
+ if (this.retryAttempts <= MAX_RETRY_ATTEMPTS) {
+ // The frame stays up so Zoom's own "meeting has not started" panel
+ // remains visible alongside the countdown.
+ this.isRetryingNow = false;
+ this.startRetryCountdown();
+ return;
+ }
+ }
+
+ this.leaveZoom();
+ this.errorMessage = i18n("discourse_calendar.livestream.zoom.load_error");
+ } finally {
+ this.isJoining = false;
+
+ this.layoutFrame = window.requestAnimationFrame(() =>
+ syncZoomLayout(this.element)
+ );
+ this.videoSyncFrame = window.requestAnimationFrame(() =>
+ this.syncVideoSize()
+ );
+ }
+ }
+
+ async performJoin() {
+ const zoomJoinPayload = await fetchZoomJoinPayload(this.topicId);
+
+ if (!this.zoomClientInitialized) {
+ const ZoomMtgEmbedded = await loadZoomMeetingSdkEmbedded();
+ this.zoomClient = ZoomMtgEmbedded.createClient();
+
+ await this.zoomClient.init({
+ zoomAppRoot: this.element,
+ language: "en-US",
+ patchJsMedia: true,
+ leaveOnPageUnload: true,
+ customize: {
+ activeApps: {
+ popper: {
+ placement: "top",
+ },
+ },
+ video: {
+ isResizable: false,
+ defaultViewType: DEFAULT_VIEW_TYPE,
+ viewSizes: {
+ default: computeZoomViewSize(this.element),
+ },
+ popper: {
+ disableDraggable: true,
+ },
+ },
+ },
+ });
+
+ this.zoomClient.on("connection-change", (payload) => {
+ // Handles the livestream ending while the user is still on the page.
+ if (payload.state === "Closed") {
+ this.leaveZoom();
+ }
+ });
+
+ this.zoomClientInitialized = true;
+ }
+
+ await this.zoomClient.join({
+ signature: zoomJoinPayload.signature,
+ sdkKey: zoomJoinPayload.sdk_key,
+ meetingNumber: zoomJoinPayload.meeting_number,
+ password: zoomJoinPayload.password || "",
+ userName: zoomJoinPayload.user_name,
+ userEmail: zoomJoinPayload.user_email,
+ });
+ }
+
+ syncVideoSize() {
+ if (!this.zoomClient) {
+ return;
+ }
+
+ this.zoomClient.updateVideoOptions({
+ viewSizes: {
+ default: computeZoomViewSize(this.element),
+ },
+ });
+ }
+
+ leaveZoom() {
+ this.isJoined = false;
+ this.showZoomFrame = false;
+
+ // Deletes inline styles that Zoom applies which leaves a big empty box on
+ // the page
+ this.element?.removeAttribute("style");
+
+ this.stopRetrying();
+ }
+
+ startRetryCountdown() {
+ clearInterval(this.retryTimer);
+ this.retryCountdown = RETRY_DELAY_SECONDS;
+
+ this.retryTimer = setInterval(() => {
+ if (this.retryCountdown > 1) {
+ this.retryCountdown -= 1;
+ return;
+ }
+
+ clearInterval(this.retryTimer);
+ this.retryTimer = null;
+ this.attemptRejoin();
+ }, 1000);
+ }
+
+ stopRetrying() {
+ clearInterval(this.retryTimer);
+ this.retryTimer = null;
+ this.retryCountdown = null;
+ this.isRetryingNow = false;
+ this.retryAttempts = 0;
+ }
+
+ // The client is deliberately reused. `ZoomMtgEmbedded.destroyClient()` never
+ // unmounts the React root that `join()` mounted into the app root, so a
+ // fresh client would call `createRoot()` on a container that already has one
+ // and render nothing. Joining again on the same client re-runs the join
+ // against the already-mounted component view.
+ async attemptRejoin() {
+ this.retryCountdown = null;
+ this.isRetryingNow = true;
+
+ await this.join();
+ }
+}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/models/discourse-post-event-event.js b/plugins/discourse-calendar/assets/javascripts/discourse/models/discourse-post-event-event.js
index 0181e6392b9..f98e3f89e88 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/models/discourse-post-event-event.js
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/models/discourse-post-event-event.js
@@ -15,6 +15,26 @@ const DEFAULT_REMINDER = {
unit: "minutes",
period: "before",
};
+// Keep in sync with the constants of the same name on
+// DiscoursePostEvent::Event, which enforces the same window server-side.
+const EARLY_ACCESS_MINUTES = 30;
+const GRACE_PERIOD_MINUTES = 10;
+
+export function isWithinEventTimeframe(allDay, startsAt, endsAt) {
+ const now = moment();
+
+ if (allDay) {
+ const opensAt = moment(startsAt).startOf("day");
+ const closesAt = moment(startsAt).endOf("day");
+
+ return now.isBetween(opensAt, closesAt);
+ }
+
+ const opensAt = moment(startsAt).subtract(EARLY_ACCESS_MINUTES, "minutes");
+ const closesAt = moment(endsAt).add(GRACE_PERIOD_MINUTES, "minutes");
+
+ return now.isBetween(opensAt, closesAt);
+}
export default class DiscoursePostEventEvent {
static create(args = {}) {
@@ -42,6 +62,9 @@ export default class DiscoursePostEventEvent {
@tracked chatEnabled;
@tracked livestream;
@tracked livestreamOnebox;
+ @tracked livestreamUrl;
+ @tracked livestreamChatChannelId;
+ @tracked isZoomLivestream;
@tracked canUpdateAttendance;
@tracked canActOnDiscoursePostEvent;
@tracked shouldDisplayInvitees;
@@ -89,6 +112,9 @@ export default class DiscoursePostEventEvent {
this.chatEnabled = args.chat_enabled;
this.livestream = args.livestream;
this.livestreamOnebox = args.livestream_onebox;
+ this.livestreamUrl = args.livestream_url;
+ this.livestreamChatChannelId = args.livestream_chat_channel_id;
+ this.isZoomLivestream = args.is_zoom_livestream;
this.maxAttendees = args.max_attendees;
this.atCapacity = args.at_capacity;
this.recurrence = args.recurrence;
@@ -162,6 +188,22 @@ export default class DiscoursePostEventEvent {
return this.imageUpload?.url;
}
+ get currentlyWithinEventTimeframe() {
+ return isWithinEventTimeframe(this.allDay, this.startsAt, this.endsAt);
+ }
+
+ // An event without an end time never falls past its timeframe, since
+ // `moment(undefined)` is "now" rather than an invalid date.
+ get pastEventTimeframe() {
+ if (!this.endsAt) {
+ return false;
+ }
+
+ return moment().isAfter(
+ moment(this.endsAt).add(GRACE_PERIOD_MINUTES, "minutes")
+ );
+ }
+
updateFromEvent(event) {
this.name = event.name;
this.startsAt = event.startsAt;
@@ -183,6 +225,9 @@ export default class DiscoursePostEventEvent {
this.chatEnabled = event.chatEnabled;
this.livestream = event.livestream;
this.livestreamOnebox = event.livestreamOnebox;
+ this.livestreamUrl = this.location || this.url;
+ this.livestreamChatChannelId = event.livestreamChatChannelId;
+ this.isZoomLivestream = event.isZoomLivestream;
this.rrule = event.rrule;
this.maxAttendees = event.maxAttendees;
this.atCapacity = event.atCapacity;
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/modifiers/zoom-component-view-layout.js b/plugins/discourse-calendar/assets/javascripts/discourse/modifiers/zoom-component-view-layout.js
new file mode 100644
index 00000000000..f380c396030
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/modifiers/zoom-component-view-layout.js
@@ -0,0 +1,60 @@
+import { modifier } from "ember-modifier";
+import {
+ isZoomLeaveButtonClick,
+ syncZoomLayout,
+} from "../lib/zoom-component-view-dom";
+
+// Applied to the element the Zoom embedded SDK renders its component view
+// into.
+// Registers the element with the session and keeps Zoom's DOM in shape as it
+// mutates and resizes.
+export default modifier((element, [session, observeResize]) => {
+ session.registerRoot(element);
+
+ // Zoom's "meeting has not started" panel has its own leave button, and
+ // unlike every other leave path it fires no `connection-change` event: the
+ // SDK only reports `Closed` once it has a meeting id, which a join that
+ // failed before the host started never gets. Watching the click is the only
+ // signal.
+ const onClick = (event) => {
+ // The joined toolbar's leave button carries the same title, but clicking
+ // it only opens Zoom's confirmation popper. Hiding the frame there would
+ // strand the user in a meeting they can no longer see or leave. That path
+ // reports `Closed` on its own once the user confirms.
+ if (!session.isJoined && isZoomLeaveButtonClick(event)) {
+ session.leaveZoom();
+ }
+ };
+ element.addEventListener("click", onClick, { capture: true });
+
+ let resizeObserver;
+ if (observeResize && window.ResizeObserver) {
+ resizeObserver = new ResizeObserver(() => {
+ session.syncVideoSize();
+ syncZoomLayout(element);
+ });
+ resizeObserver.observe(element);
+ }
+
+ let mutationObserver;
+ if (window.MutationObserver) {
+ mutationObserver = new MutationObserver(() => {
+ syncZoomLayout(element);
+ });
+ mutationObserver.observe(element, {
+ childList: true,
+ subtree: true,
+ attributes: true,
+ attributeFilter: ["style", "class"],
+ });
+ }
+
+ syncZoomLayout(element);
+
+ return () => {
+ resizeObserver?.disconnect();
+ mutationObserver?.disconnect();
+ element.removeEventListener("click", onClick, { capture: true });
+ session.unregisterRoot(element);
+ };
+});
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/routes/topic-zoom.js b/plugins/discourse-calendar/assets/javascripts/discourse/routes/topic-zoom.js
new file mode 100644
index 00000000000..3d45df9f909
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/routes/topic-zoom.js
@@ -0,0 +1,26 @@
+import { service } from "@ember/service";
+import DiscourseRoute from "discourse/routes/discourse";
+
+export default class TopicZoomRoute extends DiscourseRoute {
+ @service embeddableChat;
+ @service store;
+
+ activate() {
+ this.embeddableChat.closeChatVisibility();
+ }
+
+ async model(params) {
+ const topic = this.store.createRecord("topic", { id: params.topic_id });
+
+ // Populates the topic (chat_channel_id, slug, post stream) from the
+ // server-preloaded payload when available, falling back to a request.
+ await topic.postStream.refresh();
+
+ return topic;
+ }
+
+ setupController(controller, model) {
+ super.setupController(controller, model);
+ this.controllerFor("topic").set("model", model);
+ }
+}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/services/embeddable-chat.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/services/embeddable-chat.gjs
index 6ad35f0b731..e497c7901a2 100644
--- a/plugins/discourse-calendar/assets/javascripts/discourse/services/embeddable-chat.gjs
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/services/embeddable-chat.gjs
@@ -1,5 +1,6 @@
import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";
+import { getOwner } from "@ember/owner";
import Service, { service } from "@ember/service";
import optionalService from "discourse/lib/optional-service";
@@ -16,8 +17,7 @@ export default class EmbeddableChat extends Service {
return this.chat?.userCanChat ?? false;
}
- canRenderChatChannel(topicController, mobileViewAllowed = false) {
- this.topicController = topicController;
+ canRenderChatChannel(mobileViewAllowed = false) {
if (
this.isMobileViewport === mobileViewAllowed &&
this.siteSettings.chat_enabled &&
@@ -32,7 +32,7 @@ export default class EmbeddableChat extends Service {
this.router.currentURL.startsWith(path)
);
- if (withinPathsAllowed && this.topicController?.model?.chat_channel_id) {
+ if (withinPathsAllowed && this.chatChannelId) {
return true;
}
}
@@ -45,6 +45,11 @@ export default class EmbeddableChat extends Service {
this.isMobileChatVisible = !this.isMobileChatVisible;
}
+ @action
+ closeChatVisibility() {
+ this.isMobileChatVisible = false;
+ }
+
get isMobileModal() {
return (
this.siteSettings.livestream_enable_modal_chat_on_mobile &&
@@ -56,6 +61,10 @@ export default class EmbeddableChat extends Service {
return !this.capabilities.viewport.lg;
}
+ get topicController() {
+ return getOwner(this).lookup("controller:topic");
+ }
+
get topic() {
return this.topicController?.model;
}
diff --git a/plugins/discourse-calendar/assets/javascripts/discourse/templates/topic-zoom.gjs b/plugins/discourse-calendar/assets/javascripts/discourse/templates/topic-zoom.gjs
new file mode 100644
index 00000000000..c827da721d6
--- /dev/null
+++ b/plugins/discourse-calendar/assets/javascripts/discourse/templates/topic-zoom.gjs
@@ -0,0 +1,3 @@
+import LivestreamZoomPage from "../components/livestream/zoom-page";
+
+export default <template><LivestreamZoomPage @topic={{@model}} /></template>
diff --git a/plugins/discourse-calendar/assets/stylesheets/common/discourse-post-event.scss b/plugins/discourse-calendar/assets/stylesheets/common/discourse-post-event.scss
index b0185859bcc..caee5bbf42e 100644
--- a/plugins/discourse-calendar/assets/stylesheets/common/discourse-post-event.scss
+++ b/plugins/discourse-calendar/assets/stylesheets/common/discourse-post-event.scss
@@ -415,6 +415,10 @@ $show-interested: inherit;
}
}
+ .event-location a {
+ overflow-wrap: anywhere;
+ }
+
.event-description {
align-items: start;
padding-right: 2em;
@@ -460,6 +464,14 @@ $show-interested: inherit;
}
}
+ .event-livestream {
+ padding-top: 0;
+
+ button {
+ width: 100%;
+ }
+ }
+
.cooked-date,
.participants,
.event-url .url {
diff --git a/plugins/discourse-calendar/assets/stylesheets/common/livestream.scss b/plugins/discourse-calendar/assets/stylesheets/common/livestream.scss
index c3d1c6e7061..1ce1ab02a2f 100644
--- a/plugins/discourse-calendar/assets/stylesheets/common/livestream.scss
+++ b/plugins/discourse-calendar/assets/stylesheets/common/livestream.scss
@@ -28,3 +28,145 @@ body.chat-enabled.livestream-topic.confirmed-event-assistance {
width: 100%;
}
}
+
+.discourse-calendar-livestream-zoom-entry-container {
+ margin-top: 1rem;
+}
+
+.discourse-calendar-livestream-zoom-entry {
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+
+ &__actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 0.75rem;
+ align-items: center;
+
+ p.discourse-calendar-livestream-zoom-entry__error {
+ margin: 0;
+ color: var(--danger);
+ margin-right: auto;
+ }
+ }
+
+ &__waiting {
+ margin: 0;
+ color: var(--primary-medium);
+ text-align: center;
+ width: 100%;
+ }
+
+ &__frame {
+ // Zoom sets `display` inline on this element when it mounts, which beats
+ // anything declared here. Only `justify-content` and `padding-top` apply.
+ //
+ // Until the meeting is joined the widget is a small dialog (spinner,
+ // "meeting has not started"), so it is centred. Once joined it fills the
+ // frame and must sit flush.
+ &.--visible {
+ display: block;
+ justify-content: center;
+ padding-top: var(--space-4);
+ }
+
+ &.--joined {
+ justify-content: initial;
+ padding-top: 0;
+ }
+
+ // Get rid of the view mode buttons in zoom, they break the video stream
+ // when used
+ .zoom-MuiTabs-flexContainer[aria-label="view mode tabs"] {
+ display: none;
+ }
+
+ // Get rid of chat button in zoom, Discourse chat should be used,
+ // there is no way to hide this natively even if the webinar
+ // host has disabled chat
+ button.zoom-MuiButton-root[title="Chat"] {
+ display: none;
+ }
+ }
+}
+
+.discourse-calendar-livestream-zoom-page {
+ position: relative;
+ min-height: calc(100vh - var(--header-offset, 0px));
+ background: var(--secondary);
+
+ &__frame {
+ min-height: calc(100vh - var(--header-offset, 0px));
+ }
+
+ &__waiting-wrapper {
+ border: 1px solid var(--primary-300);
+ border-radius: var(--d-border-radius);
+ }
+
+ &__waiting {
+ margin: 0;
+ padding: 1rem;
+ color: var(--primary-medium);
+ text-align: center;
+ }
+
+ &__fallback {
+ position: absolute;
+ top: 1rem;
+ left: 1rem;
+ right: 1rem;
+ z-index: 2;
+ padding: 1rem;
+ border-radius: 8px;
+ background: var(--secondary);
+ border: 1px solid var(--primary-low);
+
+ p {
+ margin-top: 0;
+ }
+ }
+
+ &__chat-button {
+ position: fixed;
+ right: 1rem;
+ bottom: 4rem;
+ z-index: 3;
+ }
+}
+
+body.chat-enabled.livestream-topic,
+body.chat-enabled.websdk-body {
+ .chat-channel-preview-card {
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+
+ .chat-channel__placeholder {
+ display: none;
+ }
+ }
+}
+
+.livestream-join-channel-message {
+ text-align: center;
+ margin-top: 1rem;
+
+ h2 {
+ margin-bottom: 0.5rem;
+ }
+}
+
+// Overrides zoom toasts, we do not want these showing as they are
+// un-dismissable and not helpful messages
+.notistack-SnackbarContainer {
+ display: none !important;
+}
+
+// Full page client view Zoom overrides
+#zmmtg-root {
+ #sdk-footer-sortable-list #chat {
+ display: none;
+ }
+}
diff --git a/plugins/discourse-calendar/assets/stylesheets/desktop/livestream.scss b/plugins/discourse-calendar/assets/stylesheets/desktop/livestream.scss
index 64431ab1d06..d035afe6fb8 100644
--- a/plugins/discourse-calendar/assets/stylesheets/desktop/livestream.scss
+++ b/plugins/discourse-calendar/assets/stylesheets/desktop/livestream.scss
@@ -39,4 +39,22 @@
height: 100%;
}
}
+
+ .discourse-calendar-livestream-zoom-entry {
+ width: min(100%, 1444px);
+ margin-left: auto;
+ margin-right: auto;
+
+ &__frame {
+ margin-left: auto;
+ margin-right: auto;
+ width: 100%;
+ aspect-ratio: 16 / 9;
+ border: 1px solid var(--primary-low);
+ border-radius: 8px;
+ overflow: hidden;
+ background: var(--secondary);
+ display: none;
+ }
+ }
}
diff --git a/plugins/discourse-calendar/assets/stylesheets/mobile/livestream.scss b/plugins/discourse-calendar/assets/stylesheets/mobile/livestream.scss
index 27b2c834eda..dad6ad4fe6a 100644
--- a/plugins/discourse-calendar/assets/stylesheets/mobile/livestream.scss
+++ b/plugins/discourse-calendar/assets/stylesheets/mobile/livestream.scss
@@ -1,4 +1,5 @@
-body.livestream-topic.chat-enabled {
+body.livestream-topic.chat-enabled,
+body.websdk-body {
.d-header-icons {
.livestream-header-icon {
position: relative;
@@ -125,6 +126,10 @@ body.livestream-topic.chat-enabled {
}
}
+ .chat-message-text {
+ color: var(--primary);
+ }
+
.livestream-chat-modal {
// don't blur the background when the livestream chat modal is open
& ~ .d-modal__backdrop {
@@ -161,8 +166,64 @@ body.livestream-topic.chat-enabled {
}
}
}
+
+ .chat-composer__outer-container {
+ gap: var(--space-2);
+ }
+
+ .chat-composer-dropdown__menu-trigger {
+ padding: 0;
+ margin: 0;
+ width: 3em;
+
+ .d-icon {
+ padding: var(--space-2);
+ width: 100%;
+ height: 100%;
+ }
+ }
+
+ .chat-composer-button__wrapper {
+ margin: 0;
+ align-self: stretch;
+ }
+
+ .chat-composer-button {
+ margin: 0;
+ padding: 0.5em 0.65em;
+ height: 100%;
+ }
}
body:not(.livestream-topic) .d-header-icons .livestream-header-icon {
display: none;
}
+
+.discourse-calendar-livestream-zoom-page {
+ margin-left: calc(var(--topic-body-width-padding, 1rem) * -1);
+ margin-right: calc(var(--topic-body-width-padding, 1rem) * -1);
+}
+
+// zoom specific overrides, undoes core conflicts
+#wc-footer {
+ .btn-group {
+ margin: 0;
+ }
+
+ .audio-option-menu {
+ position: relative;
+ }
+
+ .footer-button__wrapper {
+ display: flex;
+
+ > div {
+ display: flex;
+ }
+
+ .audio-option-menu {
+ display: flex;
+ margin-block: auto;
+ }
+ }
+}
diff --git a/plugins/discourse-calendar/config/locales/client.en.yml b/plugins/discourse-calendar/config/locales/client.en.yml
index 58ba6583ca2..57340e40a9e 100644
--- a/plugins/discourse-calendar/config/locales/client.en.yml
+++ b/plugins/discourse-calendar/config/locales/client.en.yml
@@ -28,6 +28,17 @@ en:
label: Topic ID
discourse_calendar:
livestream:
+ zoom:
+ join: "Join Zoom"
+ chat: "Chat"
+ open_in_zoom: "Open in Zoom"
+ load_error: "You left the webinar or we are unable to load Zoom in this page."
+ too_early: "You can join the webinar closer to the event start time"
+ view_topic: "View topic for the event"
+ not_started_retrying:
+ one: "The webinar hasn't started yet. Retrying join in %{count} second..."
+ other: "The webinar hasn't started yet. Retrying join in %{count} seconds..."
+ not_started_trying_again: "Trying to join the webinar again now..."
chat:
going: "Click Going"
join_channel_header: "🌟 Join the Buzz! 🌟"
diff --git a/plugins/discourse-calendar/config/locales/server.en.yml b/plugins/discourse-calendar/config/locales/server.en.yml
index e1e45cc8d0c..f09feff6863 100644
--- a/plugins/discourse-calendar/config/locales/server.en.yml
+++ b/plugins/discourse-calendar/config/locales/server.en.yml
@@ -73,6 +73,9 @@ en:
sidebar_show_upcoming_events: "Show upcoming events link in the sidebar under 'More'."
calendar_first_day_of_week: "Set the first day of the week for calendar display. Options are Saturday, Sunday, or Monday."
enable_events_category_type_setup: "Enables the Events category type option during category creation setup."
+ livestream_zoom_enabled: "Enable Zoom video embedding for livestream topics."
+ livestream_zoom_sdk_key: "Zoom Meeting SDK client ID."
+ livestream_zoom_sdk_secret: "Zoom Meeting SDK client secret."
livestream_embeddable_chat_allowed_paths: "Allowed paths for the embeddable livestream chat."
livestream_enable_modal_chat_on_mobile: "Show livestream chat in a modal on mobile."
diff --git a/plugins/discourse-calendar/config/routes.rb b/plugins/discourse-calendar/config/routes.rb
index 79b681e9dd7..03725157f03 100644
--- a/plugins/discourse-calendar/config/routes.rb
+++ b/plugins/discourse-calendar/config/routes.rb
@@ -23,10 +23,17 @@ DiscoursePostEvent::Engine.routes.draw do
get "/upcoming-events/mine" => "upcoming_events#index"
end
+DiscourseCalendar::Engine.routes.draw do
+ get "/discourse-calendar/livestream/zoom/signature" => "livestream#prepare_zoom_signature",
+ :format => :json
+end
+
Discourse::Application.routes.draw do
mount DiscourseCalendar::Engine, at: "/"
mount DiscoursePostEvent::Engine, at: "/"
+ get "t/:slug/:topic_id/zoom" => "topics#show", :constraints => { topic_id: /\d+/ }
+
scope constraints: StaffConstraint.new do
get "/admin/plugins/calendar" => "admin/plugins#index"
get "/admin/plugins/discourse-calendar" => "admin/plugins#index"
diff --git a/plugins/discourse-calendar/config/settings.yml b/plugins/discourse-calendar/config/settings.yml
index 0f05a7bed7b..69341e922f8 100644
--- a/plugins/discourse-calendar/config/settings.yml
+++ b/plugins/discourse-calendar/config/settings.yml
@@ -140,6 +140,14 @@ discourse_calendar:
status: "stable"
impact: "feature,staff"
learn_more_url: "https://meta.discourse.org/t/-/401309"
+ livestream_zoom_enabled:
+ default: false
+ client: true
+ livestream_zoom_sdk_key:
+ default: ""
+ livestream_zoom_sdk_secret:
+ default: ""
+ secret: true
livestream_embeddable_chat_allowed_paths:
type: list
default: "/t"
@@ -147,4 +155,4 @@ discourse_calendar:
hidden: true
livestream_enable_modal_chat_on_mobile:
default: true
- client: true
\ No newline at end of file
+ client: true
diff --git a/plugins/discourse-calendar/jobs/regular/discourse_post_event/warm_livestream_onebox.rb b/plugins/discourse-calendar/jobs/regular/discourse_post_event/warm_livestream_onebox.rb
index 37d71dfa8bd..a9ece0c130b 100644
--- a/plugins/discourse-calendar/jobs/regular/discourse_post_event/warm_livestream_onebox.rb
+++ b/plugins/discourse-calendar/jobs/regular/discourse_post_event/warm_livestream_onebox.rb
@@ -8,12 +8,9 @@ module Jobs
url = args[:url]
return if url.blank?
- Oneboxer.onebox(url)
-
event = DiscoursePostEvent::Event.find_by(id: args[:event_id])
- return if event.blank? || !event.livestream? || event.location != url
-
- event.post&.publish_change_to_clients!(:revised)
+ return if event.blank? || event.livestream_url != url
+ event.warm_livestream_onebox!
end
end
end
diff --git a/plugins/discourse-calendar/lib/discourse_calendar/livestream/zoom_url_parser.rb b/plugins/discourse-calendar/lib/discourse_calendar/livestream/zoom_url_parser.rb
new file mode 100644
index 00000000000..432364ff0f7
--- /dev/null
+++ b/plugins/discourse-calendar/lib/discourse_calendar/livestream/zoom_url_parser.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+module DiscourseCalendar
+ module Livestream
+ module ZoomUrlParser
+ # Matches zoom.us and its vanity subdomains (us06web.zoom.us), but not
+ # hosts that merely end in those characters (notzoom.us, zoom.us.evil.com).
+ SUPPORTED_HOST = /(\A|\.)zoom\.us\z/i
+ SUPPORTED_PATH_SEGMENTS = %w[j w wc].freeze
+
+ # The single source of truth for "is this a Zoom livestream URL we can
+ # join?". A URL that parses is one the Meeting SDK can be handed.
+ def self.zoom_url?(url)
+ parse(url).present?
+ end
+
+ def self.parse(url)
+ return if url.blank?
+
+ uri = URI.parse(url)
+ return if !uri.is_a?(URI::HTTPS) || uri.host.blank? || uri.host !~ SUPPORTED_HOST
+
+ segments = uri.path.split("/").reject(&:blank?)
+ segment_index = segments.find_index { |segment| SUPPORTED_PATH_SEGMENTS.include?(segment) }
+ return if segment_index.blank?
+
+ meeting_number = segments[segment_index + 1]
+ return if meeting_number.blank? || !meeting_number.match?(/\A\d+\z/)
+
+ password = Rack::Utils.parse_nested_query(uri.query.to_s)["pwd"]
+
+ { meeting_number:, password: password.presence, url: uri.to_s }
+ rescue URI::InvalidURIError
+ nil
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-calendar/plugin.rb b/plugins/discourse-calendar/plugin.rb
index 5414c6980ae..7ab7606d2ac 100644
--- a/plugins/discourse-calendar/plugin.rb
+++ b/plugins/discourse-calendar/plugin.rb
@@ -44,6 +44,10 @@ register_svg_icon "star"
register_svg_icon "file-arrow-up"
register_svg_icon "location-pin"
register_svg_icon "arrows-up-to-line"
+extend_content_security_policy(
+ script_src: %w[https://source.zoom.us],
+ worker_src: %w[https://source.zoom.us blob:],
+)
module ::DiscourseCalendar
PLUGIN_NAME = "discourse-calendar"
@@ -119,6 +123,7 @@ end
require_relative "lib/discourse_calendar/engine"
require_relative "lib/discourse_calendar/livestream/topic_extension"
require_relative "lib/discourse_calendar/livestream/chat_channel_extension"
+require_relative "lib/discourse_calendar/livestream/zoom_url_parser"
Dir
.glob(File.expand_path("../lib/discourse_calendar/site_settings/*.rb", __FILE__))
diff --git a/plugins/discourse-calendar/spec/jobs/regular/discourse_post_event/warm_livestream_onebox_spec.rb b/plugins/discourse-calendar/spec/jobs/regular/discourse_post_event/warm_livestream_onebox_spec.rb
index 40dda37e7ca..7732885f125 100644
--- a/plugins/discourse-calendar/spec/jobs/regular/discourse_post_event/warm_livestream_onebox_spec.rb
+++ b/plugins/discourse-calendar/spec/jobs/regular/discourse_post_event/warm_livestream_onebox_spec.rb
@@ -25,7 +25,7 @@ describe Jobs::WarmLivestreamOnebox do
it "does not publish when the event URL has changed" do
stale_url = "https://example.com/old-live"
event
- Oneboxer.expects(:onebox).with(stale_url).returns("<aside>cached</aside>")
+ Oneboxer.stubs(:onebox).returns("<aside>cached</aside>")
messages =
MessageBus.track_publish("/topic/#{post.topic_id}") do
@@ -34,4 +34,38 @@ describe Jobs::WarmLivestreamOnebox do
expect(messages).to be_empty
end
+
+ it "does not publish when the URL is blank" do
+ event
+ Oneboxer.stubs(:onebox).returns("<aside>cached</aside>")
+
+ messages =
+ MessageBus.track_publish("/topic/#{post.topic_id}") do
+ described_class.new.execute(event_id: event.id, url: nil)
+ end
+
+ expect(messages).to be_empty
+ end
+
+ it "does not fetch the onebox again when it is already cached" do
+ event
+ Discourse.cache.write(
+ Oneboxer.onebox_cache_key(livestream_url),
+ { onebox: "<aside>cached</aside>" },
+ )
+ Oneboxer.expects(:onebox).never
+
+ described_class.new.execute(event_id: event.id, url: livestream_url)
+ end
+
+ it "does not publish when the event cannot be found" do
+ Oneboxer.stubs(:onebox).returns("<aside>cached</aside>")
+
+ messages =
+ MessageBus.track_publish("/topic/#{post.topic_id}") do
+ described_class.new.execute(event_id: -1, url: livestream_url)
+ end
+
+ expect(messages).to be_empty
+ end
end
diff --git a/plugins/discourse-calendar/spec/lib/discourse_calendar/livestream/zoom_url_parser_spec.rb b/plugins/discourse-calendar/spec/lib/discourse_calendar/livestream/zoom_url_parser_spec.rb
new file mode 100644
index 00000000000..6c0d9dd8208
--- /dev/null
+++ b/plugins/discourse-calendar/spec/lib/discourse_calendar/livestream/zoom_url_parser_spec.rb
@@ -0,0 +1,88 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseCalendar::Livestream::ZoomUrlParser do
+ describe ".parse" do
+ it "parses a standard Zoom meeting URL" do
+ result = described_class.parse("https://us06web.zoom.us/j/123456789?pwd=secret")
+
+ expect(result).to eq(
+ meeting_number: "123456789",
+ password: "secret",
+ url: "https://us06web.zoom.us/j/123456789?pwd=secret",
+ )
+ end
+
+ it "parses a Zoom webinar URL without a password" do
+ result = described_class.parse("https://zoom.us/w/987654321")
+
+ expect(result).to eq(
+ meeting_number: "987654321",
+ password: nil,
+ url: "https://zoom.us/w/987654321",
+ )
+ end
+
+ it "parses a web client URL" do
+ result = described_class.parse("https://zoom.us/wc/123456789/join")
+
+ expect(result).to include(meeting_number: "123456789")
+ end
+
+ it "ignores the case of the host" do
+ result = described_class.parse("https://US06WEB.ZOOM.US/j/123456789")
+
+ expect(result).to include(meeting_number: "123456789")
+ end
+
+ it "returns nil for hosts that only end in the Zoom domain" do
+ expect(described_class.parse("https://notzoom.us/j/123456789")).to be_nil
+ end
+
+ it "returns nil for hosts that only start with the Zoom domain" do
+ expect(described_class.parse("https://zoom.us.evil.com/j/123456789")).to be_nil
+ end
+
+ it "returns nil for unsupported hosts" do
+ expect(described_class.parse("https://example.com/j/123456789")).to be_nil
+ end
+
+ it "returns nil for non-HTTPS URLs" do
+ expect(described_class.parse("http://zoom.us/j/123456789")).to be_nil
+ end
+
+ it "returns nil when there is no supported path segment" do
+ expect(described_class.parse("https://zoom.us/meeting/123456789")).to be_nil
+ end
+
+ it "returns nil when the meeting number is missing" do
+ expect(described_class.parse("https://zoom.us/j/")).to be_nil
+ end
+
+ it "returns nil when the meeting number is not numeric" do
+ expect(described_class.parse("https://zoom.us/j/not-a-number")).to be_nil
+ end
+
+ it "returns nil for malformed URLs" do
+ expect(described_class.parse("not-a-url")).to be_nil
+ end
+
+ it "returns nil for blank URLs" do
+ expect(described_class.parse(nil)).to be_nil
+ expect(described_class.parse("")).to be_nil
+ end
+ end
+
+ describe ".zoom_url?" do
+ it "is true for a joinable Zoom URL on a vanity subdomain" do
+ expect(described_class.zoom_url?("https://us06web.zoom.us/j/123456789")).to eq(true)
+ end
+
+ it "is false for a Zoom URL we cannot extract a meeting number from" do
+ expect(described_class.zoom_url?("https://zoom.us/about")).to eq(false)
+ end
+
+ it "is false for a non-Zoom URL" do
+ expect(described_class.zoom_url?("https://example.com/live")).to eq(false)
+ end
+ end
+end
diff --git a/plugins/discourse-calendar/spec/models/discourse_post_event/event_spec.rb b/plugins/discourse-calendar/spec/models/discourse_post_event/event_spec.rb
index 6e47b7fcace..4ccf33b64cf 100644
--- a/plugins/discourse-calendar/spec/models/discourse_post_event/event_spec.rb
+++ b/plugins/discourse-calendar/spec/models/discourse_post_event/event_spec.rb
@@ -48,6 +48,117 @@ describe DiscoursePostEvent::Event do
Fabricate(:event, post: post, livestream: true, location: livestream_url)
end
end
+
+ it "skips onebox warming for events that are not livestreams" do
+ expect_not_enqueued_with(job: :warm_livestream_onebox) do
+ Fabricate(:event, post: post, livestream: false, location: "Room 5")
+ end
+ end
+
+ it "skips onebox warming when the livestream has no URL" do
+ expect_not_enqueued_with(job: :warm_livestream_onebox) do
+ Fabricate(:event, post: post, livestream: true)
+ end
+ end
+
+ it "warms the onebox when the URL changes" do
+ event = Fabricate(:event, post: post, livestream: true, location: livestream_url)
+
+ expect_enqueued_with(
+ job: :warm_livestream_onebox,
+ args: {
+ event_id: event.id,
+ url: "https://example.com/other-live",
+ },
+ ) { event.update!(location: "https://example.com/other-live") }
+ end
+
+ it "does not warm the onebox when an unrelated attribute changes" do
+ event = Fabricate(:event, post: post, livestream: true, location: livestream_url)
+
+ expect_not_enqueued_with(job: :warm_livestream_onebox) { event.update!(name: "Renamed") }
+ end
+ end
+
+ describe "#livestream_url" do
+ fab!(:topic) { Fabricate(:topic, category: nil) }
+ fab!(:post) { Fabricate(:post, topic: topic) }
+
+ it "prefers the location over the url" do
+ event =
+ Fabricate(
+ :event,
+ post: post,
+ location: "https://zoom.us/j/123456789",
+ url: "https://example.com/fallback",
+ )
+
+ expect(event.livestream_url).to eq("https://zoom.us/j/123456789")
+ end
+
+ it "falls back to the url when there is no location" do
+ event = Fabricate(:event, post: post, url: "https://example.com/fallback")
+
+ expect(event.livestream_url).to eq("https://example.com/fallback")
+ end
+
+ it "is nil when neither is set" do
+ event = Fabricate(:event, post: post)
+
+ expect(event.livestream_url).to be_nil
+ end
+ end
+
+ describe "#is_zoom_livestream?" do
+ fab!(:topic) { Fabricate(:topic, category: nil) }
+ fab!(:post) { Fabricate(:post, topic: topic) }
+
+ before do
+ SiteSetting.livestream_zoom_enabled = true
+ # Creating a livestream event enqueues onebox warming, which would
+ # otherwise run inline and try to fetch the URL.
+ Jobs.run_later!
+ end
+
+ def event_for(location)
+ Fabricate(:event, post: post, livestream: true, location: location)
+ end
+
+ it "recognises a Zoom URL on a vanity subdomain" do
+ expect(event_for("https://us06web.zoom.us/j/123456789?pwd=secret")).to be_is_zoom_livestream
+ end
+
+ it "recognises a Zoom URL on the bare host" do
+ expect(event_for("https://zoom.us/j/123456789")).to be_is_zoom_livestream
+ end
+
+ it "recognises a Zoom webinar URL" do
+ expect(event_for("https://zoom.us/w/123456789")).to be_is_zoom_livestream
+ end
+
+ it "rejects a host that only ends in the Zoom domain" do
+ expect(event_for("https://notzoom.us/j/123456789")).not_to be_is_zoom_livestream
+ end
+
+ it "rejects a Zoom URL with no joinable meeting number" do
+ expect(event_for("https://zoom.us/about")).not_to be_is_zoom_livestream
+ end
+
+ it "rejects a non-Zoom livestream URL" do
+ expect(event_for("https://example.com/live")).not_to be_is_zoom_livestream
+ end
+
+ it "is false when the event is not a livestream" do
+ event = Fabricate(:event, post: post, livestream: false, url: "https://zoom.us/j/123456789")
+
+ expect(event).not_to be_is_zoom_livestream
+ end
+
+ it "is false when Zoom is disabled" do
+ SiteSetting.livestream_zoom_enabled = false
+
+ expect(event_for("https://zoom.us/j/123456789")).not_to be_is_zoom_livestream
+ end
end
describe "#create_livestream_chat_channel" do
@@ -514,6 +625,84 @@ describe DiscoursePostEvent::Event do
end
end
+ describe "#currently_within_event_timeframe?" do
+ let(:user) { Fabricate(:user, admin: true) }
+ let(:topic) { Fabricate(:topic, user: user) }
+ let!(:first_post) { Fabricate(:post, topic: topic) }
+
+ def event_with(starts_at:, ends_at: nil, all_day: false)
+ DiscoursePostEvent::Event.create!(
+ original_starts_at: starts_at,
+ original_ends_at: ends_at,
+ all_day:,
+ post: first_post,
+ )
+ end
+
+ it "is false before the early access window opens" do
+ expect(event_with(starts_at: 45.minutes.from_now).currently_within_event_timeframe?).to be(
+ false,
+ )
+ end
+
+ it "is true within the early access window" do
+ expect(event_with(starts_at: 15.minutes.from_now).currently_within_event_timeframe?).to be(
+ true,
+ )
+ end
+
+ it "is true while the event is in progress" do
+ expect(
+ event_with(
+ starts_at: 1.hour.ago,
+ ends_at: 1.hour.from_now,
+ ).currently_within_event_timeframe?,
+ ).to be(true)
+ end
+
+ it "is true within the grace period after the end" do
+ expect(
+ event_with(
+ starts_at: 2.hours.ago,
+ ends_at: 5.minutes.ago,
+ ).currently_within_event_timeframe?,
+ ).to be(true)
+ end
+
+ it "is false once the grace period has passed" do
+ expect(
+ event_with(
+ starts_at: 2.hours.ago,
+ ends_at: 15.minutes.ago,
+ ).currently_within_event_timeframe?,
+ ).to be(false)
+ end
+
+ it "is true for a started event without an end time" do
+ expect(event_with(starts_at: 1.day.ago).currently_within_event_timeframe?).to be(true)
+ end
+
+ context "for an all day event" do
+ it "is true when now is between the start + end of the day of the event" do
+ expect(
+ event_with(
+ starts_at: Time.zone.now.beginning_of_day,
+ all_day: true,
+ ).currently_within_event_timeframe?,
+ ).to be(true)
+ end
+
+ it "is false when now is before the start of the day of the event" do
+ expect(
+ event_with(
+ starts_at: Time.zone.now.tomorrow.beginning_of_day,
+ all_day: true,
+ ).currently_within_event_timeframe?,
+ ).to be(false)
+ end
+ end
+ end
+
describe "#expired?" do
let(:user) { Fabricate(:user, admin: true) }
let(:topic) { Fabricate(:topic, user: user) }
diff --git a/plugins/discourse-calendar/spec/requests/api/schemas/json/events_index_detailed_response.json b/plugins/discourse-calendar/spec/requests/api/schemas/json/events_index_detailed_response.json
index eebdca5d396..23b8eea0677 100644
--- a/plugins/discourse-calendar/spec/requests/api/schemas/json/events_index_detailed_response.json
+++ b/plugins/discourse-calendar/spec/requests/api/schemas/json/events_index_detailed_response.json
@@ -241,6 +241,9 @@
"null"
]
},
+ "is_zoom_livestream": {
+ "type": "boolean"
+ },
"max_attendees": {
"type": [
"integer",
@@ -290,13 +293,17 @@
},
"tags_descriptions": {
"type": "object"
+ },
+ "slug": {
+ "type": "string"
}
},
"required": [
"id",
"title",
"tags",
- "tags_descriptions"
+ "tags_descriptions",
+ "slug"
]
}
},
diff --git a/plugins/discourse-calendar/spec/requests/api/schemas/json/events_index_response.json b/plugins/discourse-calendar/spec/requests/api/schemas/json/events_index_response.json
index 86ee7300ce5..82c3680ceca 100644
--- a/plugins/discourse-calendar/spec/requests/api/schemas/json/events_index_response.json
+++ b/plugins/discourse-calendar/spec/requests/api/schemas/json/events_index_response.json
@@ -12,24 +12,42 @@
"type": "integer"
},
"category_id": {
- "type": ["integer", "null"]
+ "type": [
+ "integer",
+ "null"
+ ]
},
"name": {
- "type": ["string", "null"]
+ "type": [
+ "string",
+ "null"
+ ]
},
"recurrence": {
- "type": ["string", "null"]
+ "type": [
+ "string",
+ "null"
+ ]
},
"recurrence_until": {
- "type": ["string", "null"],
+ "type": [
+ "string",
+ "null"
+ ],
"format": "date-time"
},
"starts_at": {
- "type": ["string", "null"],
+ "type": [
+ "string",
+ "null"
+ ],
"format": "date-time"
},
"ends_at": {
- "type": ["string", "null"],
+ "type": [
+ "string",
+ "null"
+ ],
"format": "date-time"
},
"rrule": {
@@ -39,7 +57,10 @@
"type": "boolean"
},
"timezone": {
- "type": ["string", "null"]
+ "type": [
+ "string",
+ "null"
+ ]
},
"duration": {
"type": "string",
@@ -85,12 +106,27 @@
},
"tags_descriptions": {
"type": "object"
+ },
+ "slug": {
+ "type": "string"
}
},
- "required": ["id", "title", "tags", "tags_descriptions"]
+ "required": [
+ "id",
+ "title",
+ "tags",
+ "tags_descriptions",
+ "slug"
+ ]
}
},
- "required": ["id", "post_number", "url", "category_slug", "topic"]
+ "required": [
+ "id",
+ "post_number",
+ "url",
+ "category_slug",
+ "topic"
+ ]
},
"occurrences": {
"type": "array",
@@ -99,13 +135,22 @@
"additionalProperties": false,
"properties": {
"starts_at": {
- "type": ["string", "null"]
+ "type": [
+ "string",
+ "null"
+ ]
},
"ends_at": {
- "type": ["string", "null"]
+ "type": [
+ "string",
+ "null"
+ ]
}
},
- "required": ["starts_at", "ends_at"]
+ "required": [
+ "starts_at",
+ "ends_at"
+ ]
}
}
},
@@ -122,5 +167,7 @@
}
}
},
- "required": ["events"]
-}
+ "required": [
+ "events"
+ ]
+}
\ No newline at end of file
diff --git a/plugins/discourse-calendar/spec/requests/livestream_controller_spec.rb b/plugins/discourse-calendar/spec/requests/livestream_controller_spec.rb
new file mode 100644
index 00000000000..3a8ea9cae30
--- /dev/null
+++ b/plugins/discourse-calendar/spec/requests/livestream_controller_spec.rb
@@ -0,0 +1,183 @@
+# frozen_string_literal: true
+
+module DiscourseCalendar
+ describe LivestreamController do
+ fab!(:current_user, :user)
+ fab!(:tag) { Fabricate(:tag, name: "livestream") }
+ fab!(:topic) { Fabricate(:topic, user: current_user, tags: [tag]) }
+ fab!(:post) { Fabricate(:post, user: current_user, topic: topic, post_number: 1) }
+ fab!(:event) do
+ Fabricate(
+ :event,
+ post: post,
+ location: "https://us06web.zoom.us/j/123456789?pwd=secret",
+ livestream: true,
+ original_starts_at: 5.minutes.ago.iso8601,
+ original_ends_at: 1.hour.from_now.iso8601,
+ )
+ end
+
+ before do
+ SiteSetting.calendar_enabled = true
+ SiteSetting.discourse_post_event_enabled = true
+ SiteSetting.livestream_zoom_enabled = true
+ SiteSetting.livestream_zoom_sdk_key = "sdk-key"
+ SiteSetting.livestream_zoom_sdk_secret = "sdk-secret"
+ end
+
+ describe "#prepare_zoom_signature" do
+ it "rejects anonymous users" do
+ get "/discourse-calendar/livestream/zoom/signature.json", params: { topic_id: topic.id }
+
+ expect(response.status).to eq(403)
+ end
+
+ context "when signed in" do
+ before { sign_in(current_user) }
+
+ it "returns the Zoom join payload" do
+ get "/discourse-calendar/livestream/zoom/signature.json", params: { topic_id: topic.id }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["sdk_key"]).to eq("sdk-key")
+ expect(response.parsed_body["meeting_number"]).to eq("123456789")
+ expect(response.parsed_body["password"]).to eq("secret")
+ expect(response.parsed_body["user_name"]).to eq(current_user.display_name)
+ expect(response.parsed_body["user_email"]).to eq(current_user.email)
+ expect(response.parsed_body["leave_url"]).to eq(topic.relative_url)
+ expect(response.parsed_body["signature"]).to be_present
+ end
+
+ it "returns a signature the Zoom SDK can verify" do
+ get "/discourse-calendar/livestream/zoom/signature.json", params: { topic_id: topic.id }
+
+ claims =
+ JWT.decode(response.parsed_body["signature"], "sdk-secret", true, algorithm: "HS256")[0]
+
+ expect(claims["sdkKey"]).to eq("sdk-key")
+ expect(claims["mn"]).to eq("123456789")
+ expect(claims["role"]).to eq(0)
+ end
+
+ it "rejects invalid params" do
+ get "/discourse-calendar/livestream/zoom/signature.json"
+
+ expect(response.status).to eq(400)
+ end
+
+ it "returns not found when livestreams are unavailable" do
+ SiteSetting.discourse_post_event_enabled = false
+
+ get "/discourse-calendar/livestream/zoom/signature.json", params: { topic_id: topic.id }
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns not found when Zoom embedding is unavailable" do
+ SiteSetting.livestream_zoom_enabled = false
+
+ get "/discourse-calendar/livestream/zoom/signature.json", params: { topic_id: topic.id }
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns not found when the topic does not exist" do
+ get "/discourse-calendar/livestream/zoom/signature.json", params: { topic_id: -1 }
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns not found when the topic cannot be seen" do
+ group = Fabricate(:group)
+ private_category = Fabricate(:private_category, group: group)
+ private_topic = Fabricate(:topic, category: private_category, tags: [tag])
+ private_post = Fabricate(:post, topic: private_topic, post_number: 1)
+ Fabricate(
+ :event,
+ post: private_post,
+ location: "https://us06web.zoom.us/j/123456789?pwd=secret",
+ livestream: true,
+ )
+
+ get "/discourse-calendar/livestream/zoom/signature.json",
+ params: {
+ topic_id: private_topic.id,
+ }
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns not found when there is no first-post event" do
+ topic_without_event = Fabricate(:topic, user: current_user, tags: [tag])
+ Fabricate(:post, user: current_user, topic: topic_without_event, post_number: 1)
+
+ get "/discourse-calendar/livestream/zoom/signature.json",
+ params: {
+ topic_id: topic_without_event.id,
+ }
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns not found when the event is not a livestream" do
+ event.update!(livestream: false)
+
+ get "/discourse-calendar/livestream/zoom/signature.json", params: { topic_id: topic.id }
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns not found when the livestream has no location or URL" do
+ event.update_columns(location: nil, url: nil)
+
+ get "/discourse-calendar/livestream/zoom/signature.json", params: { topic_id: topic.id }
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns not found when the livestream URL is not a supported Zoom URL" do
+ event.update!(location: "https://example.com/stream")
+
+ get "/discourse-calendar/livestream/zoom/signature.json", params: { topic_id: topic.id }
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns not found when the event is outside its timeframe" do
+ event.update!(
+ original_starts_at: 2.hours.from_now.iso8601,
+ original_ends_at: 3.hours.from_now.iso8601,
+ )
+
+ get "/discourse-calendar/livestream/zoom/signature.json", params: { topic_id: topic.id }
+
+ expect(response.status).to eq(404)
+ end
+
+ it "returns not found when the livestream URL is not served over HTTPS" do
+ event.update_columns(location: "http://zoom.us/j/123456789")
+
+ get "/discourse-calendar/livestream/zoom/signature.json", params: { topic_id: topic.id }
+
+ expect(response.status).to eq(404)
+ end
+ end
+ end
+
+ # The full-page mobile Zoom view is a client-side route rendered by the topic
+ # controller, so the server just needs to serve the topic at that path.
+ describe "the full-page Zoom route" do
+ it "serves the topic" do
+ get "/t/#{topic.slug}/#{topic.id}/zoom"
+
+ expect(response.status).to eq(200)
+ end
+
+ it "returns not found for an unknown topic" do
+ get "/t/#{topic.slug}/-1/zoom"
+
+ expect(response.status).to eq(404)
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-calendar/spec/serializers/discourse_post_event/event_serializer_spec.rb b/plugins/discourse-calendar/spec/serializers/discourse_post_event/event_serializer_spec.rb
index a040ed2004e..b534091220d 100644
--- a/plugins/discourse-calendar/spec/serializers/discourse_post_event/event_serializer_spec.rb
+++ b/plugins/discourse-calendar/spec/serializers/discourse_post_event/event_serializer_spec.rb
@@ -103,7 +103,10 @@ describe DiscoursePostEvent::EventSerializer do
context "when event is a livestream" do
let(:livestream_url) { "https://example.com/live" }
- let(:livestream_post) { Fabricate(:post, topic: topic) }
+ # The event must live on the topic's first post: `Event#before_save` clears
+ # the `livestream` flag on any other post.
+ let(:livestream_topic) { Fabricate(:topic, category: category) }
+ let(:livestream_post) { Fabricate(:post, topic: livestream_topic) }
let(:livestream_event) do
Fabricate(:event, post: livestream_post, livestream: true, location: livestream_url)
end
@@ -120,6 +123,97 @@ describe DiscoursePostEvent::EventSerializer do
expect(json[:event][:livestream_onebox]).to be_nil
end
end
+
+ it "does not fetch the onebox while serializing" do
+ livestream_event
+ Oneboxer.expects(:onebox).never
+
+ DiscoursePostEvent::EventSerializer.new(livestream_event, scope: Guardian.new).as_json
+ end
+
+ it "serves the onebox from the cache when it has been warmed" do
+ livestream_event
+ Discourse.cache.write(
+ Oneboxer.onebox_cache_key(livestream_url),
+ { onebox: "<aside>cached</aside>" },
+ )
+
+ json =
+ DiscoursePostEvent::EventSerializer.new(livestream_event, scope: Guardian.new).as_json
+
+ expect(json[:event][:livestream_onebox]).to eq("<aside>cached</aside>")
+ end
+
+ it "includes the livestream URL and chat channel id" do
+ livestream_event
+
+ json =
+ DiscoursePostEvent::EventSerializer.new(livestream_event, scope: Guardian.new).as_json
+
+ expect(json[:event][:livestream_url]).to eq(livestream_url)
+ expect(json[:event].key?(:livestream_chat_channel_id)).to eq(true)
+ end
+
+ it "is not a Zoom livestream" do
+ livestream_event
+
+ json =
+ DiscoursePostEvent::EventSerializer.new(livestream_event, scope: Guardian.new).as_json
+
+ expect(json[:event][:is_zoom_livestream]).to eq(false)
+ end
+ end
+
+ context "when the event is not a livestream" do
+ fab!(:plain_post) { Fabricate(:post, topic: topic) }
+ fab!(:plain_event) { Fabricate(:event, post: plain_post, location: "Room 5") }
+
+ it "omits the livestream attributes" do
+ json = DiscoursePostEvent::EventSerializer.new(plain_event, scope: Guardian.new).as_json
+
+ expect(json[:event].key?(:livestream_url)).to eq(false)
+ expect(json[:event].key?(:livestream_onebox)).to eq(false)
+ expect(json[:event].key?(:livestream_chat_channel_id)).to eq(false)
+ end
+ end
+
+ context "when the event is a Zoom livestream" do
+ let(:zoom_url) { "https://us06web.zoom.us/j/123456789?pwd=secret" }
+ let(:zoom_topic) { Fabricate(:topic, category: category) }
+ let(:zoom_post) { Fabricate(:post, topic: zoom_topic) }
+ let(:zoom_event) { Fabricate(:event, post: zoom_post, livestream: true, location: zoom_url) }
+
+ before do
+ SiteSetting.livestream_zoom_enabled = true
+ Jobs.run_later!
+ end
+
+ it "flags the event as a Zoom livestream" do
+ json = DiscoursePostEvent::EventSerializer.new(zoom_event, scope: Guardian.new).as_json
+
+ expect(json[:event][:is_zoom_livestream]).to eq(true)
+ expect(json[:event][:livestream_url]).to eq(zoom_url)
+ end
+
+ it "omits the onebox, since the Zoom entry component renders instead" do
+ Discourse.cache.write(
+ Oneboxer.onebox_cache_key(zoom_url),
+ { onebox: "<aside>cached</aside>" },
+ )
+
+ json = DiscoursePostEvent::EventSerializer.new(zoom_event, scope: Guardian.new).as_json
+
+ expect(json[:event].key?(:livestream_onebox)).to eq(false)
+ end
+
+ it "falls back to the onebox when Zoom is disabled" do
+ SiteSetting.livestream_zoom_enabled = false
+
+ json = DiscoursePostEvent::EventSerializer.new(zoom_event, scope: Guardian.new).as_json
+
+ expect(json[:event][:is_zoom_livestream]).to eq(false)
+ expect(json[:event].key?(:livestream_onebox)).to eq(true)
+ end
end
context "when event has duration" do
diff --git a/plugins/discourse-calendar/spec/serializers/topic_view_serializer_spec.rb b/plugins/discourse-calendar/spec/serializers/topic_view_serializer_spec.rb
index 1f0ad9f4173..4e9886176d2 100644
--- a/plugins/discourse-calendar/spec/serializers/topic_view_serializer_spec.rb
+++ b/plugins/discourse-calendar/spec/serializers/topic_view_serializer_spec.rb
@@ -138,7 +138,7 @@ RSpec.describe TopicViewSerializer do
before do
SiteSetting.chat_enabled = true
- # enqueue (don't run) the onebox-warming job so it doesn't make a real request
+ # Don't do onebox-warming job so it doesn't make a real request
Jobs.run_later!
first_post
end
diff --git a/plugins/discourse-calendar/spec/services/discourse_calendar/livestream/prepare_zoom_join_spec.rb b/plugins/discourse-calendar/spec/services/discourse_calendar/livestream/prepare_zoom_join_spec.rb
new file mode 100644
index 00000000000..c909862d864
--- /dev/null
+++ b/plugins/discourse-calendar/spec/services/discourse_calendar/livestream/prepare_zoom_join_spec.rb
@@ -0,0 +1,186 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseCalendar::Livestream::PrepareZoomJoin do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:topic_id) }
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, guardian:) }
+
+ fab!(:current_user, :user)
+ fab!(:tag) { Fabricate(:tag, name: "livestream") }
+ fab!(:topic) { Fabricate(:topic, user: current_user, tags: [tag]) }
+ fab!(:post) { Fabricate(:post, user: current_user, topic: topic, post_number: 1) }
+ fab!(:event) do
+ Fabricate(
+ :event,
+ post: post,
+ livestream: true,
+ location: "https://us06web.zoom.us/j/123456789?pwd=secret",
+ original_starts_at: 5.minutes.ago.iso8601,
+ original_ends_at: 1.hour.from_now.iso8601,
+ )
+ end
+
+ let(:guardian) { current_user.guardian }
+ let(:params) { { topic_id: topic.id } }
+
+ before do
+ SiteSetting.calendar_enabled = true
+ SiteSetting.discourse_post_event_enabled = true
+ SiteSetting.livestream_zoom_enabled = true
+ SiteSetting.livestream_zoom_sdk_key = "sdk-key"
+ SiteSetting.livestream_zoom_sdk_secret = "sdk-secret"
+ end
+
+ context "when the contract is invalid" do
+ let(:params) { { topic_id: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when post events are not enabled" do
+ before { SiteSetting.discourse_post_event_enabled = false }
+
+ it { is_expected.to fail_a_policy(:livestream_available) }
+ end
+
+ context "when Zoom embedding is disabled" do
+ before { SiteSetting.livestream_zoom_enabled = false }
+
+ it { is_expected.to fail_a_policy(:zoom_enabled) }
+ end
+
+ context "when the topic cannot be seen" do
+ fab!(:group)
+ fab!(:private_category) { Fabricate(:private_category, group:) }
+ fab!(:private_topic) do
+ Fabricate(:topic, user: current_user, category: private_category, tags: [tag])
+ end
+ fab!(:private_post) do
+ Fabricate(:post, user: current_user, topic: private_topic, post_number: 1)
+ end
+ fab!(:private_event) do
+ Fabricate(
+ :event,
+ post: private_post,
+ livestream: true,
+ location: "https://zoom.us/j/123456789?pwd=secret",
+ )
+ end
+ fab!(:outsider, :user)
+
+ let(:params) { { topic_id: private_topic.id } }
+ let(:guardian) { outsider.guardian }
+
+ it { is_expected.to fail_a_policy(:can_see_topic) }
+ end
+
+ context "when there is no first-post event" do
+ fab!(:topic_without_event) { Fabricate(:topic, user: current_user, tags: [tag]) }
+ fab!(:topic_without_event_post) do
+ Fabricate(:post, user: current_user, topic: topic_without_event, post_number: 1)
+ end
+
+ let(:params) { { topic_id: topic_without_event.id } }
+
+ it { is_expected.to fail_to_find_a_model(:event) }
+ end
+
+ context "when the event is not a livestream" do
+ before { event.update!(livestream: false) }
+
+ it { is_expected.to fail_a_policy(:event_has_livestream) }
+ end
+
+ context "when the livestream has no location or URL" do
+ before { event.update_columns(location: nil, url: nil) }
+
+ it { is_expected.to fail_a_policy(:event_has_livestream) }
+ end
+
+ context "when the livestream URL is not a supported Zoom URL" do
+ before { event.update!(location: "https://example.com/stream") }
+
+ it { is_expected.to fail_to_find_a_model(:zoom_join_data) }
+ end
+
+ context "when the event has not opened for early access yet" do
+ before do
+ event.update!(
+ original_starts_at: 2.hours.from_now.iso8601,
+ original_ends_at: 3.hours.from_now.iso8601,
+ )
+ end
+
+ it { is_expected.to fail_a_policy(:event_within_timeframe) }
+ end
+
+ context "when the event ended more than the grace period ago" do
+ before do
+ event.update!(original_starts_at: 3.hours.ago.iso8601, original_ends_at: 1.hour.ago.iso8601)
+ end
+
+ it { is_expected.to fail_a_policy(:event_within_timeframe) }
+ end
+
+ # TODO (martin) ignore_timeframe backs the showzoom testing workaround,
+ # remove these examples along with it before merge
+ context "when a staff user asks to ignore the timeframe" do
+ fab!(:admin)
+
+ let(:guardian) { admin.guardian }
+ let(:params) { { topic_id: topic.id, ignore_timeframe: true } }
+
+ before do
+ event.update!(
+ original_starts_at: 2.hours.from_now.iso8601,
+ original_ends_at: 3.hours.from_now.iso8601,
+ )
+ end
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when a regular user asks to ignore the timeframe" do
+ let(:params) { { topic_id: topic.id, ignore_timeframe: true } }
+
+ before do
+ event.update!(
+ original_starts_at: 2.hours.from_now.iso8601,
+ original_ends_at: 3.hours.from_now.iso8601,
+ )
+ end
+
+ it { is_expected.to fail_a_policy(:event_within_timeframe) }
+ end
+
+ context "when the event starts within the early access window" do
+ before do
+ event.update!(
+ original_starts_at: 15.minutes.from_now.iso8601,
+ original_ends_at: 2.hours.from_now.iso8601,
+ )
+ end
+
+ it { is_expected.to run_successfully }
+ end
+
+ context "when everything is valid" do
+ it { is_expected.to run_successfully }
+
+ it "returns the Zoom join payload" do
+ expect(result.zoom_join_payload).to include(
+ sdk_key: "sdk-key",
+ signature: be_present,
+ meeting_number: "123456789",
+ password: "secret",
+ user_name: current_user.display_name,
+ user_email: current_user.email,
+ leave_url: topic.relative_url,
+ )
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-calendar/spec/services/discourse_calendar/livestream/zoom_payload_builder_spec.rb b/plugins/discourse-calendar/spec/services/discourse_calendar/livestream/zoom_payload_builder_spec.rb
new file mode 100644
index 00000000000..f3fe22c2cdb
--- /dev/null
+++ b/plugins/discourse-calendar/spec/services/discourse_calendar/livestream/zoom_payload_builder_spec.rb
@@ -0,0 +1,86 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseCalendar::Livestream::ZoomPayloadBuilder do
+ subject(:payload) { described_class.call(topic:, user:, zoom_join_data:) }
+
+ fab!(:user)
+ fab!(:topic)
+
+ let(:zoom_join_data) do
+ { meeting_number: "123456789", password: "secret", url: "https://zoom.us/j/123456789" }
+ end
+
+ before do
+ SiteSetting.livestream_zoom_sdk_key = "sdk-key"
+ SiteSetting.livestream_zoom_sdk_secret = "sdk-secret"
+ end
+
+ def decoded_signature
+ JWT.decode(
+ payload[:signature],
+ SiteSetting.livestream_zoom_sdk_secret,
+ true,
+ algorithm: "HS256",
+ )[
+ 0
+ ]
+ end
+
+ it "returns everything the Meeting SDK needs to join" do
+ expect(payload).to include(
+ sdk_key: "sdk-key",
+ meeting_number: "123456789",
+ password: "secret",
+ user_name: user.display_name,
+ user_email: user.email,
+ leave_url: topic.relative_url,
+ )
+ end
+
+ it "signs the payload with the configured SDK secret" do
+ expect {
+ JWT.decode(payload[:signature], "wrong-secret", true, algorithm: "HS256")
+ }.to raise_error(JWT::VerificationError)
+ expect(decoded_signature).to be_present
+ end
+
+ it "signs the user in as a participant, never as the host" do
+ expect(decoded_signature["role"]).to eq(described_class::ROLE_PARTICIPANT)
+ expect(decoded_signature["role"]).to eq(0)
+ end
+
+ it "signs the meeting number the user is joining" do
+ expect(decoded_signature["mn"]).to eq("123456789")
+ expect(decoded_signature["sdkKey"]).to eq("sdk-key")
+ expect(decoded_signature["appKey"]).to eq("sdk-key")
+ end
+
+ it "backdates the issued-at claim so a skewed client clock still accepts the token" do
+ freeze_time
+
+ expect(decoded_signature["iat"]).to eq(
+ Time.zone.now.to_i - described_class::TOKEN_ISSUE_LEEWAY.to_i,
+ )
+ end
+
+ it "expires the token two hours after it was issued" do
+ freeze_time
+
+ expected =
+ Time.zone.now.to_i - described_class::TOKEN_ISSUE_LEEWAY.to_i +
+ described_class::TOKEN_VALIDITY.to_i
+
+ expect(decoded_signature["exp"]).to eq(expected)
+ expect(decoded_signature["tokenExp"]).to eq(expected)
+ end
+
+ context "when the meeting has no password" do
+ let(:zoom_join_data) do
+ { meeting_number: "123456789", password: nil, url: "https://zoom.us/j/123456789" }
+ end
+
+ it "returns a nil password rather than omitting it" do
+ expect(payload).to include(password: nil)
+ end
+ end
+end
diff --git a/plugins/discourse-calendar/spec/system/desktop_topic_livestream_authenticated_spec.rb b/plugins/discourse-calendar/spec/system/desktop_topic_livestream_authenticated_spec.rb
index 7977a3150f0..ac4e011865f 100644
--- a/plugins/discourse-calendar/spec/system/desktop_topic_livestream_authenticated_spec.rb
+++ b/plugins/discourse-calendar/spec/system/desktop_topic_livestream_authenticated_spec.rb
@@ -13,6 +13,7 @@ describe "Discourse Livestream - Topic Livestream - Desktop - Authenticated" do
SiteSetting.chat_enabled = true
SiteSetting.discourse_post_event_enabled = true
SiteSetting.discourse_post_event_allowed_on_groups = Group::AUTO_GROUPS[:everyone].to_s
+ topic_livestream.cache_livestream_onebox
sign_in(current_user)
end
diff --git a/plugins/discourse-calendar/spec/system/livestream_calendar_event_spec.rb b/plugins/discourse-calendar/spec/system/livestream_calendar_event_spec.rb
index 9be56c1629a..2c839201c8f 100644
--- a/plugins/discourse-calendar/spec/system/livestream_calendar_event_spec.rb
+++ b/plugins/discourse-calendar/spec/system/livestream_calendar_event_spec.rb
@@ -14,6 +14,7 @@ describe "Discourse Livestream - Topic Livestream with events - Authenticated" d
SiteSetting.chat_enabled = true
SiteSetting.discourse_post_event_enabled = true
SiteSetting.discourse_post_event_allowed_on_groups = group.id.to_s
+ topic_livestream.cache_livestream_onebox
sign_in(current_user)
end
diff --git a/plugins/discourse-calendar/spec/system/mobile_topic_livestream_authenticated_spec.rb b/plugins/discourse-calendar/spec/system/mobile_topic_livestream_authenticated_spec.rb
index e377f4a42db..b62f7bb880d 100644
--- a/plugins/discourse-calendar/spec/system/mobile_topic_livestream_authenticated_spec.rb
+++ b/plugins/discourse-calendar/spec/system/mobile_topic_livestream_authenticated_spec.rb
@@ -13,6 +13,7 @@ describe "Discourse Livestream - Topic Livestream - Mobile - Authenticated", mob
SiteSetting.calendar_enabled = true
SiteSetting.chat_enabled = true
SiteSetting.discourse_post_event_enabled = true
+ topic_livestream.cache_livestream_onebox
sign_in(admin)
end
diff --git a/plugins/discourse-calendar/spec/system/page_objects/discourse_calendar/livestream/topic_livestream.rb b/plugins/discourse-calendar/spec/system/page_objects/discourse_calendar/livestream/topic_livestream.rb
index 4ed8a6a2008..f45951b4185 100644
--- a/plugins/discourse-calendar/spec/system/page_objects/discourse_calendar/livestream/topic_livestream.rb
+++ b/plugins/discourse-calendar/spec/system/page_objects/discourse_calendar/livestream/topic_livestream.rb
@@ -3,6 +3,15 @@
module PageObjects
module Pages
class TopicLivestream < PageObjects::Pages::Base
+ LIVESTREAM_URL = "https://example.com/live"
+
+ def cache_livestream_onebox
+ Discourse.cache.write(
+ Oneboxer.onebox_cache_key(LIVESTREAM_URL),
+ { onebox: "<aside>cached livestream</aside>" },
+ )
+ end
+
def create_livestream_topic(composer, topic_page, tag)
visit("/latest")
topic_page.open_new_topic
@@ -15,7 +24,7 @@ module PageObjects
tomorrow = 1.day.from_now.strftime("%Y-%m-%d")
composer.fill_content <<~MD
- [event start="#{tomorrow} 13:37" status="public" livestream="true" location="https://example.com/live"]
+ [event start="#{tomorrow} 13:37" status="public" livestream="true" location="#{LIVESTREAM_URL}"]
[/event]
MD
composer.create
@@ -42,7 +51,7 @@ module PageObjects
tomorrow = 1.day.from_now.strftime("%Y-%m-%d")
composer.fill_content <<~MD
- [event start="#{tomorrow} 13:37" status="public" livestream="true" location="https://example.com/live"]
+ [event start="#{tomorrow} 13:37" status="public" livestream="true" location="#{LIVESTREAM_URL}"]
[/event]
MD
composer.create
diff --git a/plugins/discourse-calendar/test/javascripts/integration/components/livestream-test.gjs b/plugins/discourse-calendar/test/javascripts/integration/components/livestream-test.gjs
new file mode 100644
index 00000000000..0546cab8576
--- /dev/null
+++ b/plugins/discourse-calendar/test/javascripts/integration/components/livestream-test.gjs
@@ -0,0 +1,94 @@
+import { getOwner } from "@ember/owner";
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import Livestream from "../../discourse/components/discourse-post-event/livestream";
+
+const ZOOM_URL = "https://us06web.zoom.us/j/123456789?pwd=secret";
+const ZOOM_ENTRY_SELECTOR = ".discourse-calendar-livestream-zoom-entry";
+
+module(
+ "Integration | Component | DiscoursePostEvent::Livestream",
+ function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ const owner = getOwner(this);
+
+ owner.unregister("service:capabilities");
+ owner.register(
+ "service:capabilities",
+ { viewport: { lg: true } },
+ { instantiate: false }
+ );
+
+ owner.lookup("service:site-settings").livestream_zoom_enabled = true;
+
+ this.event = {
+ livestream: true,
+ livestreamUrl: ZOOM_URL,
+ livestreamChatChannelId: 9,
+ isZoomLivestream: true,
+ post: { topic: { id: 1, slug: "test-topic", chat_channel_id: 9 } },
+ };
+ });
+
+ test("renders nothing when the event has no livestream", async function (assert) {
+ this.event.livestream = false;
+
+ await render(<template><Livestream @event={{this.event}} /></template>);
+
+ assert.dom(".event-livestream").doesNotExist();
+ });
+
+ test("renders nothing when the livestream has no URL", async function (assert) {
+ this.event.livestreamUrl = null;
+
+ await render(<template><Livestream @event={{this.event}} /></template>);
+
+ assert.dom(".event-livestream").doesNotExist();
+ });
+
+ test("renders the Zoom entry for a Zoom livestream", async function (assert) {
+ await render(<template><Livestream @event={{this.event}} /></template>);
+
+ assert.dom(ZOOM_ENTRY_SELECTOR).exists();
+ });
+
+ test("does not render the Zoom entry when Zoom is disabled", async function (assert) {
+ getOwner(this).lookup("service:site-settings").livestream_zoom_enabled =
+ false;
+
+ await render(<template><Livestream @event={{this.event}} /></template>);
+
+ assert.dom(ZOOM_ENTRY_SELECTOR).doesNotExist();
+ assert
+ .dom(".event-livestream")
+ .exists("still renders the livestream section");
+ });
+
+ test("renders the onebox for a non-Zoom livestream", async function (assert) {
+ this.event.isZoomLivestream = false;
+ this.event.livestreamUrl = "https://example.com/live";
+ this.event.livestreamOnebox = "<aside class='onebox'>cached</aside>";
+
+ await render(<template><Livestream @event={{this.event}} /></template>);
+
+ assert.dom(ZOOM_ENTRY_SELECTOR).doesNotExist();
+ assert
+ .dom(".event-livestream aside.onebox")
+ .exists("renders the cached onebox");
+ });
+
+ test("renders nothing inside the section when the onebox has not warmed yet", async function (assert) {
+ this.event.isZoomLivestream = false;
+ this.event.livestreamUrl = "https://example.com/live";
+ this.event.livestreamOnebox = null;
+
+ await render(<template><Livestream @event={{this.event}} /></template>);
+
+ assert.dom(".event-livestream").exists();
+ assert.dom(".event-livestream aside.onebox").doesNotExist();
+ });
+ }
+);
diff --git a/plugins/discourse-calendar/test/javascripts/integration/components/post-event-builder-test.gjs b/plugins/discourse-calendar/test/javascripts/integration/components/post-event-builder-test.gjs
index 74c99950c82..8cdda967fa2 100644
--- a/plugins/discourse-calendar/test/javascripts/integration/components/post-event-builder-test.gjs
+++ b/plugins/discourse-calendar/test/javascripts/integration/components/post-event-builder-test.gjs
@@ -117,7 +117,7 @@ module("Integration | Component | Modal | PostEventBuilder", function (hooks) {
reminders: [],
raw_invitees: [],
custom_fields: {},
- location: "https://example.com/live",
+ location: "https://zoom.us/j/123456789",
livestream: true,
});
diff --git a/plugins/discourse-calendar/test/javascripts/integration/components/zoom-entry-test.gjs b/plugins/discourse-calendar/test/javascripts/integration/components/zoom-entry-test.gjs
new file mode 100644
index 00000000000..1bf39fe93ff
--- /dev/null
+++ b/plugins/discourse-calendar/test/javascripts/integration/components/zoom-entry-test.gjs
@@ -0,0 +1,722 @@
+import { getOwner } from "@ember/owner";
+import { clearRender, click, render, settled } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import LivestreamZoomEntry from "../../discourse/components/livestream/zoom-entry";
+import ZoomMeetingSession, {
+ MAX_RETRY_ATTEMPTS,
+ RETRY_DELAY_SECONDS,
+} from "../../discourse/lib/zoom-meeting-session";
+
+const MEETING_NOT_STARTED = {
+ errorCode: 3008,
+ reason: "Meeting has not started",
+};
+
+const WAITING_SELECTOR = ".discourse-calendar-livestream-zoom-entry__waiting";
+const ERROR_SELECTOR = ".discourse-calendar-livestream-zoom-entry__error";
+const FRAME_SELECTOR = ".discourse-calendar-livestream-zoom-entry__frame";
+const JOIN_BUTTON_SELECTOR =
+ ".discourse-calendar-livestream-zoom-entry .btn-primary";
+const LEAVE_BUTTON_SELECTOR = ".zoom-MuiButton-root";
+
+const COUNTDOWN_TEXT = `The webinar hasn't started yet. Retrying join in ${RETRY_DELAY_SECONDS} seconds...`;
+const ERROR_TEXT =
+ "You left the webinar or we are unable to load Zoom in this page.";
+
+// `join` guards against being called when the button is disabled, which a
+// test can never reach through a click. `registerRoot` runs from the modifier
+// on insert, so stubbing it hands us the session instance before any join.
+function captureSession() {
+ const captured = {};
+
+ const stub = sinon
+ .stub(ZoomMeetingSession.prototype, "registerRoot")
+ .callsFake(function (element) {
+ captured.session = this;
+ stub.wrappedMethod.call(this, element);
+ });
+
+ return captured;
+}
+
+function deferred() {
+ let resolve, reject;
+ const promise = new Promise((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+// Zoom renders its own leave button inside the app root, both on the
+// "meeting has not started" panel and on the joined toolbar. The component can
+// only tell them apart by its own `isJoined` state, so both look like this.
+// The inner span stands in for Zoom's icon, and makes sure we still match when
+// the click lands on a descendant rather than the button itself.
+function renderZoomLeaveButton() {
+ const frame = document.querySelector(FRAME_SELECTOR);
+ frame.innerHTML = `<button class="zoom-MuiButton-root" title="Leave"><span class="zoom-icon"></span></button>`;
+}
+
+module("Integration | Component | LivestreamZoomEntry", function (hooks) {
+ setupRenderingTest(hooks);
+
+ function stubCapabilities(owner, viewport) {
+ owner.unregister("service:capabilities");
+ owner.register(
+ "service:capabilities",
+ {
+ viewport,
+ },
+ { instantiate: false }
+ );
+ }
+
+ // Stands in for the real API service, mirroring the parts of `joinEvent` and
+ // `updateEventAttendance` the component depends on: both leave the event
+ // carrying a `watchingInvitee` with the new status.
+ function stubEventApi(owner) {
+ const api = {
+ joinEvent: sinon.fake(function (event, payload) {
+ event.watchingInvitee = { id: 5, status: payload.status };
+ return Promise.resolve(event.watchingInvitee);
+ }),
+ updateEventAttendance: sinon.fake(function (event, payload) {
+ event.watchingInvitee = { ...event.watchingInvitee, ...payload };
+ return Promise.resolve(event.watchingInvitee);
+ }),
+ };
+
+ owner.unregister("service:discourse-post-event-api");
+ owner.register("service:discourse-post-event-api", api, {
+ instantiate: false,
+ });
+
+ return api;
+ }
+
+ hooks.beforeEach(function () {
+ const siteSettings = getOwner(this).lookup("service:site-settings");
+ siteSettings.livestream_zoom_enabled = true;
+
+ this.eventApi = stubEventApi(getOwner(this));
+
+ this.event = {
+ id: 42,
+ currentlyWithinEventTimeframe: true,
+ canUpdateAttendance: true,
+ watchingInvitee: null,
+ livestreamChatChannelId: 9,
+ post: {
+ topic: {
+ id: 1,
+ slug: "test-topic",
+ chat_channel_id: 9,
+ },
+ },
+ url: "https://us06web.zoom.us/j/123456789?pwd=secret",
+ livestreamUrl: "https://us06web.zoom.us/j/123456789?pwd=secret",
+ };
+ });
+
+ test("renders the inline join button on desktop", async function (assert) {
+ stubCapabilities(getOwner(this), { lg: true });
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ assert.dom(JOIN_BUTTON_SELECTOR).hasText("Join Zoom");
+ assert.dom(FRAME_SELECTOR).exists();
+ assert
+ .dom(`${FRAME_SELECTOR}.--visible`)
+ .doesNotExist("the frame is hidden until the user joins");
+ assert
+ .dom(".discourse-calendar-livestream-zoom-entry a")
+ .doesNotExist("no fallback link before an error");
+ });
+
+ test("renders the mobile route link on mobile", async function (assert) {
+ stubCapabilities(getOwner(this), { lg: false });
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ assert.dom(JOIN_BUTTON_SELECTOR).hasText("Join Zoom");
+ assert
+ .dom(FRAME_SELECTOR)
+ .doesNotExist("does not render the inline Zoom frame");
+ });
+
+ test("disables the join button outside the event timeframe", async function (assert) {
+ stubCapabilities(getOwner(this), { lg: true });
+ this.event.currentlyWithinEventTimeframe = false;
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ assert.dom(JOIN_BUTTON_SELECTOR).isDisabled();
+ assert
+ .dom(WAITING_SELECTOR)
+ .hasText("You can join the webinar closer to the event start time");
+ });
+
+ test("disables the mobile join button outside the event timeframe", async function (assert) {
+ stubCapabilities(getOwner(this), { lg: false });
+ this.event.currentlyWithinEventTimeframe = false;
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ assert.dom(JOIN_BUTTON_SELECTOR).isDisabled();
+ assert
+ .dom(WAITING_SELECTOR)
+ .hasText("You can join the webinar closer to the event start time");
+ });
+
+ test("renders nothing once the event is past its grace period", async function (assert) {
+ stubCapabilities(getOwner(this), { lg: true });
+ this.event.currentlyWithinEventTimeframe = false;
+ this.event.pastEventTimeframe = true;
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ assert.dom(".discourse-calendar-livestream-zoom-entry").doesNotExist();
+ });
+
+ test("renders nothing when Zoom livestreams are disabled", async function (assert) {
+ stubCapabilities(getOwner(this), { lg: true });
+ getOwner(this).lookup("service:site-settings").livestream_zoom_enabled =
+ false;
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ assert.dom(".discourse-calendar-livestream-zoom-entry").doesNotExist();
+ });
+
+ test("renders nothing without a livestream chat channel", async function (assert) {
+ stubCapabilities(getOwner(this), { lg: true });
+ this.event.livestreamChatChannelId = null;
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ assert.dom(".discourse-calendar-livestream-zoom-entry").doesNotExist();
+ });
+
+ test("renders nothing for anonymous users", async function (assert) {
+ stubCapabilities(getOwner(this), { lg: true });
+ getOwner(this).unregister("service:current-user");
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ assert.dom(".discourse-calendar-livestream-zoom-entry").doesNotExist();
+ });
+
+ module("when marking attendance", function (innerHooks) {
+ let appEvents, performJoin;
+
+ innerHooks.beforeEach(function () {
+ stubCapabilities(getOwner(this), { lg: true });
+ performJoin = sinon.stub(ZoomMeetingSession.prototype, "performJoin");
+ performJoin.resolves();
+ appEvents = sinon.stub(
+ getOwner(this).lookup("service:app-events"),
+ "trigger"
+ );
+ sinon.stub(console, "error");
+ });
+
+ test("marks a user who has not answered as going", async function (assert) {
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+
+ assert.strictEqual(this.eventApi.joinEvent.callCount, 1);
+ assert.deepEqual(this.eventApi.joinEvent.firstCall.args[1], {
+ status: "going",
+ });
+ assert.true(
+ appEvents.calledWith("calendar:create-invitee-status", {
+ status: "going",
+ postId: 42,
+ }),
+ "tells the rest of the page the RSVP changed"
+ );
+ assert.dom(`${FRAME_SELECTOR}.--joined`).exists("still joins Zoom");
+ });
+
+ test("marks an invitee with no status as going", async function (assert) {
+ this.event.watchingInvitee = { id: 5, status: null };
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+
+ assert.false(
+ this.eventApi.joinEvent.called,
+ "does not re-join the event"
+ );
+ assert.strictEqual(this.eventApi.updateEventAttendance.callCount, 1);
+ assert.deepEqual(this.eventApi.updateEventAttendance.firstCall.args[1], {
+ status: "going",
+ });
+ assert.true(
+ appEvents.calledWith("calendar:update-invitee-status", {
+ status: "going",
+ postId: 42,
+ })
+ );
+ });
+
+ test("leaves an existing answer alone", async function (assert) {
+ this.event.watchingInvitee = { id: 5, status: "not_going" };
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+
+ assert.false(this.eventApi.joinEvent.called);
+ assert.false(
+ this.eventApi.updateEventAttendance.called,
+ "an explicit 'not going' is not overwritten"
+ );
+ assert.dom(`${FRAME_SELECTOR}.--joined`).exists("still joins Zoom");
+ });
+
+ test("leaves an existing 'going' answer alone", async function (assert) {
+ this.event.watchingInvitee = { id: 5, status: "going", recurring: true };
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+
+ assert.false(
+ this.eventApi.updateEventAttendance.called,
+ "does not clobber a recurring RSVP"
+ );
+ });
+
+ test("does not RSVP when the user may not update attendance", async function (assert) {
+ this.event.canUpdateAttendance = false;
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+
+ assert.false(this.eventApi.joinEvent.called);
+ assert.dom(`${FRAME_SELECTOR}.--joined`).exists("still joins Zoom");
+ });
+
+ test("joins Zoom even when the RSVP fails", async function (assert) {
+ this.eventApi.joinEvent = sinon.fake.rejects(new Error("nope"));
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+
+ assert.dom(`${FRAME_SELECTOR}.--joined`).exists("still joins Zoom");
+ assert.dom(ERROR_SELECTOR).doesNotExist("does not surface an error");
+ });
+
+ test("only RSVPs once when the join is retried", async function (assert) {
+ const clock = sinon.useFakeTimers({
+ toFake: ["setInterval", "clearInterval"],
+ });
+
+ try {
+ performJoin.rejects(MEETING_NOT_STARTED);
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+
+ performJoin.resolves();
+ clock.tick(RETRY_DELAY_SECONDS * 1000);
+ await settled();
+
+ assert.dom(`${FRAME_SELECTOR}.--joined`).exists();
+ assert.strictEqual(
+ this.eventApi.joinEvent.callCount,
+ 1,
+ "the retry sees the RSVP it already made"
+ );
+ } finally {
+ clock.restore();
+ }
+ });
+ });
+
+ module("when joining", function (innerHooks) {
+ let performJoin;
+
+ innerHooks.beforeEach(function () {
+ stubCapabilities(getOwner(this), { lg: true });
+ performJoin = sinon.stub(ZoomMeetingSession.prototype, "performJoin");
+ sinon.stub(console, "error");
+ });
+
+ test("shows the Zoom frame and joins", async function (assert) {
+ performJoin.resolves();
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+
+ assert.true(performJoin.calledOnce);
+ assert.dom(`${FRAME_SELECTOR}.--visible.--joined`).exists();
+ assert.dom(JOIN_BUTTON_SELECTOR).doesNotExist("hides the join button");
+ assert.dom(ERROR_SELECTOR).doesNotExist();
+ });
+
+ test("ignores a second click while a join is in flight", async function (assert) {
+ const join = deferred();
+ performJoin.returns(join.promise);
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ // Not awaited: the join is deliberately left pending.
+ click(JOIN_BUTTON_SELECTOR);
+ await settled();
+
+ assert.dom(JOIN_BUTTON_SELECTOR).isDisabled("disabled while joining");
+
+ join.resolve();
+ await settled();
+
+ assert.true(performJoin.calledOnce, "only joined once");
+ });
+
+ test("does not join outside the event timeframe", async function (assert) {
+ performJoin.resolves();
+ this.event.currentlyWithinEventTimeframe = false;
+ const captured = captureSession();
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ assert.dom(JOIN_BUTTON_SELECTOR).isDisabled();
+
+ await captured.session.join();
+
+ assert.false(performJoin.called, "the guard refuses the join");
+ assert.dom(`${FRAME_SELECTOR}.--visible`).doesNotExist();
+ });
+
+ test("shows an error and a fallback link when the join fails", async function (assert) {
+ performJoin.rejects(new Error("nope"));
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+
+ assert.dom(ERROR_SELECTOR).hasText(ERROR_TEXT);
+ assert
+ .dom(".discourse-calendar-livestream-zoom-entry a")
+ .hasText("Open in Zoom", "offers the fallback link");
+ assert.dom(`${FRAME_SELECTOR}.--visible`).doesNotExist();
+ assert.dom(JOIN_BUTTON_SELECTOR).isNotDisabled("can be retried");
+ });
+
+ test("clears a previous error once a later join succeeds", async function (assert) {
+ performJoin.rejects(new Error("nope"));
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+ assert.dom(ERROR_SELECTOR).exists();
+
+ performJoin.resolves();
+ await click(JOIN_BUTTON_SELECTOR);
+
+ assert.dom(ERROR_SELECTOR).doesNotExist("clears the error message");
+ assert
+ .dom(".discourse-calendar-livestream-zoom-entry a")
+ .doesNotExist("clears the fallback link");
+ assert.dom(`${FRAME_SELECTOR}.--joined`).exists();
+ });
+
+ test("leaving a joined meeting is left to Zoom's confirmation dialog", async function (assert) {
+ performJoin.resolves();
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+ renderZoomLeaveButton();
+
+ // Zoom's toolbar leave button only opens a confirmation popper. Tearing
+ // the frame down here would strand the user in an invisible meeting.
+ await click(LEAVE_BUTTON_SELECTOR);
+
+ assert.dom(`${FRAME_SELECTOR}.--joined`).exists("keeps the frame up");
+ assert.dom(JOIN_BUTTON_SELECTOR).doesNotExist("stays joined");
+ });
+
+ test("hides the frame when the meeting closes", async function (assert) {
+ let session;
+ performJoin.callsFake(function () {
+ session = this;
+ return Promise.resolve();
+ });
+
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+ document.querySelector(FRAME_SELECTOR).style.height = "600px";
+
+ // What the `connection-change` handler does when the host ends the
+ // meeting while the user is still on the page.
+ session.leaveZoom();
+ await settled();
+
+ assert.dom(`${FRAME_SELECTOR}.--visible`).doesNotExist("hides the frame");
+ assert.dom(`${FRAME_SELECTOR}.--joined`).doesNotExist();
+ assert.strictEqual(
+ document.querySelector(FRAME_SELECTOR).style.height,
+ "",
+ "strips the inline height Zoom left behind, which would otherwise leave an empty box"
+ );
+ assert.dom(JOIN_BUTTON_SELECTOR).isNotDisabled("can join again");
+ });
+ });
+
+ module("when the meeting has not started", function (innerHooks) {
+ let clock, performJoin;
+
+ innerHooks.beforeEach(function () {
+ stubCapabilities(getOwner(this), { lg: true });
+
+ // Only the countdown timers are faked, so `settled()` still works.
+ clock = sinon.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });
+
+ performJoin = sinon.stub(ZoomMeetingSession.prototype, "performJoin");
+ performJoin.rejects(MEETING_NOT_STARTED);
+
+ sinon.stub(console, "error");
+ });
+
+ innerHooks.afterEach(function () {
+ clock.restore();
+ });
+
+ async function tick(seconds) {
+ clock.tick(seconds * 1000);
+ await settled();
+ }
+
+ test("counts down and retries the join", async function (assert) {
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+
+ assert.dom(JOIN_BUTTON_SELECTOR).isDisabled();
+ assert
+ .dom(WAITING_SELECTOR)
+ .hasText(COUNTDOWN_TEXT, "shows the initial countdown");
+ assert
+ .dom(`${FRAME_SELECTOR}.--visible`)
+ .exists("keeps the Zoom frame up while waiting");
+ assert
+ .dom(`${FRAME_SELECTOR}.--joined`)
+ .doesNotExist("but not in its joined layout");
+
+ await tick(1);
+
+ assert
+ .dom(WAITING_SELECTOR)
+ .hasText(
+ `The webinar hasn't started yet. Retrying join in ${
+ RETRY_DELAY_SECONDS - 1
+ } seconds...`,
+ "the countdown updates every second"
+ );
+
+ performJoin.resetHistory();
+ await tick(RETRY_DELAY_SECONDS - 1);
+
+ assert.true(performJoin.calledOnce, "retries the join at zero");
+ assert
+ .dom(WAITING_SELECTOR)
+ .hasText(
+ COUNTDOWN_TEXT,
+ "restarts the countdown after another failure"
+ );
+ });
+
+ test("reports that a retry is in flight", async function (assert) {
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+
+ const retry = deferred();
+ performJoin.returns(retry.promise);
+ await tick(RETRY_DELAY_SECONDS);
+
+ assert
+ .dom(WAITING_SELECTOR)
+ .hasText(
+ "Trying to join the webinar again now...",
+ "swaps the countdown for the in-flight message"
+ );
+
+ retry.resolve();
+ await settled();
+
+ assert.dom(WAITING_SELECTOR).doesNotExist();
+ assert.dom(`${FRAME_SELECTOR}.--joined`).exists();
+ });
+
+ test("joins when the meeting starts", async function (assert) {
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+
+ performJoin.resolves();
+ await tick(RETRY_DELAY_SECONDS);
+
+ assert.dom(WAITING_SELECTOR).doesNotExist("clears the waiting message");
+ assert.dom(JOIN_BUTTON_SELECTOR).doesNotExist("hides the join button");
+ assert
+ .dom(`${FRAME_SELECTOR}.--joined`)
+ .exists("shows the joined Zoom frame");
+ });
+
+ test("stops retrying on a non-retryable error", async function (assert) {
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+
+ performJoin.rejects(new Error("nope"));
+ await tick(RETRY_DELAY_SECONDS);
+
+ assert.dom(WAITING_SELECTOR).doesNotExist("stops the countdown");
+ assert.dom(JOIN_BUTTON_SELECTOR).isNotDisabled();
+ assert.dom(ERROR_SELECTOR).hasText(ERROR_TEXT);
+ assert
+ .dom(`${FRAME_SELECTOR}.--visible`)
+ .doesNotExist("tears the Zoom frame down");
+ assert
+ .dom(".discourse-calendar-livestream-zoom-entry a")
+ .hasText("Open in Zoom", "offers the fallback link");
+ });
+
+ test("gives up once the retry budget is exhausted", async function (assert) {
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+
+ // The initial click is attempt 1, so MAX_RETRY_ATTEMPTS further attempts
+ // exhaust the budget.
+ for (let i = 0; i < MAX_RETRY_ATTEMPTS; i++) {
+ await tick(RETRY_DELAY_SECONDS);
+ }
+
+ assert.dom(WAITING_SELECTOR).doesNotExist("stops the countdown");
+ assert.dom(JOIN_BUTTON_SELECTOR).isNotDisabled();
+ assert.dom(ERROR_SELECTOR).hasText(ERROR_TEXT);
+ });
+
+ test("stops retrying when the user leaves Zoom's not-started panel", async function (assert) {
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+ renderZoomLeaveButton();
+
+ // Zoom fires no `connection-change` event from this panel, so the click
+ // itself is the only signal that the user wants out.
+ await click(LEAVE_BUTTON_SELECTOR);
+
+ assert.dom(WAITING_SELECTOR).doesNotExist("stops the countdown");
+ assert.dom(`${FRAME_SELECTOR}.--visible`).doesNotExist("hides the frame");
+ assert.dom(JOIN_BUTTON_SELECTOR).isNotDisabled("re-enables joining");
+
+ performJoin.resetHistory();
+ await tick(RETRY_DELAY_SECONDS * 2);
+
+ assert.false(performJoin.called, "does not retry after leaving");
+ });
+
+ test("can join again after leaving the not-started panel", async function (assert) {
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+ renderZoomLeaveButton();
+ await click(LEAVE_BUTTON_SELECTOR);
+
+ performJoin.resolves();
+ await click(JOIN_BUTTON_SELECTOR);
+
+ assert.dom(`${FRAME_SELECTOR}.--joined`).exists("joins on a fresh click");
+ });
+
+ test("stops retrying once the component is torn down", async function (assert) {
+ await render(
+ <template><LivestreamZoomEntry @event={{this.event}} /></template>
+ );
+
+ await click(JOIN_BUTTON_SELECTOR);
+ await clearRender();
+
+ performJoin.resetHistory();
+ await tick(RETRY_DELAY_SECONDS * 2);
+
+ assert.false(
+ performJoin.called,
+ "the retry timer does not outlive the component"
+ );
+ });
+ });
+});
diff --git a/plugins/discourse-calendar/test/javascripts/integration/components/zoom-page-test.gjs b/plugins/discourse-calendar/test/javascripts/integration/components/zoom-page-test.gjs
new file mode 100644
index 00000000000..fde80168c77
--- /dev/null
+++ b/plugins/discourse-calendar/test/javascripts/integration/components/zoom-page-test.gjs
@@ -0,0 +1,183 @@
+import { getOwner } from "@ember/owner";
+import { render } from "@ember/test-helpers";
+import { module, test } from "qunit";
+import sinon from "sinon";
+import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import LivestreamZoomPage from "../../discourse/components/livestream/zoom-page";
+
+const FALLBACK_SELECTOR = ".discourse-calendar-livestream-zoom-page__fallback";
+const FRAME_SELECTOR = ".discourse-calendar-livestream-zoom-page__frame";
+const CHAT_BUTTON_SELECTOR =
+ ".discourse-calendar-livestream-zoom-page__chat-button";
+const WAITING_SELECTOR = ".discourse-calendar-livestream-zoom-page__waiting";
+const ERROR_TEXT =
+ "You left the webinar or we are unable to load Zoom in this page.";
+
+// `returnedFromZoom` reads `window.location.search`, which a rendering test
+// cannot set. Stubbing the getter is the only way to reach the branch.
+function stubReturnedFromZoom(value) {
+ sinon.stub(LivestreamZoomPage.prototype, "returnedFromZoom").get(() => value);
+}
+
+// `loadZoom` is an `@action`, so the prototype holds an accessor rather than a
+// plain method and a bare `sinon.stub` would leave the real one in place — it
+// would reach for the network and the Zoom SDK.
+function stubLoadZoom(implementation) {
+ const fake = sinon.fake(implementation ?? (() => Promise.resolve()));
+
+ sinon.stub(LivestreamZoomPage.prototype, "loadZoom").get(function () {
+ return fake.bind(this);
+ });
+
+ return fake;
+}
+
+module("Integration | Component | LivestreamZoomPage", function (hooks) {
+ setupRenderingTest(hooks);
+
+ hooks.beforeEach(function () {
+ getOwner(this).lookup("service:site-settings").chat_enabled = true;
+
+ this.topic = {
+ id: 1,
+ slug: "test-topic",
+ chat_channel_id: 9,
+ postStream: {
+ posts: [
+ {
+ event: {
+ id: 2,
+ creator: { id: 1, username: "test-user" },
+ livestream_url: "https://us06web.zoom.us/j/123456789",
+ starts_at: moment().subtract(5, "minutes").toISOString(),
+ ends_at: moment().add(1, "hour").toISOString(),
+ },
+ },
+ ],
+ },
+ };
+ });
+
+ test("loads Zoom once into the frame", async function (assert) {
+ const loadZoom = stubLoadZoom();
+ stubReturnedFromZoom(false);
+
+ await render(
+ <template><LivestreamZoomPage @topic={{this.topic}} /></template>
+ );
+
+ assert.dom(FRAME_SELECTOR).exists();
+ assert.dom(FALLBACK_SELECTOR).doesNotExist("no error before a failure");
+ assert.strictEqual(loadZoom.callCount, 1, "sets the SDK up exactly once");
+ });
+
+ // Simulates navigating straight to /t/:slug/:id/zoom before the join window
+ // opens, bypassing the disabled button on the topic page.
+ test("does not load Zoom before the event timeframe", async function (assert) {
+ const loadZoom = stubLoadZoom();
+ stubReturnedFromZoom(false);
+ this.topic.postStream.posts[0].event.starts_at = moment()
+ .add(2, "hours")
+ .toISOString();
+
+ await render(
+ <template><LivestreamZoomPage @topic={{this.topic}} /></template>
+ );
+
+ assert.dom(FRAME_SELECTOR).doesNotExist();
+ assert
+ .dom(WAITING_SELECTOR)
+ .includesText("You can join the webinar closer to the event start time");
+ assert
+ .dom(`${WAITING_SELECTOR} a`)
+ .hasText("View topic for the event")
+ .hasAttribute("href", "/t/test-topic/1")
+ .hasClass("raw-link");
+ assert.strictEqual(loadZoom.callCount, 0, "never sets the SDK up");
+ });
+
+ test("does not load Zoom after the event timeframe", async function (assert) {
+ const loadZoom = stubLoadZoom();
+ stubReturnedFromZoom(false);
+ this.topic.postStream.posts[0].event.starts_at = moment()
+ .subtract(3, "hours")
+ .toISOString();
+ this.topic.postStream.posts[0].event.ends_at = moment()
+ .subtract(1, "hour")
+ .toISOString();
+
+ await render(
+ <template><LivestreamZoomPage @topic={{this.topic}} /></template>
+ );
+
+ assert.dom(FRAME_SELECTOR).doesNotExist();
+ assert.dom(WAITING_SELECTOR).exists();
+ assert.strictEqual(loadZoom.callCount, 0, "never sets the SDK up");
+ });
+
+ test("shows the fallback link when Zoom fails to load", async function (assert) {
+ stubLoadZoom(function () {
+ this.errorMessage = ERROR_TEXT;
+ return Promise.resolve();
+ });
+ stubReturnedFromZoom(false);
+
+ await render(
+ <template><LivestreamZoomPage @topic={{this.topic}} /></template>
+ );
+
+ assert.dom(FALLBACK_SELECTOR).exists();
+ assert.dom(`${FALLBACK_SELECTOR} p`).hasText(ERROR_TEXT);
+ assert
+ .dom(`${FALLBACK_SELECTOR} .btn-primary`)
+ .doesNotExist("no retry button unless the user came back from Zoom");
+ });
+
+ test("offers a retry when the user has returned from Zoom", async function (assert) {
+ stubReturnedFromZoom(true);
+
+ await render(
+ <template><LivestreamZoomPage @topic={{this.topic}} /></template>
+ );
+
+ assert
+ .dom(`${FALLBACK_SELECTOR} p`)
+ .hasText(ERROR_TEXT, "does not try to rejoin automatically");
+ assert.dom(`${FALLBACK_SELECTOR} .btn-primary`).hasText("Join Zoom");
+ });
+
+ test("offers to open the chat when the topic has a channel", async function (assert) {
+ stubLoadZoom();
+ stubReturnedFromZoom(false);
+
+ await render(
+ <template><LivestreamZoomPage @topic={{this.topic}} /></template>
+ );
+
+ assert.dom(CHAT_BUTTON_SELECTOR).exists();
+ });
+
+ test("hides the chat button when chat is disabled", async function (assert) {
+ stubLoadZoom();
+ stubReturnedFromZoom(false);
+ getOwner(this).lookup("service:site-settings").chat_enabled = false;
+
+ await render(
+ <template><LivestreamZoomPage @topic={{this.topic}} /></template>
+ );
+
+ assert.dom(CHAT_BUTTON_SELECTOR).doesNotExist();
+ });
+
+ test("hides the chat button when the topic has no channel", async function (assert) {
+ stubLoadZoom();
+ stubReturnedFromZoom(false);
+ this.topic.chat_channel_id = null;
+
+ await render(
+ <template><LivestreamZoomPage @topic={{this.topic}} /></template>
+ );
+
+ assert.dom(CHAT_BUTTON_SELECTOR).doesNotExist();
+ });
+});
diff --git a/plugins/discourse-calendar/test/javascripts/lib/livestream-utils-test.js b/plugins/discourse-calendar/test/javascripts/lib/livestream-utils-test.js
new file mode 100644
index 00000000000..35bae4a6ad1
--- /dev/null
+++ b/plugins/discourse-calendar/test/javascripts/lib/livestream-utils-test.js
@@ -0,0 +1,35 @@
+import { module, test } from "qunit";
+import { eventHasLivestream } from "discourse/plugins/discourse-calendar/discourse/lib/livestream-utils";
+
+module("Unit | Lib | livestream-utils", function () {
+ test("eventHasLivestream requires both the flag and a URL", function (assert) {
+ assert.true(
+ eventHasLivestream({
+ livestream: true,
+ livestreamUrl: "https://us06web.zoom.us/j/123456789",
+ }),
+ "flagged with a URL"
+ );
+
+ assert.false(
+ eventHasLivestream({ livestream: true, livestreamUrl: null }),
+ "flagged without a URL"
+ );
+ assert.false(
+ eventHasLivestream({ livestream: true, livestreamUrl: "" }),
+ "flagged with a blank URL"
+ );
+ assert.false(
+ eventHasLivestream({
+ livestream: false,
+ livestreamUrl: "https://us06web.zoom.us/j/123456789",
+ }),
+ "unflagged with a URL"
+ );
+ });
+
+ test("eventHasLivestream handles a missing event", function (assert) {
+ assert.false(eventHasLivestream(null));
+ assert.false(eventHasLivestream(undefined));
+ });
+});
diff --git a/plugins/discourse-calendar/test/javascripts/lib/raw-event-helper-test.js b/plugins/discourse-calendar/test/javascripts/lib/raw-event-helper-test.js
index 729853414db..d63817417eb 100644
--- a/plugins/discourse-calendar/test/javascripts/lib/raw-event-helper-test.js
+++ b/plugins/discourse-calendar/test/javascripts/lib/raw-event-helper-test.js
@@ -483,15 +483,79 @@ module("Unit | Lib | raw-event-helper", function () {
);
});
- test("isLivestreamUrl only accepts http(s) URLs", function (assert) {
- assert.true(isLivestreamUrl("https://example.com/live"), "accepts https");
- assert.true(isLivestreamUrl("http://example.com/live"), "accepts http");
- assert.true(isLivestreamUrl("HTTPS://EXAMPLE.COM"), "case-insensitive");
-
+ test("isLivestreamUrl only accepts http(s) URLs for major livestreaming platforms", function (assert) {
+ assert.false(
+ isLivestreamUrl("https://example.com/live"),
+ "does not accept arbitrary URLs"
+ );
+ assert.false(
+ isLivestreamUrl("http://example.com/live"),
+ "does not accept arbitrary URLs"
+ );
+ assert.false(
+ isLivestreamUrl("HTTPS://EXAMPLE.COM"),
+ "does not accept arbitrary URLs"
+ );
assert.false(isLivestreamUrl("www.example.com"), "rejects schemeless www");
assert.false(isLivestreamUrl("mailto:[email protected]"), "rejects mailto");
assert.false(isLivestreamUrl("Room 5"), "rejects plain text");
assert.false(isLivestreamUrl(null), "handles null");
assert.false(isLivestreamUrl(undefined), "handles undefined");
+
+ assert.true(
+ isLivestreamUrl("https://www.youtube.com/watch?v=dQw4w9WgXcQ"),
+ "accepts YouTube"
+ );
+ assert.true(
+ isLivestreamUrl("https://youtu.be/dQw4w9WgXcQ"),
+ "accepts YouTube short link"
+ );
+ assert.true(
+ isLivestreamUrl("https://www.twitch.tv/username"),
+ "accepts Twitch"
+ );
+ assert.true(
+ isLivestreamUrl("https://www.facebook.com/username/videos/123456789"),
+ "accepts Facebook"
+ );
+ assert.true(
+ isLivestreamUrl("https://www.tiktok.com/@username/video/123456789"),
+ "accepts TikTok"
+ );
+ assert.true(
+ isLivestreamUrl("https://www.instagram.com/tv/123456789"),
+ "accepts Instagram"
+ );
+ assert.true(isLivestreamUrl("https://zoom.us/j/123456789"), "accepts Zoom");
+ });
+
+ test("isLivestreamUrl accepts subdomains of livestreaming platforms", function (assert) {
+ assert.true(
+ isLivestreamUrl("https://us06web.zoom.us/j/123456789?pwd=secret"),
+ "accepts the vanity subdomain Zoom actually hands out"
+ );
+ assert.true(
+ isLivestreamUrl("https://gaming.youtube.com/watch?v=dQw4w9WgXcQ"),
+ "accepts a YouTube subdomain"
+ );
+ assert.true(
+ isLivestreamUrl("HTTPS://US06WEB.ZOOM.US/j/123456789"),
+ "is case-insensitive"
+ );
+ });
+
+ test("isLivestreamUrl rejects hosts that merely resemble a platform", function (assert) {
+ assert.false(
+ isLivestreamUrl("https://notzoom.us/j/123456789"),
+ "rejects a host ending in the platform name"
+ );
+ assert.false(
+ isLivestreamUrl("https://zoom.us.evil.com/j/123456789"),
+ "rejects a host starting with the platform name"
+ );
+ assert.false(
+ isLivestreamUrl("https://myyoutube.com/watch?v=1"),
+ "rejects a host prefixed with the platform name"
+ );
});
});
diff --git a/plugins/discourse-calendar/test/javascripts/unit/models/discourse-post-event-event-test.js b/plugins/discourse-calendar/test/javascripts/unit/models/discourse-post-event-event-test.js
index 0288d25a54a..459fcb30aed 100644
--- a/plugins/discourse-calendar/test/javascripts/unit/models/discourse-post-event-event-test.js
+++ b/plugins/discourse-calendar/test/javascripts/unit/models/discourse-post-event-event-test.js
@@ -1,5 +1,7 @@
import { module, test } from "qunit";
-import DiscoursePostEventEvent from "../../discourse/models/discourse-post-event-event";
+import DiscoursePostEventEvent, {
+ isWithinEventTimeframe,
+} from "../../discourse/models/discourse-post-event-event";
module("Unit | Model | DiscoursePostEventEvent", function () {
test("maps description fields from API response", function (assert) {
@@ -17,6 +19,94 @@ module("Unit | Model | DiscoursePostEventEvent", function () {
);
});
+ test("pastEventTimeframe allows a grace period after the end time", function (assert) {
+ const endedRecently = DiscoursePostEventEvent.create({
+ id: 1,
+ ends_at: moment().subtract(5, "minutes").toISOString(),
+ });
+ const endedLongAgo = DiscoursePostEventEvent.create({
+ id: 2,
+ ends_at: moment().subtract(15, "minutes").toISOString(),
+ });
+ const noEndTime = DiscoursePostEventEvent.create({ id: 3 });
+
+ assert.false(
+ endedRecently.pastEventTimeframe,
+ "still within the grace period"
+ );
+ assert.true(endedLongAgo.pastEventTimeframe, "past the grace period");
+ assert.false(
+ noEndTime.pastEventTimeframe,
+ "an event without an end time never ends"
+ );
+ });
+
+ test("currentlyWithinEventTimeframe opens 30 minutes before the start", function (assert) {
+ const notYetOpen = DiscoursePostEventEvent.create({
+ id: 1,
+ starts_at: moment().add(45, "minutes").toISOString(),
+ ends_at: moment().add(2, "hours").toISOString(),
+ });
+ const earlyAccess = DiscoursePostEventEvent.create({
+ id: 2,
+ starts_at: moment().add(15, "minutes").toISOString(),
+ ends_at: moment().add(2, "hours").toISOString(),
+ });
+
+ assert.false(notYetOpen.currentlyWithinEventTimeframe, "45 minutes out");
+ assert.true(earlyAccess.currentlyWithinEventTimeframe, "15 minutes out");
+ });
+
+ test("currentlyWithinEventTimeframe closes 10 minutes after the end", function (assert) {
+ const inProgress = DiscoursePostEventEvent.create({
+ id: 1,
+ starts_at: moment().subtract(1, "hour").toISOString(),
+ ends_at: moment().add(1, "hour").toISOString(),
+ });
+ const withinGrace = DiscoursePostEventEvent.create({
+ id: 2,
+ starts_at: moment().subtract(2, "hours").toISOString(),
+ ends_at: moment().subtract(5, "minutes").toISOString(),
+ });
+ const pastGrace = DiscoursePostEventEvent.create({
+ id: 3,
+ starts_at: moment().subtract(2, "hours").toISOString(),
+ ends_at: moment().subtract(15, "minutes").toISOString(),
+ });
+
+ assert.true(inProgress.currentlyWithinEventTimeframe, "in progress");
+ assert.true(withinGrace.currentlyWithinEventTimeframe, "within grace");
+ assert.false(pastGrace.currentlyWithinEventTimeframe, "past grace");
+ });
+
+ test("updateFromEvent copies the livestream fields", function (assert) {
+ const event = DiscoursePostEventEvent.create({ id: 1 });
+ const updated = DiscoursePostEventEvent.create({
+ id: 1,
+ location: "https://us06web.zoom.us/j/123456789",
+ livestream: true,
+ livestream_chat_channel_id: 9,
+ is_zoom_livestream: true,
+ });
+
+ event.updateFromEvent(updated);
+
+ assert.true(event.livestream);
+ assert.strictEqual(
+ event.livestreamUrl,
+ "https://us06web.zoom.us/j/123456789"
+ );
+ assert.strictEqual(
+ event.livestreamChatChannelId,
+ 9,
+ "keeps the chat channel the Zoom entry depends on"
+ );
+ assert.true(
+ event.isZoomLivestream,
+ "keeps the flag that decides whether the Zoom entry renders"
+ );
+ });
+
test("updateFromEvent copies description fields", function (assert) {
const event = DiscoursePostEventEvent.create({ id: 1 });
const updated = DiscoursePostEventEvent.create({
@@ -34,4 +124,62 @@ module("Unit | Model | DiscoursePostEventEvent", function () {
'Visit <a href="https://example.com">https://example.com</a>'
);
});
+
+ test("isWithinEventTimeframe returns true for all-day events on the same day", function (assert) {
+ const startsAt = moment().startOf("day").toISOString();
+ const allDayEvent = DiscoursePostEventEvent.create({
+ id: 1,
+ starts_at: startsAt,
+ ends_at: null,
+ all_day: true,
+ });
+
+ assert.true(
+ isWithinEventTimeframe(
+ allDayEvent.allDay,
+ allDayEvent.startsAt,
+ allDayEvent.endsAt
+ ),
+ "returns true for all-day events on the same day"
+ );
+ });
+
+ test("isWithinEventTimeframe returns false for all-day events on a different day", function (assert) {
+ const startsAt = moment().add(1, "day").toISOString();
+ const allDayEvent = DiscoursePostEventEvent.create({
+ id: 2,
+ starts_at: startsAt,
+ ends_at: null,
+ all_day: true,
+ });
+
+ assert.false(
+ isWithinEventTimeframe(
+ allDayEvent.allDay,
+ allDayEvent.startsAt,
+ allDayEvent.endsAt
+ ),
+ "returns false for all-day events on a different day"
+ );
+ });
+
+ test("isWithinEventTimeframe returns true for non-all-day events within the timeframe", function (assert) {
+ const startsAt = moment().subtract(15, "minutes").toISOString();
+ const endsAt = moment().add(15, "minutes").toISOString();
+ const nonAllDayEvent = DiscoursePostEventEvent.create({
+ id: 3,
+ starts_at: startsAt,
+ ends_at: endsAt,
+ all_day: false,
+ });
+
+ assert.true(
+ isWithinEventTimeframe(
+ nonAllDayEvent.allDay,
+ nonAllDayEvent.startsAt,
+ nonAllDayEvent.endsAt
+ ),
+ "returns true for non-all-day events within the timeframe"
+ );
+ });
});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a2717cf6d2f..db103b624ae 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -294,6 +294,9 @@ importers:
'@lezer/lr':
specifier: ^1.4.8
version: 1.4.10
+ '@zoom/meetingsdk':
+ specifier: 6.2.0
ace-builds:
specifier: ^1.44.0
version: 1.44.0
@@ -408,6 +411,21 @@ importers:
prosemirror-view:
specifier: ^1.41.8
version: 1.41.8
+ react:
+ specifier: 18.2.0
+ version: 18.2.0
+ react-dom:
+ specifier: 18.2.0
+ version: 18.2.0([email protected])
+ react-redux:
+ specifier: 8.1.2
+ redux:
+ specifier: 4.2.1
+ version: 4.2.1
+ redux-thunk:
+ specifier: 2.4.2
+ version: 2.4.2([email protected])
rete:
specifier: ^2.0.6
version: 2.0.6
@@ -558,7 +576,7 @@ importers:
version: 2.1.1(patch_hash=6f462c5d8fcc3ebcc27fc038b7be66b9337f0c848ad18e37a2101cb62b29ede5)(@babel/[email protected])
ember-cli:
specifier: ~7.0.1
ember-cli-deprecation-workflow:
specifier: ^4.0.1
version: 4.0.1(@babel/[email protected])
@@ -615,7 +633,7 @@ importers:
version: 22.0.0
testem:
specifier: ^3.20.1
typescript:
specifier: ^5.9.3
version: 5.9.3
@@ -2897,6 +2915,11 @@ packages:
resolution: {integrity: sha512-00UxlRaIUvYm4R4W9WYkN8/J+kV8fmOQ7okeH6YFtGWFMt3odD45tpG5yA5wnL7HE6lLgjaTW5n14ju2hl2NNA==}
deprecated: This is a stub types definition. glob provides its own type definitions, so you do not need this installed.
+ '@types/[email protected]':
+ resolution: {integrity: sha512-PQTyIulDkIDro8P+IHbKCsw7U2xxBYflVzW/FgWdCAePD9xGSidgA76/GeJ6lBKoblyhf9pBY763gbrN+1dI8g==}
+ peerDependencies:
+ '@types/react': '*'
+
resolution: {integrity: sha512-SeyVJXlCZpEki5F0ghuYe+L+PprQta6nRZqhONt9F13dWBtR/ftoaIbdRQ7cis7womE+X2LKhsDdDtkkDhJS6g==}
@@ -2948,6 +2971,9 @@ packages:
resolution: {integrity: sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA==}
+
resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
@@ -3104,6 +3130,16 @@ packages:
resolution: {integrity: sha512-A9gOqLdi6cV4ibazAjcQufGj0B1y/vDqYrcuP6d/6x8P27gRS8643Dj9o1dEKtB6O7fwxb2FgBmJS2mX7gpvdw==}
engines: {node: '>=14.6'}
+ resolution: {integrity: sha512-QVoZKZMtt0xMuwQRyEQrh4wVWjsMSrqko9wbFS21E6eoTSGjq/Q2iSrUtkYjwPes1skXXmItuxW2ZpLS6zschg==}
+ peerDependencies:
+ lodash: ^4.18.1
+ react: 18.2.0
+ react-dom: 18.2.0
+ react-redux: 8.1.2
+ redux: 4.2.1
+ redux-thunk: 2.4.2
+
resolution: {integrity: sha512-SlFk3QSqeuvmN/anaIteUkB6ipBHoG1jq5gfQZU2kqvbkDW3Iab7SNufj4io4e8StvuIshD+loJnsQgTEvq6dA==}
@@ -5180,6 +5216,9 @@ packages:
resolution: {integrity: sha512-Xwwo44whKBVCYoliBQwaPvtd/2tYFkRQtXDWj1nackaV2JPXx3L0+Jvd8/qCJ2p+ML0/XVkJ2q+Mr+UVdpJK5w==}
engines: {node: '>=12.0.0'}
+ resolution: {integrity: sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==}
+
resolution: {integrity: sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA==}
engines: {node: '>=0.10.0'}
@@ -5965,6 +6004,10 @@ packages:
resolution: {integrity: sha512-CdaO738xRapbKIMVn2m4F6KTj4j7ooJ8POVnebSgKo3KBz5axNXRAL7ZdRjIV6NOr2Uf4vjtRkxrFETOioCqSA==}
engines: {node: '>= 12.0.0'}
+ resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
+ hasBin: true
+
resolution: {integrity: sha512-7fm3l3NAF9WfN6W3JOmf5drwpVqX78JtoGJ3A6W0a6ZnldM41w2fV5D490psKFTpMds8TJse/eHLFFsNHHjHgg==}
@@ -6919,6 +6962,42 @@ packages:
resolution: {integrity: sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==}
engines: {node: '>= 0.10'}
+ resolution: {integrity: sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==}
+ peerDependencies:
+ react: ^18.2.0
+
+ resolution: {integrity: sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==}
+
+ resolution: {integrity: sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==}
+
+ resolution: {integrity: sha512-xJKYI189VwfsFc4CJvHqHlDrzyFTY/3vZACbE+rr/zQ34Xx1wQfB4OTOSeOSNrF6BDVe8OOdxIrAnMGXA3ggfw==}
+ peerDependencies:
+ '@types/react': ^16.8 || ^17.0 || ^18.0
+ '@types/react-dom': ^16.8 || ^17.0 || ^18.0
+ react: ^16.8 || ^17.0 || ^18.0
+ react-dom: ^16.8 || ^17.0 || ^18.0
+ react-native: '>=0.59'
+ redux: ^4 || ^5.0.0-beta.0
+ peerDependenciesMeta:
+ '@types/react':
+ optional: true
+ '@types/react-dom':
+ optional: true
+ react-dom:
+ optional: true
+ react-native:
+ optional: true
+ redux:
+ optional: true
+
+ resolution: {integrity: sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ==}
+ engines: {node: '>=0.10.0'}
+
resolution: {integrity: sha512-yILWifhaSEEytfXI76kB9xEEiG1AiozaCJZ83A87ytjRiN+jVibXjedjCRNjoZviinhG+4UkalO3mWTd8u5O0Q==}
engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0}
@@ -6948,6 +7027,14 @@ packages:
resolution: {integrity: sha512-8eEWsNCkV2rvwKLS1Cvp5agNjMhwRe2um+y32B2+3LqOzg4C9BBPs6vzAfV16Ivb8B9HPNKIqd8OrdBws8kNlQ==}
+ resolution: {integrity: sha512-+P3TjtnP0k/FEjcBL5FZpoovtvrTNT/UXd4/sluaSyrURlSlhLSzEdfsTBW7WsKB6yPvgd7q/iZPICFjW4o57Q==}
+ peerDependencies:
+ redux: ^4
+
+ resolution: {integrity: sha512-LAUYz4lc+Do8/g7aeRa8JkyDErK6ekstQaqWQrNRW//MY1TvCEpMtpTWvlQ+FPbWCx+Xixu/6SHt5N0HR+SB4w==}
+
resolution: {integrity: sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==}
engines: {node: '>= 0.4'}
@@ -7216,6 +7303,9 @@ packages:
resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==}
engines: {node: '>=v12.22.7'}
+ resolution: {integrity: sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==}
+
resolution: {integrity: sha512-SHiNtMOUGWBQJwzISiVYKu82GiV4QYGePp3odlY1tuKO7gPtphAT5R/py0fA6xtbgLL/RvtJZnU9b8s0F1q0Xg==}
engines: {node: '>= 8.9.0'}
@@ -7958,6 +8048,11 @@ packages:
resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}
+ resolution: {integrity: sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==}
+ peerDependencies:
+ react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0
+
resolution: {integrity: sha512-m/7/FSqjJNAzF2La448c/aEom0gJy7HY7Y509h6l0ePvEkFictAGptwWaj1msWJ38JbfEDOUoE8kqFee9EHKdA==}
@@ -10773,6 +10868,10 @@ snapshots:
dependencies:
glob: 13.0.6
+ '@types/[email protected]':
+ dependencies:
+ hoist-non-react-statics: 3.3.2
+
dependencies:
'@types/sizzle': 2.3.10
@@ -10819,6 +10918,8 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]': {}
+
dependencies:
'@types/node': 25.9.1
@@ -11052,6 +11153,15 @@ snapshots:
'@xmldom/[email protected]': {}
+ dependencies:
+ lodash: 4.18.1
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
+ redux: 4.2.1
+ redux-thunk: 2.4.2([email protected])
+
dependencies:
focusable-selectors: 0.8.4
@@ -12018,13 +12128,15 @@ snapshots:
ora: 3.4.0
through2: 3.0.2
optionalDependencies:
'@babel/core': 7.29.7
ejs: 3.1.10
handlebars: 4.7.9
lodash: 4.18.1
mustache: 4.2.0
+ react: 18.2.0
+ react-dom: 18.2.0([email protected])
underscore: 1.13.8
@@ -12465,7 +12577,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@ember-tooling/blueprint-blueprint': 0.3.0
'@ember-tooling/blueprint-model': 0.6.3
@@ -12544,7 +12656,7 @@ snapshots:
silent-error: 1.1.1
sort-package-json: 3.6.1
symlink-or-copy: 1.3.1
tiny-lr: 2.0.0
tree-sync: 2.1.0
walk-sync: 4.0.2
@@ -13819,6 +13931,10 @@ snapshots:
+ dependencies:
+ react-is: 16.13.1
+
dependencies:
parse-passwd: 1.0.0
@@ -14589,6 +14705,10 @@ snapshots:
safe-stable-stringify: 2.5.0
triple-beam: 1.4.1
+ dependencies:
+ js-tokens: 4.0.0
+
dependencies:
tslib: 2.8.1
@@ -15560,6 +15680,33 @@ snapshots:
iconv-lite: 0.7.2
unpipe: 1.0.0
+ dependencies:
+ loose-envify: 1.4.0
+ react: 18.2.0
+ scheduler: 0.23.2
+
+
+
+ dependencies:
+ '@babel/runtime': 7.29.7
+ '@types/hoist-non-react-statics': 3.3.7
+ '@types/use-sync-external-store': 0.0.3
+ hoist-non-react-statics: 3.3.2
+ react: 18.2.0
+ react-is: 18.3.1
+ use-sync-external-store: 1.6.0([email protected])
+ optionalDependencies:
+ react-dom: 18.2.0([email protected])
+ redux: 4.2.1
+
+ dependencies:
+ loose-envify: 1.4.0
+
@@ -15603,6 +15750,14 @@ snapshots:
dependencies:
esprima: 3.0.0
+ dependencies:
+ redux: 4.2.1
+
+ dependencies:
+ '@babel/runtime': 7.29.7
+
dependencies:
call-bind: 1.0.9
@@ -15914,6 +16069,10 @@ snapshots:
dependencies:
xmlchars: 2.2.0
+ dependencies:
+ loose-envify: 1.4.0
+
dependencies:
'@types/json-schema': 7.0.15
@@ -16538,7 +16697,7 @@ snapshots:
commander: 2.20.3
source-map-support: 0.5.21
dependencies:
'@xmldom/xmldom': 0.9.10
backbone: 1.6.1
@@ -16546,7 +16705,7 @@ snapshots:
chokidar: 5.0.0
commander: 14.0.3
compression: 1.8.1
execa: 9.6.1
express: 5.2.1
glob: 13.0.6
@@ -16892,6 +17051,10 @@ snapshots:
dependencies:
punycode: 2.3.1
+ dependencies:
+ react: 18.2.0
+
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 9fb102b4d5d..f5cb7103d59 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -3,6 +3,7 @@ strictDepBuilds: true
onlyBuiltDependencies:
- lefthook
ignoredBuiltDependencies:
+- "@zoom/meetingsdk"
- core-js
- rete
packages:
diff --git a/themes/horizon/common/common.scss b/themes/horizon/common/common.scss
index 04655206370..f9467296a05 100644
--- a/themes/horizon/common/common.scss
+++ b/themes/horizon/common/common.scss
@@ -6,6 +6,7 @@
@import "composer";
@import "composer-peek-mode";
@import "experimental-screen";
+@import "discourse-calendar";
@import "header";
@import "hiddenstuff";
@import "login";
diff --git a/themes/horizon/scss/discourse-calendar.scss b/themes/horizon/scss/discourse-calendar.scss
new file mode 100644
index 00000000000..a74a52f5340
--- /dev/null
+++ b/themes/horizon/scss/discourse-calendar.scss
@@ -0,0 +1,5 @@
+.discourse-calendar-livestream-zoom-full {
+ .experimental-screen {
+ display: none;
+ }
+}