A platform for community discussion. Free, open, simple.
UX: Always open zoom livestreams on dedicated route (#42694)
Kriscae1f1d1f0d6
diff --git a/plugins/discourse-events/app/controllers/discourse_calendar/livestream_controller.rb b/plugins/discourse-events/app/controllers/discourse_calendar/livestream_controller.rbindex bfa9a4bf3ec..7c920a1e721 100644--- a/plugins/discourse-events/app/controllers/discourse_calendar/livestream_controller.rb+++ b/plugins/discourse-events/app/controllers/discourse_calendar/livestream_controller.rb@@ -7,8 +7,9 @@ module DiscourseCalendarskip_before_action :check_xhr, only: [:zoom_frame]- # Kept in step with the version the app itself loads the SDK at, in- # `lib/load-zoom-meeting-sdk.js`.+ # The frame is the only thing that loads the SDK, so this is the one place+ # the version is stated. Bump it to adopt a newer release.+ # https://developers.zoom.us/docs/meeting-sdk/web/get-started/ZOOM_SDK_VERSION = "6.2.0"ZOOM_SDK_CDN = "https://source.zoom.us"diff --git a/plugins/discourse-events/app/models/discourse_post_event/event.rb b/plugins/discourse-events/app/models/discourse_post_event/event.rbindex 9ba87ae08b4..c21827bb968 100644--- a/plugins/discourse-events/app/models/discourse_post_event/event.rb+++ b/plugins/discourse-events/app/models/discourse_post_event/event.rb@@ -174,7 +174,7 @@ module DiscoursePostEventif all_dayopens_at = starts_at.beginning_of_day- closes_at = starts_at.end_of_day+ closes_at = (ends_at || starts_at).end_of_dayreturn opens_at <= now && now <= closes_atenddiff --git a/plugins/discourse-events/app/views/discourse_calendar/livestream/zoom_frame.html.erb b/plugins/discourse-events/app/views/discourse_calendar/livestream/zoom_frame.html.erbindex db50024b726..03329fe0818 100644--- a/plugins/discourse-events/app/views/discourse_calendar/livestream/zoom_frame.html.erb+++ b/plugins/discourse-events/app/views/discourse_calendar/livestream/zoom_frame.html.erb@@ -185,6 +185,7 @@leaveUrl: config.leaveUrl,patchJsMedia: true,disableCallOut: true,+ isSupportChat: false,success: resolve,error: reject,});diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/livestream.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/livestream.gjsindex 0cabd3c4b3b..1c4f667615d 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/livestream.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/discourse-post-event/livestream.gjs@@ -82,10 +82,7 @@ export default class Livestream extends Component {{{#if this.show}}<section class="event__section event-livestream">{{#if this.isZoomLivestream}}- <LivestreamZoomEntry- @event={{@event}}- @onJoined={{this.preventCloak}}- />+ <LivestreamZoomEntry @event={{@event}} />{{else if this.hasLivestreamOnebox}}{{#if this.videoAttributes}}<this.lazyVideodiff --git a/plugins/discourse-events/assets/javascripts/discourse/components/livestream/responsive-livestream-chat-icon.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/livestream/responsive-livestream-chat-icon.gjsindex 95b1442a799..d1eedd06888 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/livestream/responsive-livestream-chat-icon.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/livestream/responsive-livestream-chat-icon.gjs@@ -6,9 +6,7 @@ export default class ResponsiveLivestreamChatIcon extends Component {@service embeddableChat;get shouldShow() {- return (- this.embeddableChat.isMobileViewport && this.embeddableChat.chatChannelId- );+ return this.embeddableChat.showLivestreamHeaderChatIcon;}<template>diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/livestream/zoom-entry.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/livestream/zoom-entry.gjsindex 0c323cd356f..cb35209ef33 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/livestream/zoom-entry.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/livestream/zoom-entry.gjs@@ -1,37 +1,17 @@import Component from "@glimmer/component";-import { array } from "@ember/helper";+import { on } from "@ember/modifier";import { action } from "@ember/object";import { getOwner } from "@ember/owner";import { service } from "@ember/service";-import { trustHTML } from "@ember/template";-import { isEmpty } from "@ember/utils";-import { bind } from "discourse/lib/decorators";-import { iconHTML } from "discourse/lib/icon-library";+import { wantsNewWindow } from "discourse/lib/intercept-click";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 router;@service siteSettings;- session = new ZoomMeetingSession(getOwner(this), {- topicId: this.topic.id,- canJoin: () => this.canJoinNow,- onBeforeJoinAttempt: this.markAsGoing,- onJoined: () => this.args.onJoined?.(),- });-- willDestroy() {- super.willDestroy(...arguments);- this.session.teardown();- }-get topic() {return this.args.event.post.topic;}@@ -52,153 +32,56 @@ export default class LivestreamZoomEntry extends Component {);}- get isDesktop() {- return this.capabilities.viewport.lg;- }-- get showFallbackLink() {- return !isEmpty(this.session.errorMessage);- }-- get showAudioHint() {- return this.session.isJoined && !this.session.hasJoinedAudio;- }-- get joinAudioHint() {- return trustHTML(- i18n("discourse_calendar.livestream.zoom.join_audio_hint", {- icon: iconHTML("zoom-join-audio"),- })- );- }-get joinDisabled() {- return (- this.session.isJoining ||- this.session.isWaitingForStart ||- !this.canJoinNow- );+ return !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;+ // A `disabled` anchor is still followable, and the meeting has nothing to+ // show an anonymous user, so the button only carries a link once it leads+ // somewhere: everything else is left to the click.+ get joinHref() {+ if (!this.canJoinNow || !this.currentUser) {+ return null;}- 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);- }+ return this.router.urlFor("topic-zoom", this.topic.slug, this.topic.id);}@action- joinZoom() {+ joinZoom(event) {if (!this.currentUser) {- return getOwner(this)- .lookup("route:application")- .send("showCreateAccount");+ event.preventDefault();+ getOwner(this).lookup("route:application").send("showCreateAccount");+ return;+ }++ if (wantsNewWindow(event)) {+ return;}- this.session.join();+ event.preventDefault();+ this.router.transitionTo("topic-zoom", this.topic.slug, this.topic.id);}<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>-- {{#if this.showAudioHint}}- <p class="discourse-calendar-livestream-zoom-entry__audio-hint">- {{this.joinAudioHint}}+ <div class="discourse-calendar-livestream-zoom-entry__actions">+ <DButton+ @href={{this.joinHref}}+ @label="discourse_calendar.livestream.zoom.join"+ @icon="video"+ class="discourse-calendar-livestream-zoom-entry__join btn-primary"+ @disabled={{this.joinDisabled}}+ {{on "click" this.joinZoom}}+ />++ {{#unless this.canJoinNow}}+ <p class="discourse-calendar-livestream-zoom-entry__waiting">+ {{i18n "discourse_calendar.livestream.zoom.too_early"}}</p>- {{/if}}- {{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}}+ {{/unless}}+ </div></div>{{/if}}</template>diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/livestream/zoom-page.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/livestream/zoom-page.gjsindex ddd609f846f..6dfc025873b 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/livestream/zoom-page.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/livestream/zoom-page.gjs@@ -5,6 +5,7 @@ import { action } from "@ember/object";import { service } from "@ember/service";import { modifier } from "ember-modifier";import bodyClass from "discourse/helpers/body-class";+import { popupAjaxError } from "discourse/lib/ajax-error";import { bind } from "discourse/lib/decorators";import getURL from "discourse/lib/get-url";import { wantsNewWindow } from "discourse/lib/intercept-click";@@ -22,7 +23,9 @@ import EmbeddableChatChannel from "./embeddable-chat-channel";const FRAME_MESSAGE_SOURCE = "discourse-zoom-frame";export default class LivestreamZoomPage extends Component {+ @service appEvents;@service currentUser;+ @service discoursePostEventApi;@service embeddableChat;@service siteSettings;@@ -38,6 +41,30 @@ export default class LivestreamZoomPage extends Component {return () => window.removeEventListener("message", this.onFrameMessage);});+ confirmAttendance = modifier(() => {+ if (this.#attendanceConfirmed) {+ return;+ }++ this.#attendanceConfirmed = true;+ this.markAsGoing();+ });+ #attendanceConfirmed = false;++ // Attendance is what follows a user into the livestream chat channel, so+ // someone who reaches the meeting without ever answering the RSVP would sit+ // in front of a read-only chat beside it. Anyone who has already made a+ // choice, including an explicit "not going", keeps it.+ //+ // This page is the only way into the meeting, and it is addressable in its+ // own right, so it is asked for here rather than beside the button that+ // usually leads here.+ //+ // Asked once per visit: the body reads tracked state, so it would otherwise+ // run again whenever the post is invalidated, and `event` is rebuilt from the+ // raw payload on each access, so a later run cannot see the invitee the first+ // one wrote+get post() {return this.args.topic?.postStream?.posts?.[0];}@@ -120,6 +147,37 @@ export default class LivestreamZoomPage extends Component {}}+ @bind+ async markAsGoing() {+ const event = this.event;++ if (!this.canJoinNow || !event?.canUpdateAttendance) {+ return;+ }++ if (event.watchingInvitee?.status) {+ return;+ }++ const payload = { status: "going" };+ const appEventData = { status: payload.status, postId: event.id };++ try {+ 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);+ }+ } catch (e) {+ // Chat beside the meeting stays read-only without this, and its own RSVP+ // prompt is the way back from that, so the failure is worth saying out+ // loud rather than leaving the user to find it there.+ popupAjaxError(e);+ }+ }+@actionretryZoom() {this.errorMessage = null;@@ -144,6 +202,7 @@ export default class LivestreamZoomPage extends Component {(if this.canRenderChat "--with-chat")}}{{zoomPageViewportFit}}+ {{this.confirmAttendance}}>{{#if this.canJoinNow}}{{#if this.errorMessage}}diff --git a/plugins/discourse-events/assets/javascripts/discourse/lib/fetch-zoom-join-payload.js b/plugins/discourse-events/assets/javascripts/discourse/lib/fetch-zoom-join-payload.jsdeleted file mode 100644index 4d248ab82ed..00000000000--- a/plugins/discourse-events/assets/javascripts/discourse/lib/fetch-zoom-join-payload.js+++ /dev/null@@ -1,14 +0,0 @@-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-events/assets/javascripts/discourse/lib/load-zoom-meeting-sdk.js b/plugins/discourse-events/assets/javascripts/discourse/lib/load-zoom-meeting-sdk.jsdeleted file mode 100644index ca43b70b30f..00000000000--- a/plugins/discourse-events/assets/javascripts/discourse/lib/load-zoom-meeting-sdk.js+++ /dev/null@@ -1,28 +0,0 @@-import loadScript from "discourse/lib/load-script";--// The Zoom Meeting SDK is hotlinked from Zoom's CDN rather than bundled, so it-// stays out of Discourse's build and Zoom serves matching wasm/AV assets from-// the same origin. Bump this to adopt a newer SDK release.-// https://developers.zoom.us/docs/meeting-sdk/web/get-started/-//-// The page the meeting is embedded in loads the SDK for itself and pins the-// same version in `LivestreamController::ZOOM_SDK_VERSION`, which a bump here-// has to carry to.-const ZOOM_SDK_VERSION = "6.2.0";-const CDN = "https://source.zoom.us";--// React must precede ReactDOM, and Redux precede its thunk.-const DEPENDENCIES = ["react", "react-dom", "redux", "redux-thunk", "lodash"];--async function loadDependencies() {- for (const dep of DEPENDENCIES) {- await loadScript(`${CDN}/${ZOOM_SDK_VERSION}/lib/vendor/${dep}.min.js`);- }-}--// Component View (`ZoomMtgEmbedded`) - embeds Zoom inside a container element.-export async function loadZoomMeetingSdkEmbedded() {- await loadDependencies();- await loadScript(`${CDN}/zoom-meeting-embedded-${ZOOM_SDK_VERSION}.min.js`);- return window.ZoomMtgEmbedded;-}diff --git a/plugins/discourse-events/assets/javascripts/discourse/lib/zoom-component-view-dom.js b/plugins/discourse-events/assets/javascripts/discourse/lib/zoom-component-view-dom.jsdeleted file mode 100644index 6b7445131d2..00000000000--- a/plugins/discourse-events/assets/javascripts/discourse/lib/zoom-component-view-dom.js+++ /dev/null@@ -1,114 +0,0 @@-// 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) {- // Zoom is configured with this size once, at init, and only ever corrects it- // if a later sync gets through. Falling back to the minimum because the root- // happened to measure zero locks the component view into a 240px video for- // the rest of the session, so measure the container it sits in instead.- const measuredWidth =- root?.getBoundingClientRect().width ||- root?.parentElement?.getBoundingClientRect().width ||- 0;-- const width = Math.max(- MIN_VIDEO_WIDTH,- Math.min(MAX_VIDEO_WIDTH, Math.floor(measuredWidth))- );-- 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-events/assets/javascripts/discourse/lib/zoom-error.js b/plugins/discourse-events/assets/javascripts/discourse/lib/zoom-error.jsdeleted file mode 100644index d54e6de56f0..00000000000--- a/plugins/discourse-events/assets/javascripts/discourse/lib/zoom-error.js+++ /dev/null@@ -1,31 +0,0 @@-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-events/assets/javascripts/discourse/lib/zoom-meeting-session.js b/plugins/discourse-events/assets/javascripts/discourse/lib/zoom-meeting-session.jsdeleted file mode 100644index f6e47b4bbe5..00000000000--- a/plugins/discourse-events/assets/javascripts/discourse/lib/zoom-meeting-session.js+++ /dev/null@@ -1,288 +0,0 @@-import { tracked } from "@glimmer/tracking";-import { setOwner } from "@ember/owner";-import { isEmpty } from "@ember/utils";-import { bind } from "discourse/lib/decorators";-import { i18n } from "discourse-i18n";-import fetchZoomJoinPayload from "./fetch-zoom-join-payload";-import { loadZoomMeetingSdkEmbedded } from "./load-zoom-meeting-sdk";-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 hasJoinedAudio = 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, onJoined }) {- setOwner(this, owner);- this.topicId = topicId;- this.canJoin = canJoin;- this.onBeforeJoinAttempt = onBeforeJoinAttempt;- this.onJoined = onJoined;-- document.addEventListener("visibilitychange", this.onVisibilityChange);- }-- teardown() {- this.#tornDown = true;- clearInterval(this.retryTimer);- cancelAnimationFrame(this.layoutFrame);- cancelAnimationFrame(this.videoSyncFrame);- document.removeEventListener("visibilitychange", this.onVisibilityChange);- 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.onJoined?.();- 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.scheduleViewSync();- }- }-- // Both the frame callbacks below and the resize observer the modifier- // attaches are suspended while the document is hidden, so a join that lands- // in a background tab leaves Zoom rendering at whatever size it was last- // told about. `onVisibilityChange` picks the work back up on return.- scheduleViewSync() {- if (document.hidden) {- return;- }-- cancelAnimationFrame(this.layoutFrame);- cancelAnimationFrame(this.videoSyncFrame);-- this.layoutFrame = window.requestAnimationFrame(() =>- syncZoomLayout(this.element)- );- this.videoSyncFrame = window.requestAnimationFrame(() =>- this.syncVideoSize()- );- }-- @bind- onVisibilityChange() {- if (document.hidden || this.#tornDown || !this.zoomClient) {- return;- }-- this.scheduleViewSync();- }-- 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.zoomClient.on("user-updated", () => this.syncAudioState());-- 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,- });-- this.syncAudioState();- }-- // Joining the meeting does not connect audio: `audio` stays "" until the user- // picks computer or phone audio in Zoom's own controls. `user-updated` carries- // only the properties that changed, so the value is re-read from the client- // rather than taken from the payload.- syncAudioState() {- this.hasJoinedAudio = !isEmpty(this.zoomClient?.getCurrentUser?.()?.audio);- }-- syncVideoSize() {- if (!this.zoomClient) {- return;- }-- this.zoomClient.updateVideoOptions({- viewSizes: {- default: computeZoomViewSize(this.element),- },- });- }-- leaveZoom() {- this.isJoined = false;- this.hasJoinedAudio = 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-events/assets/javascripts/discourse/models/discourse-post-event-event.js b/plugins/discourse-events/assets/javascripts/discourse/models/discourse-post-event-event.jsindex e7cebe3782d..16900493ca9 100644--- a/plugins/discourse-events/assets/javascripts/discourse/models/discourse-post-event-event.js+++ b/plugins/discourse-events/assets/javascripts/discourse/models/discourse-post-event-event.js@@ -20,17 +20,36 @@ const DEFAULT_REMINDER = {const EARLY_ACCESS_MINUTES = 30;const GRACE_PERIOD_MINUTES = 10;+export function isPastEventTimeframe(endsAt) {+ if (!endsAt) {+ return false;+ }++ return moment().isAfter(moment(endsAt).add(GRACE_PERIOD_MINUTES, "minutes"));+}+export function isWithinEventTimeframe(allDay, startsAt, endsAt) {+ if (!startsAt) {+ return false;+ }+const now = moment();if (allDay) {const opensAt = moment(startsAt).startOf("day");- const closesAt = moment(startsAt).endOf("day");+ const closesAt = moment(endsAt || startsAt).endOf("day");return now.isBetween(opensAt, closesAt);}const opensAt = moment(startsAt).subtract(EARLY_ACCESS_MINUTES, "minutes");++ // An event without an end time never closes, which is what the server does+ // when it issues a signature for one.+ if (!endsAt) {+ return now.isAfter(opensAt);+ }+const closesAt = moment(endsAt).add(GRACE_PERIOD_MINUTES, "minutes");return now.isBetween(opensAt, closesAt);@@ -191,16 +210,8 @@ export default class DiscoursePostEventEvent {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")- );+ return isPastEventTimeframe(this.endsAt);}updateFromEvent(event) {diff --git a/plugins/discourse-events/assets/javascripts/discourse/modifiers/zoom-component-view-layout.js b/plugins/discourse-events/assets/javascripts/discourse/modifiers/zoom-component-view-layout.jsdeleted file mode 100644index f380c396030..00000000000--- a/plugins/discourse-events/assets/javascripts/discourse/modifiers/zoom-component-view-layout.js+++ /dev/null@@ -1,60 +0,0 @@-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-events/assets/javascripts/discourse/routes/topic-zoom.js b/plugins/discourse-events/assets/javascripts/discourse/routes/topic-zoom.jsindex 3d45df9f909..493b5506d3c 100644--- a/plugins/discourse-events/assets/javascripts/discourse/routes/topic-zoom.js+++ b/plugins/discourse-events/assets/javascripts/discourse/routes/topic-zoom.js@@ -9,6 +9,11 @@ export default class TopicZoomRoute extends DiscourseRoute {this.embeddableChat.closeChatVisibility();}+ deactivate() {+ super.deactivate(...arguments);+ this.controllerFor("topic").set("model", null);+ }+async model(params) {const topic = this.store.createRecord("topic", { id: params.topic_id });diff --git a/plugins/discourse-events/assets/javascripts/discourse/services/embeddable-chat.gjs b/plugins/discourse-events/assets/javascripts/discourse/services/embeddable-chat.gjsindex 37e92bf4f53..55fc27ea737 100644--- a/plugins/discourse-events/assets/javascripts/discourse/services/embeddable-chat.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/services/embeddable-chat.gjs@@ -3,6 +3,7 @@ import { action } from "@ember/object";import { getOwner } from "@ember/owner";import Service, { service } from "@ember/service";import optionalService from "discourse/lib/optional-service";+import { isPastEventTimeframe } from "../models/discourse-post-event-event";export default class EmbeddableChat extends Service {@service siteSettings;@@ -26,6 +27,23 @@ export default class EmbeddableChat extends Service {);}+ get isPathAllowed() {+ const allowedPaths =+ this.siteSettings.livestream_embeddable_chat_allowed_paths+ .split("|")+ .map((path) => path.trim())+ .filter(Boolean);++ const currentURL = this.router.currentURL.split("?")[0];++ return allowedPaths.some((path) => {+ const normalized = path.endsWith("/") ? path.slice(0, -1) : path;+ return (+ currentURL === normalized || currentURL.startsWith(`${normalized}/`)+ );+ });+ }+canRenderChatChannel(mobileViewAllowed = false) {if (this.isMobileViewport === mobileViewAllowed &&@@ -33,15 +51,7 @@ export default class EmbeddableChat extends Service {this.currentUser &&this.userCanChat) {- const allowedPaths =- this.siteSettings.livestream_embeddable_chat_allowed_paths.split("|");- const withinPathsAllowed = allowedPaths.some(- (path) =>- this.router.currentURL.includes(path) ||- this.router.currentURL.startsWith(path)- );-- if (withinPathsAllowed && this.chatChannelId) {+ if (this.isPathAllowed && this.chatChannelId) {return !this.isChannelOpenInDrawer;}}@@ -70,6 +80,26 @@ export default class EmbeddableChat extends Service {return !this.capabilities.viewport.lg;}+ get showLivestreamHeaderChatIcon() {+ return (+ this.isMobileViewport &&+ !!this.chatChannelId &&+ !this.hasActiveZoomLivestream+ );+ }++ get hasActiveZoomLivestream() {+ if (!this.siteSettings.livestream_zoom_enabled) {+ return false;+ }++ const event = this.topic?.postStream?.posts?.find(+ (post) => post.post_number === 1+ )?.event;++ return !!event?.is_zoom_livestream && !isPastEventTimeframe(event.ends_at);+ }+get topicController() {return getOwner(this).lookup("controller:topic");}diff --git a/plugins/discourse-events/assets/javascripts/discourse/templates/topic-zoom.gjs b/plugins/discourse-events/assets/javascripts/discourse/templates/topic-zoom.gjsindex c827da721d6..a8d2606e89a 100644--- a/plugins/discourse-events/assets/javascripts/discourse/templates/topic-zoom.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/templates/topic-zoom.gjs@@ -1,3 +1,7 @@+import hideApplicationSidebar from "discourse/helpers/hide-application-sidebar";import LivestreamZoomPage from "../components/livestream/zoom-page";-export default <template><LivestreamZoomPage @topic={{@model}} /></template>+export default <template>+ {{hideApplicationSidebar}}+ <LivestreamZoomPage @topic={{@model}} />+</template>diff --git a/plugins/discourse-events/assets/stylesheets/common/livestream.scss b/plugins/discourse-events/assets/stylesheets/common/livestream.scssindex c96c5839ef1..51be48ac006 100644--- a/plugins/discourse-events/assets/stylesheets/common/livestream.scss+++ b/plugins/discourse-events/assets/stylesheets/common/livestream.scss@@ -38,10 +38,8 @@ body.chat-enabled.livestream-topic.confirmed-event-assistance {gap: 0.75rem;align-items: center;- p.discourse-calendar-livestream-zoom-entry__error {- margin: 0;- color: var(--danger);- margin-right: auto;+ a {+ width: 100%;}}@@ -51,67 +49,24 @@ body.chat-enabled.livestream-topic.confirmed-event-assistance {text-align: center;width: 100%;}-- &__audio-hint {- display: flex;- align-items: center;- justify-content: center;- gap: var(--space-1);- margin: 0;- padding: var(--space-2);-- // intentionally hardcoded zoom values- border-radius: 9px;- background: rgb(36, 36, 36);- color: rgb(255, 255, 255);- border: 1px solid rgb(0, 255, 145);- }-- &__frame {- // The frame has to lay out as soon as a join starts, not once Zoom mounts:- // the component view is initialized with a video size measured from this- // element, and a collapsed element measures zero.- display: none;-- // Zoom sets `display` inline on this element when it mounts, which beats- // anything declared here. Only `justify-content` and `padding-top` apply- // from then on.- //- // 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;- }- }}// The meeting is the page here, so it is given the viewport below the header// whole: anything the layout adds around it is height the page cannot have,// and overflowing it drags the meeting under the sticky header.body.discourse-calendar-livestream-zoom-full {+ --d-max-width: 100vw;++ #main-outlet-wrapper {+ padding: 0;+ }+#main-outlet {padding: 0 !important; // override horizon styles+ height: calc(+ var(--composer-vh, 1vh) * 100 - var(--main-outlet-offset, 0px) -+ 1px - var(--chat-header-offset, 0) - var(--composer-height, 0px)+ );}#main-container,diff --git a/plugins/discourse-events/assets/stylesheets/desktop/livestream.scss b/plugins/discourse-events/assets/stylesheets/desktop/livestream.scssindex 4b437569189..e4e463e690f 100644--- a/plugins/discourse-events/assets/stylesheets/desktop/livestream.scss+++ b/plugins/discourse-events/assets/stylesheets/desktop/livestream.scss@@ -74,16 +74,5 @@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);- }}}diff --git a/plugins/discourse-events/config/locales/client.en.yml b/plugins/discourse-events/config/locales/client.en.ymlindex df614f4b0b0..64ca25c3fab 100644--- a/plugins/discourse-events/config/locales/client.en.yml+++ b/plugins/discourse-events/config/locales/client.en.yml@@ -35,11 +35,6 @@ en: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..."- join_audio_hint: "Click %{icon} above to join audio"chat:rsvp_to_event: "RSVP to the event to start chatting"rsvp_to_event_with_link: "RSVP to <a href='%{url}'>the event</a> to start chatting"diff --git a/plugins/discourse-events/plugin.rb b/plugins/discourse-events/plugin.rbindex c40fe95e57f..f43cbb1ef31 100644--- a/plugins/discourse-events/plugin.rb+++ b/plugins/discourse-events/plugin.rb@@ -44,7 +44,6 @@ register_svg_icon "star"register_svg_icon "file-arrow-up"register_svg_icon "location-pin"register_svg_icon "arrows-up-to-line"-register_svg_icon "zoom-join-audio"extend_content_security_policy(worker_src: %w[https://source.zoom.us blob:])module ::DiscourseCalendardiff --git a/plugins/discourse-events/spec/models/discourse_post_event/event_spec.rb b/plugins/discourse-events/spec/models/discourse_post_event/event_spec.rbindex 39b847d566f..37670201f77 100644--- a/plugins/discourse-events/spec/models/discourse_post_event/event_spec.rb+++ b/plugins/discourse-events/spec/models/discourse_post_event/event_spec.rb@@ -783,10 +783,21 @@ describe DiscoursePostEvent::Event do).to be(true)end- it "is false when now is before the start of the day of the event" do+ it "is true on a later day of a multi-day event" doexpect(event_with(- starts_at: Time.zone.now.tomorrow.beginning_of_day,+ starts_at: 2.days.ago,+ ends_at: 1.day.from_now,+ all_day: true,+ ).currently_within_event_timeframe?,+ ).to be(true)+ end++ it "is false after the final day of a multi-day event" do+ expect(+ event_with(+ starts_at: 5.days.ago,+ ends_at: 2.days.ago,all_day: true,).currently_within_event_timeframe?,).to be(false)diff --git a/plugins/discourse-events/spec/requests/livestream_controller_spec.rb b/plugins/discourse-events/spec/requests/livestream_controller_spec.rbindex 936d4fd57db..87150045e43 100644--- a/plugins/discourse-events/spec/requests/livestream_controller_spec.rb+++ b/plugins/discourse-events/spec/requests/livestream_controller_spec.rb@@ -181,6 +181,12 @@ module DiscourseCalendarexpect(response.body).to include("zoomFrameConfig")end+ it "joins the meeting with chat disabled" do+ get "/discourse-calendar/livestream/zoom/frame", params: { topic_id: topic.id }++ expect(response.body).to include("isSupportChat: false")+ end+it "points the page at the signature for its own topic" doget "/discourse-calendar/livestream/zoom/frame", params: { topic_id: topic.id }diff --git a/plugins/discourse-events/svg-icons/plugin-icons.svg b/plugins/discourse-events/svg-icons/plugin-icons.svgdeleted file mode 100644index 3907c5cf3b4..00000000000--- a/plugins/discourse-events/svg-icons/plugin-icons.svg+++ /dev/null@@ -1,4 +0,0 @@-<?xml version="1.0" encoding="UTF-8"?>-<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">- <symbol id="zoom-join-audio" viewBox="0 0 16 16"><path d="M12 7C12 4.79086 10.2091 3 8 3C5.79086 3 4 4.79086 4 7V11.5C4 11.7761 3.77614 12 3.5 12H2.5C1.94772 12 1.5 11.5523 1.5 11V9.5C1.5 8.94772 1.94772 8.5 2.5 8.5H3V7C3 4.23858 5.23858 2 8 2C10.7614 2 13 4.23858 13 7V8.5H13.5C14.0523 8.5 14.5 8.94772 14.5 9.5V11C14.5 11.5523 14.0523 12 13.5 12H12.5C12.2239 12 12 11.7761 12 11.5V7Z" fill="currentColor"/><path d="M8.17678 7.21971C8.07915 7.12208 7.92085 7.12208 7.82322 7.21971L6.07322 8.96971C5.97559 9.06734 5.97559 9.22563 6.07322 9.32326L6.42678 9.67681C6.52441 9.77445 6.6827 9.77445 6.78033 9.67681L7.5 8.95714V11.75C7.5 11.8881 7.61193 12 7.75 12H8.25C8.38807 12 8.5 11.8881 8.5 11.75V8.95714L9.21967 9.67681C9.3173 9.77445 9.47559 9.77445 9.57322 9.67681L9.92678 9.32326C10.0244 9.22563 10.0244 9.06734 9.92678 8.96971L8.17678 7.21971Z" fill="#00FF91"/></symbol>-</svg>diff --git a/plugins/discourse-events/test/javascripts/integration/components/livestream-test.gjs b/plugins/discourse-events/test/javascripts/integration/components/livestream-test.gjsindex d1e70878332..e5b4c4f477b 100644--- a/plugins/discourse-events/test/javascripts/integration/components/livestream-test.gjs+++ b/plugins/discourse-events/test/javascripts/integration/components/livestream-test.gjs@@ -6,7 +6,6 @@ import sinon from "sinon";import { withPluginApi } from "discourse/lib/plugin-api";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import Livestream from "../../discourse/components/discourse-post-event/livestream";-import ZoomMeetingSession from "../../discourse/lib/zoom-meeting-session";const ZOOM_URL = "https://us06web.zoom.us/j/123456789?pwd=secret";const ZOOM_ENTRY_SELECTOR = ".discourse-calendar-livestream-zoom-entry";@@ -155,51 +154,5 @@ module();});});-- module("with a Zoom livestream", function (nestedHooks) {- let preventCloak;-- nestedHooks.beforeEach(function () {- const owner = getOwner(this);- owner.unregister("service:discourse-post-event-api");- owner.register(- "service:discourse-post-event-api",- { joinEvent: () => Promise.resolve() },- { instantiate: false }- );-- this.event.id = 7;- this.event.currentlyWithinEventTimeframe = true;- this.event.canUpdateAttendance = false;-- sinon.stub(ZoomMeetingSession.prototype, "performJoin").resolves();-- withPluginApi((api) => {- preventCloak = sinon.stub(Object.getPrototypeOf(api), "preventCloak");- });- });-- test("keeps the post rendered once the webinar has joined", async function (assert) {- this.post = { id: 42 };-- await render(- <template>- <Livestream @event={{this.event}} @post={{this.post}} />- </template>- );-- assert.false(- preventCloak.called,- "cloaking is still allowed before the user joins"- );-- await click(".discourse-calendar-livestream-zoom-entry .btn-primary");-- assert.true(- preventCloak.calledWith(42),- "prevents the post holding the Zoom session from being cloaked"- );- });- });});diff --git a/plugins/discourse-events/test/javascripts/integration/components/zoom-entry-test.gjs b/plugins/discourse-events/test/javascripts/integration/components/zoom-entry-test.gjsindex e8a6f74b3f3..e04b0ea577f 100644--- a/plugins/discourse-events/test/javascripts/integration/components/zoom-entry-test.gjs+++ b/plugins/discourse-events/test/javascripts/integration/components/zoom-entry-test.gjs@@ -1,115 +1,25 @@import { getOwner } from "@ember/owner";-import { clearRender, click, render, settled } from "@ember/test-helpers";+import { click, render } from "@ember/test-helpers";import { module, test } from "qunit";import sinon from "sinon";import { setupRenderingTest } from "discourse/tests/helpers/component-test";import 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 AUDIO_HINT_SELECTOR =- ".discourse-calendar-livestream-zoom-entry__audio-hint";--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>`;-}+ ".discourse-calendar-livestream-zoom-entry .discourse-calendar-livestream-zoom-entry__join";+const WAITING_SELECTOR = ".discourse-calendar-livestream-zoom-entry__waiting";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,+ pastEventTimeframe: false,livestreamChatChannelId: 9,post: {topic: {@@ -118,57 +28,53 @@ module("Integration | Component | LivestreamZoomEntry", function (hooks) {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 });-+ test("links to the zoom page, which the meeting takes over in place", async function (assert) {await render(<template><LivestreamZoomEntry @event={{this.event}} /></template>);+ assert.dom(JOIN_BUTTON_SELECTOR).hasTagName("a");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");+ .dom(JOIN_BUTTON_SELECTOR)+ .hasAttribute(+ "href",+ "/t/test-topic/1/zoom",+ "the link is a real one, so it can be opened however the user likes"+ );+ assert+ .dom(JOIN_BUTTON_SELECTOR)+ .doesNotHaveAttribute(+ "target",+ "the meeting is the page, so it is not sent off to a window of its own"+ );assert- .dom(".discourse-calendar-livestream-zoom-entry a")- .doesNotExist("no fallback link before an error");+ .dom(".discourse-calendar-livestream-zoom-entry__frame")+ .doesNotExist("inline embedding was replaced by the /zoom route");});- test("renders the mobile route link on mobile", async function (assert) {- stubCapabilities(getOwner(this), { lg: false });+ test("asks for the zoom route by name rather than leaving the click to the interceptor", async function (assert) {+ const transitionTo = sinon.stub(+ getOwner(this).lookup("service:router"),+ "transitionTo"+ );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 click(JOIN_BUTTON_SELECTOR);- await render(- <template><LivestreamZoomEntry @event={{this.event}} /></template>+ assert.true(+ transitionTo.calledWith("topic-zoom", "test-topic", 1),+ "the meeting is reached, not the topic it hangs off");-- 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 });+ test("disables the join button outside the event timeframe", async function (assert) {this.event.currentlyWithinEventTimeframe = false;await render(@@ -182,8 +88,6 @@ module("Integration | Component | LivestreamZoomEntry", function (hooks) {});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(@@ -194,7 +98,6 @@ module("Integration | Component | LivestreamZoomEntry", function (hooks) {});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;@@ -206,7 +109,6 @@ module("Integration | Component | LivestreamZoomEntry", function (hooks) {});test("renders nothing without a livestream chat channel", async function (assert) {- stubCapabilities(getOwner(this), { lg: true });this.event.livestreamChatChannelId = null;await render(@@ -216,647 +118,31 @@ module("Integration | Component | LivestreamZoomEntry", function (hooks) {assert.dom(".discourse-calendar-livestream-zoom-entry").doesNotExist();});- test("renders button 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").exists();- });+ test("asks an anonymous user to sign up instead of linking them out", async function (assert) {+ const owner = getOwner(this);+ owner.unregister("service:current-user");- test("shows the audio hint only once the meeting is joined", async function (assert) {- stubCapabilities(getOwner(this), { lg: true });- const performJoin = sinon.stub(ZoomMeetingSession.prototype, "performJoin");- const join = deferred();- performJoin.returns(join.promise);+ const send = sinon.spy();+ owner.unregister("route:application");+ owner.register("route:application", { send }, { instantiate: false });await render(<template><LivestreamZoomEntry @event={{this.event}} /></template>);- assert.dom(AUDIO_HINT_SELECTOR).doesNotExist("hidden before joining");-- click(JOIN_BUTTON_SELECTOR);- await settled();-- assert.dom(AUDIO_HINT_SELECTOR).doesNotExist("hidden while joining");-- join.resolve();- await settled();-- assert.dom(AUDIO_HINT_SELECTOR).hasText("Click above to join audio");- assert.dom(`${AUDIO_HINT_SELECTOR} .d-icon-zoom-join-audio`).exists();- });-- test("notifies once the desktop session has joined", async function (assert) {- stubCapabilities(getOwner(this), { lg: true });- const performJoin = sinon.stub(ZoomMeetingSession.prototype, "performJoin");- const join = deferred();- performJoin.returns(join.promise);- this.onJoined = sinon.fake();-- await render(- <template>- <LivestreamZoomEntry- @event={{this.event}}- @onJoined={{this.onJoined}}- />- </template>- );-- await click(JOIN_BUTTON_SELECTOR);-- assert.false(- this.onJoined.called,- "does not notify while the join is still in flight"- );-- join.resolve();- await settled();-- assert.strictEqual(- this.onJoined.callCount,- 1,- "notifies once the session is joined"- );- });-- test("does not notify when the join fails", async function (assert) {- stubCapabilities(getOwner(this), { lg: true });- sinon- .stub(ZoomMeetingSession.prototype, "performJoin")- .rejects(new Error("nope"));- this.onJoined = sinon.fake();-- await render(- <template>- <LivestreamZoomEntry- @event={{this.event}}- @onJoined={{this.onJoined}}- />- </template>- );-- await click(JOIN_BUTTON_SELECTOR);-- assert.false(this.onJoined.called);- });-- test("does not notify when the component is torn down mid-join", async function (assert) {- stubCapabilities(getOwner(this), { lg: true });- const performJoin = sinon.stub(ZoomMeetingSession.prototype, "performJoin");- const join = deferred();- performJoin.returns(join.promise);- this.onJoined = sinon.fake();-- await render(- <template>- <LivestreamZoomEntry- @event={{this.event}}- @onJoined={{this.onJoined}}- />- </template>- );+ assert.dom(JOIN_BUTTON_SELECTOR).hasText("Join Zoom");+ assert+ .dom(JOIN_BUTTON_SELECTOR)+ .hasTagName(+ "button",+ "there is nothing to link to: the meeting is only served to a signed-in user"+ );await click(JOIN_BUTTON_SELECTOR);- await clearRender();- join.resolve();- await settled();-- assert.false(- this.onJoined.called,- "the session was torn down before it could join"+ assert.true(+ send.calledWith("showCreateAccount"),+ "the signup modal stands in for the meeting");});-- test("hides the audio hint once the user connects audio", async function (assert) {- stubCapabilities(getOwner(this), { lg: true });- const captured = captureSession();- sinon.stub(ZoomMeetingSession.prototype, "performJoin").resolves();-- await render(- <template><LivestreamZoomEntry @event={{this.event}} /></template>- );-- await click(JOIN_BUTTON_SELECTOR);-- const { session } = captured;- session.zoomClient = {- getCurrentUser: () => ({ userId: 1, audio: "" }),- updateVideoOptions: () => {},- };-- session.syncAudioState();- await settled();-- assert.dom(AUDIO_HINT_SELECTOR).exists("audio is not connected yet");-- session.zoomClient.getCurrentUser = () => ({- userId: 1,- audio: "computer",- });- session.syncAudioState();- await settled();-- assert.dom(AUDIO_HINT_SELECTOR).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-events/test/javascripts/integration/components/zoom-page-test.gjs b/plugins/discourse-events/test/javascripts/integration/components/zoom-page-test.gjsindex 6073c543154..43b44bc305a 100644--- a/plugins/discourse-events/test/javascripts/integration/components/zoom-page-test.gjs+++ b/plugins/discourse-events/test/javascripts/integration/components/zoom-page-test.gjs@@ -1,5 +1,6 @@import { getOwner } from "@ember/owner";-import { render } from "@ember/test-helpers";+import { trackedObject } from "@ember/reactive/collections";+import { render, settled } from "@ember/test-helpers";import { module, test } from "qunit";import sinon from "sinon";import { setupRenderingTest } from "discourse/tests/helpers/component-test";@@ -63,6 +64,21 @@ function stubMessageBus(context) {sinon.stub(messageBus, "unsubscribe");}+function stubEventApi(context) {+ const api = {+ joinEvent: sinon.fake.resolves(),+ updateEventAttendance: sinon.fake.resolves(),+ };++ const owner = getOwner(context);+ owner.unregister("service:discourse-post-event-api");+ owner.register("service:discourse-post-event-api", api, {+ instantiate: false,+ });++ return api;+}+module("Integration | Component | LivestreamZoomPage", function (hooks) {setupRenderingTest(hooks);@@ -71,6 +87,7 @@ module("Integration | Component | LivestreamZoomPage", function (hooks) {stubChat(this);stubMessageBus(this);stubFrameUrl(this);+ this.eventApi = stubEventApi(this);this.topic = {id: 1,@@ -150,4 +167,58 @@ module("Integration | Component | LivestreamZoomPage", function (hooks) {assert.dom(CHAT_SELECTOR).doesNotExist();});+ // Chat beside the meeting is read-only for anyone the event has no "going"+ // answer from, so reaching the meeting is taken as that answer.+ test("marks a user who has not answered the RSVP as going", async function (assert) {+ this.topic.postStream.posts[0].event.can_update_attendance = true;++ await render(+ <template><LivestreamZoomPage @topic={{this.topic}} /></template>+ );++ assert.true(+ this.eventApi.joinEvent.calledWithMatch(sinon.match.any, {+ status: "going",+ }),+ "the user is entered into the event on the way in"+ );+ });++ test("leaves an answer the user has already given alone", async function (assert) {+ const event = this.topic.postStream.posts[0].event;+ event.can_update_attendance = true;+ event.watching_invitee = { id: 5, status: "not_going" };++ await render(+ <template><LivestreamZoomPage @topic={{this.topic}} /></template>+ );++ assert.false(this.eventApi.joinEvent.called, "no answer is overwritten");+ assert.false(this.eventApi.updateEventAttendance.called);+ });++ test("answers once, however often the post changes underneath it", async function (assert) {+ const event = this.topic.postStream.posts[0].event;+ event.can_update_attendance = true;++ const post = trackedObject({ event });+ this.topic.postStream.posts = [post];++ await render(+ <template><LivestreamZoomPage @topic={{this.topic}} /></template>+ );++ post.event = { ...event };+ await settled();++ assert.strictEqual(this.eventApi.joinEvent.callCount, 1);+ });++ test("does not answer for a user the event will not take one from", async function (assert) {+ await render(+ <template><LivestreamZoomPage @topic={{this.topic}} /></template>+ );++ assert.false(this.eventApi.joinEvent.called);+ });});diff --git a/plugins/discourse-events/test/javascripts/lib/zoom-component-view-dom-test.js b/plugins/discourse-events/test/javascripts/lib/zoom-component-view-dom-test.jsdeleted file mode 100644index 1ce7703a035..00000000000--- a/plugins/discourse-events/test/javascripts/lib/zoom-component-view-dom-test.js+++ /dev/null@@ -1,48 +0,0 @@-import { module, test } from "qunit";-import { computeZoomViewSize } from "discourse/plugins/discourse-events/discourse/lib/zoom-component-view-dom";--function elementOfWidth(width) {- return { getBoundingClientRect: () => ({ width }) };-}--module("Unit | Lib | zoom-component-view-dom", function () {- test("computeZoomViewSize measures the root", function (assert) {- assert.deepEqual(computeZoomViewSize(elementOfWidth(754)), {- width: 754,- height: 424,- });- });-- test("computeZoomViewSize falls back to the container when the root is collapsed", function (assert) {- const root = {- ...elementOfWidth(0),- parentElement: elementOfWidth(754),- };-- assert.deepEqual(- computeZoomViewSize(root),- { width: 754, height: 424 },- "a root that has not been laid out yet does not pin Zoom to the minimum"- );- });-- test("computeZoomViewSize clamps to the supported range", function (assert) {- assert.deepEqual(- computeZoomViewSize(elementOfWidth(120)),- { width: 240, height: 135 },- "below the minimum"- );-- assert.deepEqual(- computeZoomViewSize(elementOfWidth(4000)),- { width: 1440, height: 810 },- "above the maximum"- );-- assert.deepEqual(- computeZoomViewSize(null),- { width: 240, height: 135 },- "without an element to measure"- );- });-});diff --git a/plugins/discourse-events/test/javascripts/unit/lib/zoom-meeting-session-test.js b/plugins/discourse-events/test/javascripts/unit/lib/zoom-meeting-session-test.jsdeleted file mode 100644index 538cd59ccaf..00000000000--- a/plugins/discourse-events/test/javascripts/unit/lib/zoom-meeting-session-test.js+++ /dev/null@@ -1,97 +0,0 @@-import { getOwner } from "@ember/owner";-import { setupTest } from "ember-qunit";-import { module, test } from "qunit";-import sinon from "sinon";-import ZoomMeetingSession from "../../discourse/lib/zoom-meeting-session";--// `document.hidden` is an inherited accessor, so it can only be faked by-// shadowing it on the document itself.-function stubDocumentHidden(hidden) {- Object.defineProperty(document, "hidden", {- configurable: true,- get: () => hidden,- });-}--function restoreDocumentHidden() {- delete document.hidden;-}--// The view sync runs in a frame callback, which `settled` knows nothing about.-function nextFrame() {- return new Promise((resolve) => requestAnimationFrame(resolve));-}--module("Unit | Lib | ZoomMeetingSession", function (hooks) {- setupTest(hooks);-- hooks.afterEach(function () {- restoreDocumentHidden();- });-- test("defers sizing Zoom's view while the document is hidden", async function (assert) {- const session = new ZoomMeetingSession(getOwner(this), {- topicId: 1,- canJoin: () => true,- });- sinon.stub(session, "performJoin").resolves();- const syncVideoSize = sinon.stub(session, "syncVideoSize");- session.zoomClient = { updateVideoOptions: () => {} };-- stubDocumentHidden(true);-- await session.join();- await nextFrame();-- assert.false(- syncVideoSize.called,- "frame callbacks do not run in a background tab"- );-- stubDocumentHidden(false);- document.dispatchEvent(new Event("visibilitychange"));- await nextFrame();-- assert.true(- syncVideoSize.called,- "the view is sized once the tab is visible again"- );-- session.teardown();- });-- test("sizes Zoom's view straight away when the document is visible", async function (assert) {- const session = new ZoomMeetingSession(getOwner(this), {- topicId: 1,- canJoin: () => true,- });- sinon.stub(session, "performJoin").resolves();- const syncVideoSize = sinon.stub(session, "syncVideoSize");-- stubDocumentHidden(false);-- await session.join();- await nextFrame();-- assert.true(syncVideoSize.called);-- session.teardown();- });-- test("stops listening for visibility changes once torn down", async function (assert) {- const session = new ZoomMeetingSession(getOwner(this), {- topicId: 1,- canJoin: () => true,- });- const syncVideoSize = sinon.stub(session, "syncVideoSize");- session.zoomClient = { updateVideoOptions: () => {} };-- stubDocumentHidden(false);- session.teardown();-- document.dispatchEvent(new Event("visibilitychange"));- await nextFrame();-- assert.false(syncVideoSize.called);- });-});diff --git a/plugins/discourse-events/test/javascripts/unit/models/discourse-post-event-event-test.js b/plugins/discourse-events/test/javascripts/unit/models/discourse-post-event-event-test.jsindex 459fcb30aed..8fcf87f231d 100644--- a/plugins/discourse-events/test/javascripts/unit/models/discourse-post-event-event-test.js+++ b/plugins/discourse-events/test/javascripts/unit/models/discourse-post-event-event-test.js@@ -144,6 +144,47 @@ module("Unit | Model | DiscoursePostEventEvent", function () {);});+ test("isWithinEventTimeframe returns true for an all-day event on a later day", function (assert) {+ // Multi-day events run through the day of their end, not just their start.+ const startsAt = moment().subtract(2, "days").startOf("day").toISOString();+ const endsAt = moment().add(1, "day").startOf("day").toISOString();+ const allDayEvent = DiscoursePostEventEvent.create({+ id: 4,+ starts_at: startsAt,+ ends_at: endsAt,+ all_day: true,+ });++ assert.true(+ isWithinEventTimeframe(+ allDayEvent.allDay,+ allDayEvent.startsAt,+ allDayEvent.endsAt+ ),+ "allows joining while the event is ongoing"+ );+ });++ test("isWithinEventTimeframe returns false for an all-day event after its final day", function (assert) {+ const startsAt = moment().subtract(5, "days").startOf("day").toISOString();+ const endsAt = moment().subtract(2, "days").startOf("day").toISOString();+ const allDayEvent = DiscoursePostEventEvent.create({+ id: 5,+ starts_at: startsAt,+ ends_at: endsAt,+ all_day: true,+ });++ assert.false(+ isWithinEventTimeframe(+ allDayEvent.allDay,+ allDayEvent.startsAt,+ allDayEvent.endsAt+ ),+ "rejects joining once the final day has passed"+ );+ });+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({@@ -182,4 +223,40 @@ module("Unit | Model | DiscoursePostEventEvent", function () {"returns true for non-all-day events within the timeframe");});++ test("isWithinEventTimeframe stays open for an event without an end time", function (assert) {+ const started = DiscoursePostEventEvent.create({+ id: 6,+ starts_at: moment().subtract(3, "hours").toISOString(),+ ends_at: null,+ all_day: false,+ });+ const notYetOpen = DiscoursePostEventEvent.create({+ id: 7,+ starts_at: moment().add(45, "minutes").toISOString(),+ ends_at: null,+ all_day: false,+ });++ assert.true(+ isWithinEventTimeframe(started.allDay, started.startsAt, started.endsAt),+ "an event without an end time never closes"+ );+ assert.false(+ isWithinEventTimeframe(+ notYetOpen.allDay,+ notYetOpen.startsAt,+ notYetOpen.endsAt+ ),+ "early access still applies"+ );+ });++ test("isWithinEventTimeframe returns false without a start time", function (assert) {+ assert.false(isWithinEventTimeframe(false, null, null), "no start time");+ assert.false(+ isWithinEventTimeframe(false, undefined, undefined),+ "undefined start time"+ );+ });});diff --git a/plugins/discourse-events/test/javascripts/unit/routes/topic-zoom-test.js b/plugins/discourse-events/test/javascripts/unit/routes/topic-zoom-test.jsnew file mode 100644index 00000000000..85cab009ae2--- /dev/null+++ b/plugins/discourse-events/test/javascripts/unit/routes/topic-zoom-test.js@@ -0,0 +1,56 @@+import { getOwner } from "@ember/owner";+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import sinon from "sinon";++// The sidebar is hidden on this page by core's {{hideApplicationSidebar}}+// helper in templates/topic-zoom.gjs, which is core's to test and out of this+// route's reach. The route's own jobs are closing the chat it replaces and+// releasing the topic it borrowed from the topic controller.++module("Unit | Route | topic-zoom", function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ const owner = getOwner(this);++ this.topicController = {+ set(field, value) {+ this[field] = value;+ },+ };++ this.closeChatVisibility = sinon.spy();+ owner.unregister("service:embeddable-chat");+ owner.register(+ "service:embeddable-chat",+ { closeChatVisibility: this.closeChatVisibility },+ { instantiate: false }+ );++ this.subject = owner.lookup("route:topic-zoom");+ // The route hands its topic controller to the app; only the values it sets+ // on it are under test.+ this.subject.controllerFor = () => this.topicController;+ });++ test("closes the embeddable chat on activation", function (assert) {+ this.subject.activate();++ assert.true(+ this.closeChatVisibility.called,+ "the meeting takes over the chat on the way in"+ );+ });++ test("clears the shared topic model on exit", function (assert) {+ this.subject.activate();+ this.subject.deactivate();++ assert.strictEqual(+ this.topicController.model,+ null,+ "the topic is released so it does not leak into the next page"+ );+ });+});diff --git a/plugins/discourse-events/test/javascripts/unit/services/embeddable-chat-test.js b/plugins/discourse-events/test/javascripts/unit/services/embeddable-chat-test.jsnew file mode 100644index 00000000000..892ff45f76a--- /dev/null+++ b/plugins/discourse-events/test/javascripts/unit/services/embeddable-chat-test.js@@ -0,0 +1,143 @@+import { getOwner } from "@ember/owner";+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";++module("Unit | Service | embeddable-chat", function (hooks) {+ setupTest(hooks);++ hooks.beforeEach(function () {+ const owner = getOwner(this);++ this.topicController = { model: { chat_channel_id: 9 } };+ owner.register("controller:topic", this.topicController, {+ instantiate: false,+ });++ this.router = { currentURL: "/t/a-topic/1" };+ this.capabilities = { viewport: { lg: true } };++ for (const [name, value] of [+ ["router", this.router],+ ["current-user", {}],+ ["capabilities", this.capabilities],+ ["chat", { userCanChat: true }],+ ["chat-state-manager", {}],+ ]) {+ owner.unregister(`service:${name}`);+ owner.register(`service:${name}`, value, { instantiate: false });+ }++ const siteSettings = owner.lookup("service:site-settings");+ siteSettings.chat_enabled = true;+ siteSettings.livestream_embeddable_chat_allowed_paths = "/t";++ this.subject = owner.lookup("service:embeddable-chat");+ });++ test("renders on topic URLs under the allowed path", function (assert) {+ this.router.currentURL = "/t/a-topic/1";+ assert.true(this.subject.canRenderChatChannel(false));++ this.router.currentURL = "/t/a-topic/1/zoom";+ assert.true(this.subject.canRenderChatChannel(false));+ });++ test("does not render on unrelated URLs even with a leftover channel", function (assert) {+ this.router.currentURL = "/admin/config/customize/themes";+ assert.false(this.subject.canRenderChatChannel(false));+ });++ test("only matches at a path boundary", function (assert) {+ this.router.currentURL = "/tarkov";+ assert.false(this.subject.canRenderChatChannel(false));+ });++ test("honors additional configured paths", function (assert) {+ getOwner(this).lookup(+ "service:site-settings"+ ).livestream_embeddable_chat_allowed_paths = "/t|/video";++ this.router.currentURL = "/video/a-livestream/2";+ assert.true(this.subject.canRenderChatChannel(false));++ this.router.currentURL = "/t/a-topic/1";+ assert.true(this.subject.canRenderChatChannel(false));+ });++ test("ignores surrounding whitespace in the allowed paths list", function (assert) {+ getOwner(this).lookup(+ "service:site-settings"+ ).livestream_embeddable_chat_allowed_paths = "/t | /video ";++ this.router.currentURL = "/video/a-livestream/2";+ assert.true(this.subject.canRenderChatChannel(false));+ });++ test("matches a bare allowed path even with a query string", function (assert) {+ this.router.currentURL = "/t?topic_timer=123";+ assert.true(this.subject.canRenderChatChannel(false));+ });++ test("does not render when the topic has no chat channel", function (assert) {+ this.topicController.model = {};+ this.router.currentURL = "/t/a-topic/1";+ assert.false(this.subject.canRenderChatChannel(false));+ });++ test("requires the correct viewport", function (assert) {+ this.router.currentURL = "/t/a-topic/1";+ // Desktop viewport expected but mobile requested, and vice versa.+ assert.false(this.subject.canRenderChatChannel(true));++ this.capabilities.viewport.lg = false;+ assert.true(this.subject.canRenderChatChannel(true));+ assert.false(this.subject.canRenderChatChannel(false));+ });++ test("shows the header chat icon below the breakpoint with a channel", function (assert) {+ this.capabilities.viewport.lg = false;+ assert.true(this.subject.showLivestreamHeaderChatIcon);++ this.capabilities.viewport.lg = true;+ assert.false(this.subject.showLivestreamHeaderChatIcon);+ });++ test("does not show the header chat icon without a channel", function (assert) {+ this.capabilities.viewport.lg = false;+ this.topicController.model = {};++ assert.false(this.subject.showLivestreamHeaderChatIcon);+ });++ test("hides the header chat icon on a zoom livestream", function (assert) {+ const owner = getOwner(this);+ owner.lookup("service:site-settings").livestream_zoom_enabled = true;+ this.capabilities.viewport.lg = false;++ const event = { is_zoom_livestream: true, ends_at: null };+ this.topicController.model = {+ chat_channel_id: 9,+ // The join button lives on the first post, which is not necessarily the+ // first post loaded into the stream.+ postStream: { posts: [{ post_number: 4 }, { post_number: 1, event }] },+ };++ assert.false(+ this.subject.showLivestreamHeaderChatIcon,+ "the zoom page renders the chat inline instead"+ );++ event.ends_at = moment().subtract(1, "hour").toISOString();+ assert.true(+ this.subject.showLivestreamHeaderChatIcon,+ "the icon comes back once the webinar is over"+ );++ event.ends_at = null;+ owner.lookup("service:site-settings").livestream_zoom_enabled = false;+ assert.true(+ this.subject.showLivestreamHeaderChatIcon,+ "and when the zoom integration is off"+ );+ });+});