never use rtcSession.room (Relation classes refactor)

make sure everything is passed through dedicated room / client props.
This commit is contained in:
Timo K. committed 2026-11-20 01:01:28 +01:00
1 parent f6b5dd0b7e
commit 2a8836e44a
15 files changed
+319 -185

No files matched your search

+3
View File
@@ -47,6 +47,9 @@ function mockClient(knownRoom: Room | null = room): MatrixClient {
getSyncState: () => null,
getUser: () => null,
getCrypto: () => undefined,
sendEvent: vi.fn(),
redactEvent: vi.fn(),
decryptEventIfNeeded: vi.fn(),
setDisplayName: vi.fn(),
setAvatarUrl: vi.fn(),
uploadContent: vi.fn(),
+3
View File
@@ -22,6 +22,9 @@ function mockHost(): MatrixClient & { token: string } {
off: vi.fn(),
getUser: vi.fn(() => null),
getCrypto: vi.fn(() => undefined),
sendEvent: vi.fn(),
redactEvent: vi.fn(),
decryptEventIfNeeded: vi.fn(),
setDisplayName: vi.fn(),
setAvatarUrl: vi.fn(),
uploadContent: vi.fn(),
+6
View File
@@ -42,12 +42,18 @@ export function createCallViewClient(
getSyncState: host.getSyncState.bind(host),
// `on`/`off`, to listen for:
// - `ClientEvent.Sync` (RTC slot homeserver connection)
// - `MatrixEventEvent.Decrypted` (reactions once decrypted)
on: host.on.bind(host),
off: host.off.bind(host),
// The host's store, which only its sync fills
getUser: host.getUser.bind(host),
// The device's crypto: there must never be a second one
getCrypto: host.getCrypto.bind(host),
// Reactions and raised hands: the host's crypto encrypts and decrypts them,
// and its room gets the local echo
sendEvent: host.sendEvent.bind(host),
redactEvent: host.redactEvent.bind(host),
decryptEventIfNeeded: host.decryptEventIfNeeded.bind(host),
// Credentials, static, we can use own
getUserId: own.getUserId.bind(own),
+4
View File
@@ -232,6 +232,8 @@ export const ElementCall: FC<ElementCallProps> = ({
| "currentState"
// Joined and invited members, for the RTC slot and the call view model
| "getMembersWithMembership"
// Raised hands already in the room, for the reactions reader
| "relations"
// `on`/`off`, to listen for:
// - the RTC session's room events
// - `RoomEvent.Name` (room name)
@@ -239,6 +241,8 @@ export const ElementCall: FC<ElementCallProps> = ({
// - `RoomStateEvent.Events` (RTC slot status)
// - `RoomStateEvent.Members` (RTC slot and call view model members)
// - `RoomEvent.Timeline` and `RoomStickyEventsEvent.Update` (call notifications)
// - `RoomEvent.Timeline`, `RoomEvent.Redaction` and
// `RoomEvent.LocalEchoUpdated` (reactions and raised hands)
| "on"
| "off"
> | null;
+61 -20
View File
@@ -10,6 +10,7 @@ import { expect, test } from "vitest";
import { TooltipProvider } from "@vector-im/compound-web";
import { userEvent } from "@testing-library/user-event";
import { type ReactNode } from "react";
import { type MatrixClient, type Room } from "matrix-js-sdk";
import { ReactionToggleButton } from "./ReactionToggleButton";
import { ElementCallReactionEventType } from "../reactions";
@@ -25,9 +26,13 @@ const localIdent = `${localRtcMember.userId}:${localRtcMember.deviceId}`;
function TestComponent({
rtcSession,
matrixRoom,
client,
vm,
}: {
rtcSession: MockRTCSession;
matrixRoom: Room;
client: MatrixClient;
vm: CallViewModel;
}): ReactNode {
return (
@@ -35,6 +40,8 @@ function TestComponent({
<ReactionsSenderProvider
vm={vm}
rtcSession={rtcSession.asMockedSession()}
room={matrixRoom}
client={client}
>
<ReactionToggleButton
reactionData={{
@@ -50,9 +57,15 @@ function TestComponent({
test("Can open menu", async () => {
const user = userEvent.setup();
const { vm, rtcSession } = getBasicCallViewModelEnvironment([alice]);
const { vm, rtcSession, matrixRoom, client } =
getBasicCallViewModelEnvironment([alice]);
const { getByLabelText, container } = render(
<TestComponent vm={vm} rtcSession={rtcSession} />,
<TestComponent
vm={vm}
rtcSession={rtcSession}
matrixRoom={matrixRoom}
client={client}
/>,
);
await user.click(getByLabelText("Reactions"));
expect(container).toMatchSnapshot();
@@ -60,15 +73,20 @@ test("Can open menu", async () => {
test("Can raise hand", async () => {
const user = userEvent.setup();
const { vm, rtcSession, handRaisedSubject$ } =
const { vm, rtcSession, matrixRoom, client, handRaisedSubject$ } =
getBasicCallViewModelEnvironment([local, alice]);
const { getByLabelText, container } = render(
<TestComponent vm={vm} rtcSession={rtcSession} />,
<TestComponent
vm={vm}
rtcSession={rtcSession}
matrixRoom={matrixRoom}
client={client}
/>,
);
await user.click(getByLabelText("Reactions"));
await user.click(getByLabelText("Raise hand"));
expect(rtcSession.room.client.sendEvent).toHaveBeenCalledWith(
rtcSession.room.roomId,
expect(client.sendEvent).toHaveBeenCalledWith(
matrixRoom.roomId,
"m.reaction",
{
"m.relates_to": {
@@ -94,10 +112,15 @@ test("Can raise hand", async () => {
test("Can lower hand", async () => {
const reactionEventId = "$my-reaction-event:example.org";
const user = userEvent.setup();
const { vm, rtcSession, handRaisedSubject$ } =
const { vm, rtcSession, matrixRoom, client, handRaisedSubject$ } =
getBasicCallViewModelEnvironment([local, alice]);
const { getByLabelText, container } = render(
<TestComponent vm={vm} rtcSession={rtcSession} />,
<TestComponent
vm={vm}
rtcSession={rtcSession}
matrixRoom={matrixRoom}
client={client}
/>,
);
await user.click(getByLabelText("Reactions"));
await user.click(getByLabelText("Raise hand"));
@@ -112,8 +135,8 @@ test("Can lower hand", async () => {
});
await user.click(getByLabelText("Reactions"));
await user.click(getByLabelText("Lower hand"));
expect(rtcSession.room.client.redactEvent).toHaveBeenCalledWith(
rtcSession.room.roomId,
expect(client.redactEvent).toHaveBeenCalledWith(
matrixRoom.roomId,
reactionEventId,
);
act(() => {
@@ -125,14 +148,20 @@ test("Can lower hand", async () => {
test("Can react with emoji", async () => {
const user = userEvent.setup();
const { vm, rtcSession } = getBasicCallViewModelEnvironment([local, alice]);
const { vm, rtcSession, matrixRoom, client } =
getBasicCallViewModelEnvironment([local, alice]);
const { getByLabelText, getByText } = render(
<TestComponent vm={vm} rtcSession={rtcSession} />,
<TestComponent
vm={vm}
rtcSession={rtcSession}
matrixRoom={matrixRoom}
client={client}
/>,
);
await user.click(getByLabelText("Reactions"));
await user.click(getByText("🐶"));
expect(rtcSession.room.client.sendEvent).toHaveBeenCalledWith(
rtcSession.room.roomId,
expect(client.sendEvent).toHaveBeenCalledWith(
matrixRoom.roomId,
ElementCallReactionEventType,
{
"m.relates_to": {
@@ -147,16 +176,22 @@ test("Can react with emoji", async () => {
test("Can fully expand emoji picker", async () => {
const user = userEvent.setup();
const { vm, rtcSession } = getBasicCallViewModelEnvironment([local, alice]);
const { vm, rtcSession, matrixRoom, client } =
getBasicCallViewModelEnvironment([local, alice]);
const { getByLabelText, container, getByText } = render(
<TestComponent vm={vm} rtcSession={rtcSession} />,
<TestComponent
vm={vm}
rtcSession={rtcSession}
matrixRoom={matrixRoom}
client={client}
/>,
);
await user.click(getByLabelText("Reactions"));
await user.click(getByLabelText("Show more"));
expect(container).toMatchSnapshot();
await user.click(getByText("🦗"));
expect(rtcSession.room.client.sendEvent).toHaveBeenCalledWith(
rtcSession.room.roomId,
expect(client.sendEvent).toHaveBeenCalledWith(
matrixRoom.roomId,
ElementCallReactionEventType,
{
"m.relates_to": {
@@ -171,9 +206,15 @@ test("Can fully expand emoji picker", async () => {
test("Can close reaction dialog", async () => {
const user = userEvent.setup();
const { vm, rtcSession } = getBasicCallViewModelEnvironment([local, alice]);
const { vm, rtcSession, matrixRoom, client } =
getBasicCallViewModelEnvironment([local, alice]);
const { getByLabelText, container } = render(
<TestComponent vm={vm} rtcSession={rtcSession} />,
<TestComponent
vm={vm}
rtcSession={rtcSession}
matrixRoom={matrixRoom}
client={client}
/>,
);
await user.click(getByLabelText("Reactions"));
await user.click(getByLabelText("Show more"));
+62 -48
View File
@@ -31,7 +31,7 @@ afterEach(() => {
});
test("handles a hand raised reaction", () => {
const { rtcSession } = getBasicRTCSession([local, alice]);
const { rtcSession, matrixRoom, client } = getBasicRTCSession([local, alice]);
const reactionEventId = "$my_event_id:example.org";
const localTimestamp = new Date();
withTestScheduler(({ schedule, expectObservable }) => {
@@ -39,14 +39,16 @@ test("handles a hand raised reaction", () => {
const { raisedHands$ } = new ReactionsReader(
testScope(),
rtcSession.asMockedSession(),
matrixRoom,
client,
);
schedule("ab", {
a: () => {},
b: () => {
rtcSession.room.emit(
matrixRoom.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: rtcSession.room.roomId,
room_id: matrixRoom.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: EventType.Reaction,
@@ -58,7 +60,7 @@ test("handles a hand raised reaction", () => {
},
},
}),
rtcSession.room,
matrixRoom,
undefined,
false,
{} as IRoomTimelineData,
@@ -80,7 +82,7 @@ test("handles a hand raised reaction", () => {
});
test("handles a redaction", () => {
const { rtcSession } = getBasicRTCSession([local, alice]);
const { rtcSession, matrixRoom, client } = getBasicRTCSession([local, alice]);
const reactionEventId = "$my_event_id:example.org";
const localTimestamp = new Date();
withTestScheduler(({ schedule, expectObservable }) => {
@@ -88,14 +90,16 @@ test("handles a redaction", () => {
const { raisedHands$ } = new ReactionsReader(
testScope(),
rtcSession.asMockedSession(),
matrixRoom,
client,
);
schedule("abc", {
a: () => {},
b: () => {
rtcSession.room.emit(
matrixRoom.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: rtcSession.room.roomId,
room_id: matrixRoom.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: EventType.Reaction,
@@ -107,23 +111,23 @@ test("handles a redaction", () => {
},
},
}),
rtcSession.room,
matrixRoom,
undefined,
false,
{} as IRoomTimelineData,
);
},
c: () => {
rtcSession.room.emit(
matrixRoom.emit(
MatrixRoomEvent.Redaction,
new MatrixEvent({
room_id: rtcSession.room.roomId,
room_id: matrixRoom.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: EventType.RoomRedaction,
redacts: reactionEventId,
}),
rtcSession.room,
matrixRoom,
undefined,
);
},
@@ -144,7 +148,7 @@ test("handles a redaction", () => {
});
test("handles waiting for event decryption", () => {
const { rtcSession } = getBasicRTCSession([local, alice]);
const { rtcSession, matrixRoom, client } = getBasicRTCSession([local, alice]);
const reactionEventId = "$my_event_id:example.org";
const localTimestamp = new Date();
withTestScheduler(({ schedule, expectObservable }) => {
@@ -152,12 +156,14 @@ test("handles waiting for event decryption", () => {
const { raisedHands$ } = new ReactionsReader(
testScope(),
rtcSession.asMockedSession(),
matrixRoom,
client,
);
schedule("abc", {
a: () => {},
b: () => {
const encryptedEvent = new MatrixEvent({
room_id: rtcSession.room.roomId,
room_id: matrixRoom.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: EventType.Reaction,
@@ -171,20 +177,20 @@ test("handles waiting for event decryption", () => {
});
// Should ignore encrypted events that are still encrypting
encryptedEvent["decryptionPromise"] = Promise.resolve();
rtcSession.room.emit(
matrixRoom.emit(
MatrixRoomEvent.Timeline,
encryptedEvent,
rtcSession.room,
matrixRoom,
undefined,
false,
{} as IRoomTimelineData,
);
},
c: () => {
rtcSession.room.client.emit(
client.emit(
MatrixEventEvent.Decrypted,
new MatrixEvent({
room_id: rtcSession.room.roomId,
room_id: matrixRoom.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: EventType.Reaction,
@@ -214,7 +220,7 @@ test("handles waiting for event decryption", () => {
});
test("hands rejecting events without a proper membership", () => {
const { rtcSession } = getBasicRTCSession([local, alice]);
const { rtcSession, matrixRoom, client } = getBasicRTCSession([local, alice]);
const reactionEventId = "$my_event_id:example.org";
const localTimestamp = new Date();
withTestScheduler(({ schedule, expectObservable }) => {
@@ -222,14 +228,16 @@ test("hands rejecting events without a proper membership", () => {
const { raisedHands$ } = new ReactionsReader(
testScope(),
rtcSession.asMockedSession(),
matrixRoom,
client,
);
schedule("ab", {
a: () => {},
b: () => {
rtcSession.room.emit(
matrixRoom.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: rtcSession.room.roomId,
room_id: matrixRoom.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: EventType.Reaction,
@@ -241,7 +249,7 @@ test("hands rejecting events without a proper membership", () => {
},
},
}),
rtcSession.room,
matrixRoom,
undefined,
false,
{} as IRoomTimelineData,
@@ -256,7 +264,7 @@ test("hands rejecting events without a proper membership", () => {
});
test("handles a reaction", () => {
const { rtcSession } = getBasicRTCSession([local, alice]);
const { rtcSession, matrixRoom, client } = getBasicRTCSession([local, alice]);
const reactionEventId = "$my_event_id:example.org";
const reaction = ReactionSet[1];
@@ -268,14 +276,16 @@ test("handles a reaction", () => {
const { reactions$ } = new ReactionsReader(
testScope(),
rtcSession.asMockedSession(),
matrixRoom,
client,
);
schedule(`abc`, {
a: () => {},
b: () => {
rtcSession.room.emit(
matrixRoom.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: rtcSession.room.roomId,
room_id: matrixRoom.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: ElementCallReactionEventType,
@@ -287,7 +297,7 @@ test("handles a reaction", () => {
},
},
}),
rtcSession.room,
matrixRoom,
undefined,
false,
{} as IRoomTimelineData,
@@ -316,7 +326,7 @@ test("handles a reaction", () => {
});
test("ignores bad reaction events", () => {
const { rtcSession } = getBasicRTCSession([local, alice]);
const { rtcSession, room, client } = getBasicRTCSession([local, alice]);
const reactionEventId = "$my_event_id:example.org";
const reaction = ReactionSet[1];
@@ -327,30 +337,32 @@ test("ignores bad reaction events", () => {
const { reactions$ } = new ReactionsReader(
testScope(),
rtcSession.asMockedSession(),
room,
client,
);
schedule("ab", {
a: () => {},
b: () => {
// Missing content
rtcSession.room.emit(
room.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: rtcSession.room.roomId,
room_id: room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: ElementCallReactionEventType,
content: {},
}),
rtcSession.room,
room,
undefined,
false,
{} as IRoomTimelineData,
);
// Wrong relates event
rtcSession.room.emit(
room.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: rtcSession.room.roomId,
room_id: room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: ElementCallReactionEventType,
@@ -362,16 +374,16 @@ test("ignores bad reaction events", () => {
},
},
}),
rtcSession.room,
room,
undefined,
false,
{} as IRoomTimelineData,
);
// Wrong rtc member event
rtcSession.room.emit(
room.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: rtcSession.room.roomId,
room_id: room.roomId,
event_id: reactionEventId,
sender: aliceRtcMember.userId,
type: ElementCallReactionEventType,
@@ -383,16 +395,16 @@ test("ignores bad reaction events", () => {
},
},
}),
rtcSession.room,
room,
undefined,
false,
{} as IRoomTimelineData,
);
// No emoji
rtcSession.room.emit(
room.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: rtcSession.room.roomId,
room_id: room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: ElementCallReactionEventType,
@@ -403,16 +415,16 @@ test("ignores bad reaction events", () => {
},
},
}),
rtcSession.room,
room,
undefined,
false,
{} as IRoomTimelineData,
);
// Invalid emoji
rtcSession.room.emit(
room.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: rtcSession.room.roomId,
room_id: room.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: ElementCallReactionEventType,
@@ -424,7 +436,7 @@ test("ignores bad reaction events", () => {
},
},
}),
rtcSession.room,
room,
undefined,
false,
{} as IRoomTimelineData,
@@ -439,7 +451,7 @@ test("ignores bad reaction events", () => {
});
test("that reactions cannot be spammed", () => {
const { rtcSession } = getBasicRTCSession([local, alice]);
const { rtcSession, matrixRoom, client } = getBasicRTCSession([local, alice]);
const reactionEventId = "$my_event_id:example.org";
const reactionA = ReactionSet[1];
const reactionB = ReactionSet[2];
@@ -452,14 +464,16 @@ test("that reactions cannot be spammed", () => {
const { reactions$ } = new ReactionsReader(
testScope(),
rtcSession.asMockedSession(),
matrixRoom,
client,
);
schedule("abcd", {
a: () => {},
b: () => {
rtcSession.room.emit(
matrixRoom.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: rtcSession.room.roomId,
room_id: matrixRoom.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: ElementCallReactionEventType,
@@ -471,17 +485,17 @@ test("that reactions cannot be spammed", () => {
},
},
}),
rtcSession.room,
matrixRoom,
undefined,
false,
{} as IRoomTimelineData,
);
},
c: () => {
rtcSession.room.emit(
matrixRoom.emit(
MatrixRoomEvent.Timeline,
new MatrixEvent({
room_id: rtcSession.room.roomId,
room_id: matrixRoom.roomId,
event_id: reactionEventId,
sender: localRtcMember.userId,
type: ElementCallReactionEventType,
@@ -493,7 +507,7 @@ test("that reactions cannot be spammed", () => {
},
},
}),
rtcSession.room,
matrixRoom,
undefined,
false,
{} as IRoomTimelineData,
+39 -34
View File
@@ -11,7 +11,12 @@ import {
type MatrixRTCSession,
} from "matrix-js-sdk/lib/matrixrtc";
import { logger } from "matrix-js-sdk/lib/logger";
import { type MatrixEvent, MatrixEventEvent } from "matrix-js-sdk";
import {
type MatrixClient,
type MatrixEvent,
MatrixEventEvent,
type Room,
} from "matrix-js-sdk";
import { type ReactionEventContent } from "matrix-js-sdk/lib/types";
import {
RelationType,
@@ -58,6 +63,28 @@ export class ReactionsReader {
public constructor(
private readonly scope: ObservableScope,
private readonly rtcSession: MatrixRTCSession,
private readonly room: Pick<
Room,
// To ignore events from other rooms
| "roomId"
// The raised hands already in the room, as reactions to memberships
| "relations"
// `on`/`off`, to listen for:
// - `RoomEvent.Timeline` (new reactions)
// - `RoomEvent.Redaction` (lowered hands)
// - `RoomEvent.LocalEchoUpdated` (the real id of our own reactions)
| "on"
| "off"
>,
private readonly client: Pick<
MatrixClient,
// Reactions that arrived encrypted
| "decryptEventIfNeeded"
// `on`/`off`, to listen for:
// - `MatrixEventEvent.Decrypted` (reactions once decrypted)
| "on"
| "off"
>,
) {
// Hide reactions after a given time.
this.reactionsSubject$
@@ -76,47 +103,26 @@ export class ReactionsReader {
// TODO: Convert this class to the functional reactive style and get rid of
// all this manual setup and teardown for event listeners
this.rtcSession.room.on(MatrixRoomEvent.Timeline, this.handleReactionEvent);
this.room.on(MatrixRoomEvent.Timeline, this.handleReactionEvent);
this.scope.onEnd(() =>
this.rtcSession.room.off(
MatrixRoomEvent.Timeline,
this.handleReactionEvent,
),
this.room.off(MatrixRoomEvent.Timeline, this.handleReactionEvent),
);
this.rtcSession.room.on(
MatrixRoomEvent.Redaction,
this.handleReactionEvent,
);
this.room.on(MatrixRoomEvent.Redaction, this.handleReactionEvent);
this.scope.onEnd(() =>
this.rtcSession.room.off(
MatrixRoomEvent.Redaction,
this.handleReactionEvent,
),
this.room.off(MatrixRoomEvent.Redaction, this.handleReactionEvent),
);
this.rtcSession.room.client.on(
MatrixEventEvent.Decrypted,
this.handleReactionEvent,
);
this.client.on(MatrixEventEvent.Decrypted, this.handleReactionEvent);
this.scope.onEnd(() =>
this.rtcSession.room.client.off(
MatrixEventEvent.Decrypted,
this.handleReactionEvent,
),
this.client.off(MatrixEventEvent.Decrypted, this.handleReactionEvent),
);
// We listen for a local echo to get the real event ID, as timeline events
// may still be sending.
this.rtcSession.room.on(
MatrixRoomEvent.LocalEchoUpdated,
this.handleReactionEvent,
);
this.room.on(MatrixRoomEvent.LocalEchoUpdated, this.handleReactionEvent);
this.scope.onEnd(() =>
this.rtcSession.room.off(
MatrixRoomEvent.LocalEchoUpdated,
this.handleReactionEvent,
),
this.room.off(MatrixRoomEvent.LocalEchoUpdated, this.handleReactionEvent),
);
this.rtcSession.on(
@@ -145,7 +151,7 @@ export class ReactionsReader {
membershipEventId: string,
expectedSender: string,
): MatrixEvent | undefined {
const relations = this.rtcSession.room.relations.getChildEventsForEvent(
const relations = this.room.relations.getChildEventsForEvent(
membershipEventId,
RelationType.Annotation,
EventType.Reaction,
@@ -235,9 +241,8 @@ export class ReactionsReader {
* @param event The incoming matrix event, which may or may not be decrypted.
*/
private handleReactionEvent = (event: MatrixEvent): void => {
const room = this.rtcSession.room;
// Decrypted events might come from a different room
if (event.getRoomId() !== room.roomId) return;
if (event.getRoomId() !== this.room.roomId) return;
// Skip any events that are still sending.
if (event.isSending()) return;
@@ -246,7 +251,7 @@ export class ReactionsReader {
// Skip any event without a sender or event ID.
if (!sender || !reactionEventId) return;
room.client
this.client
.decryptEventIfNeeded(event)
.catch((e) => logger.warn(`Failed to decrypt ${event.getId()}`, e));
if (event.isBeingDecrypted() || event.isDecryptionFailure()) return;
+34 -26
View File
@@ -5,7 +5,12 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { EventType, RelationType } from "matrix-js-sdk";
import {
EventType,
type MatrixClient,
RelationType,
type Room,
} from "matrix-js-sdk";
import {
createContext,
use,
@@ -47,19 +52,32 @@ export const useReactionsSender = (): ReactionsSenderContextType => {
export const ReactionsSenderProvider = ({
children,
rtcSession,
room,
client,
vm,
}: {
children: ReactNode;
rtcSession: MatrixRTCSession;
/** The room the reactions are sent in. */
room: Pick<Room, "roomId">;
client: Pick<
MatrixClient,
// Our own membership, which the reactions relate to
| "getUserId"
| "getDeviceId"
// Sending reactions and raising a hand
| "sendEvent"
// Lowering a hand
| "redactEvent"
>;
vm: CallViewModel;
}): JSX.Element => {
const memberships = useMatrixRTCSessionMemberships(rtcSession);
const clientState = useClientState();
const supportsReactions =
clientState?.state === "valid" && clientState.supportedFeatures.reactions;
const room = rtcSession.room;
const myUserId = room.client.getUserId();
const myDeviceId = room.client.getDeviceId();
const myUserId = client.getUserId();
const myDeviceId = client.getDeviceId();
const myMembershipIdentifier = `${myUserId}:${myDeviceId}`;
const myMembershipEvent = useMemo(
@@ -99,8 +117,8 @@ export const ReactionsSenderProvider = ({
if (!myMembershipEvent) {
throw new Error("Cannot find own membership event");
}
const reaction = await room.client.sendEvent(
rtcSession.room.roomId,
const reaction = await client.sendEvent(
room.roomId,
EventType.Reaction,
{
"m.relates_to": {
@@ -116,20 +134,14 @@ export const ReactionsSenderProvider = ({
}
} else {
try {
await room.client.redactEvent(rtcSession.room.roomId, myReactionId);
await client.redactEvent(room.roomId, myReactionId);
logger.debug("Redacted raise hand event");
} catch (ex) {
logger.error("Failed to redact reaction event", myReactionId, ex);
throw ex;
}
}
}, [
myMembershipEvent,
myMembershipIdentifier,
myRaisedHand,
rtcSession,
room,
]);
}, [myMembershipEvent, myMembershipIdentifier, myRaisedHand, client, room]);
const sendReaction = useCallback(
async (reaction: ReactionOption) => {
@@ -140,20 +152,16 @@ export const ReactionsSenderProvider = ({
if (!myMembershipEvent) {
throw new Error("Cannot find own membership event");
}
await room.client.sendEvent(
rtcSession.room.roomId,
ElementCallReactionEventType,
{
"m.relates_to": {
rel_type: RelationType.Reference,
event_id: myMembershipEvent,
},
emoji: reaction.emoji,
name: reaction.name,
await client.sendEvent(room.roomId, ElementCallReactionEventType, {
"m.relates_to": {
rel_type: RelationType.Reference,
event_id: myMembershipEvent,
},
);
emoji: reaction.emoji,
name: reaction.name,
});
},
[myMembershipEvent, myReaction, room, myMembershipIdentifier, rtcSession],
[myMembershipEvent, myReaction, client, room, myMembershipIdentifier],
);
return (
+9
View File
@@ -105,8 +105,13 @@ interface Props {
| "baseUrl"
// Homeserver connection (RTC slot): whether the client is syncing
| "getSyncState"
// Reactions and raised hands: sending, lowering, and decrypting
| "sendEvent"
| "redactEvent"
| "decryptEventIfNeeded"
// `on`/`off`, to listen for:
// - `ClientEvent.Sync` (RTC slot homeserver connection)
// - `MatrixEventEvent.Decrypted` (reactions once decrypted)
| "on"
| "off"
// Profile: display name and avatar, for the settings and the call ended view
@@ -135,12 +140,16 @@ interface Props {
| "getMembersWithMembership"
// Call notifications, for the call view model
| "_unstable_getStickyEvents"
// Raised hands already in the room, for the reactions reader
| "relations"
// `on`/`off`, to listen for:
// - `RoomEvent.Name` (room name)
// - `RoomEvent.CurrentStateUpdated` (avatar and join rule hooks)
// - `RoomStateEvent.Events` (RTC slot status)
// - `RoomStateEvent.Members` (RTC slot and call view model members)
// - `RoomEvent.Timeline` and `RoomStickyEventsEvent.Update` (call notifications)
// - `RoomEvent.Timeline`, `RoomEvent.Redaction` and
// `RoomEvent.LocalEchoUpdated` (reactions and raised hands)
| "on"
| "off"
>;
+4 -4
View File
@@ -137,7 +137,7 @@ function createInCallView(args: CreateInCallViewArgs = {}): RenderResult & {
} {
const mediaDevices = args.mediaDevices ?? mockMediaDevices({});
const muteState = mockMuteStates();
const { vm, footerVm, developerSettingsVm, rtcSession } =
const { vm, footerVm, developerSettingsVm, rtcSession, matrixRoom, client } =
getBasicCallViewModelEnvironment(
[local, alice],
undefined,
@@ -146,8 +146,6 @@ function createInCallView(args: CreateInCallViewArgs = {}): RenderResult & {
);
rtcSession.joined = true;
const room = rtcSession.room;
const client = room.client;
const inCallView = (
<InCallView
@@ -158,7 +156,7 @@ function createInCallView(args: CreateInCallViewArgs = {}): RenderResult & {
footerVm={footerVm}
developerSettingsVm={developerSettingsVm}
matrixInfo={matrixInfo}
matrixRoom={room}
matrixRoom={matrixRoom}
onShareClick={null}
/>
);
@@ -171,6 +169,8 @@ function createInCallView(args: CreateInCallViewArgs = {}): RenderResult & {
<ReactionsSenderProvider
vm={vm}
rtcSession={rtcSession.asMockedSession()}
room={matrixRoom}
client={client}
>
<TooltipProvider>{content}</TooltipProvider>
</ReactionsSenderProvider>
+21 -2
View File
@@ -153,8 +153,13 @@ export interface ActiveCallProps extends Omit<
| "baseUrl"
// Homeserver connection (RTC slot): whether the client is syncing
| "getSyncState"
// Reactions and raised hands: sending, lowering, and decrypting
| "sendEvent"
| "redactEvent"
| "decryptEventIfNeeded"
// `on`/`off`, to listen for:
// - `ClientEvent.Sync` (RTC slot homeserver connection)
// - `MatrixEventEvent.Decrypted` (reactions once decrypted)
| "on"
| "off"
// Profile: display name and avatar, for the settings and the call ended view
@@ -174,10 +179,14 @@ export interface ActiveCallProps extends Omit<
| "getMembersWithMembership"
// Call notifications, for the call view model
| "_unstable_getStickyEvents"
// Raised hands already in the room, for the reactions reader
| "relations"
// `on`/`off`, to listen for:
// - `RoomStateEvent.Events` (RTC slot status)
// - `RoomStateEvent.Members` (RTC slot and call view model members)
// - `RoomEvent.Timeline` and `RoomStickyEventsEvent.Update` (call notifications)
// - `RoomEvent.Timeline`, `RoomEvent.Redaction` and
// `RoomEvent.LocalEchoUpdated` (reactions and raised hands)
| "on"
| "off"
>;
@@ -208,7 +217,12 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
useEffect(() => {
rootLogger.info("START CALL VIEW SCOPE");
const scope = new ObservableScope();
const reactionsReader = new ReactionsReader(scope, props.rtcSession);
const reactionsReader = new ReactionsReader(
scope,
props.rtcSession,
props.matrixRoom,
props.client,
);
const { autoLeaveWhenOthersLeft, waitForCallPickup, sendNotificationType } =
urlParams;
@@ -319,7 +333,12 @@ export const ActiveCall: FC<ActiveCallProps> = (props) => {
if (developerSettingsVm === null) return null;
return (
<ReactionsSenderProvider vm={vm} rtcSession={props.rtcSession}>
<ReactionsSenderProvider
vm={vm}
rtcSession={props.rtcSession}
room={props.matrixRoom}
client={props.client}
>
<InCallView
{...props}
vm={vm}
+2 -2
View File
@@ -52,7 +52,7 @@ export const RoomPage: FC = (): ReactNode => {
// call has a title of its own. So it is set here, for whichever room we have
// got as far as knowing about.
const loadedRoom =
groupCallState.kind === "loaded" ? groupCallState.rtcSession.room : null;
groupCallState.kind === "loaded" ? groupCallState.room : null;
const roomName = useRoomName(loadedRoom);
usePageTitle(
roomName ??
@@ -116,7 +116,7 @@ export const RoomPage: FC = (): ReactNode => {
return (
<CallView
client={client!}
room={groupCallState.rtcSession.room}
room={groupCallState.room}
rtcSession={groupCallState.rtcSession}
isPasswordlessUser={passwordlessUser}
confineToRoom={confineToRoom}
+8 -3
View File
@@ -38,6 +38,7 @@ import { useUrlParams } from "../UrlParams";
export type GroupCallLoaded = {
kind: "loaded";
room: Room;
rtcSession: MatrixRTCSession;
};
@@ -327,13 +328,15 @@ export const useLoadGroupCall = (
return room;
};
const fetchOrCreateGroupCall = async (): Promise<MatrixRTCSession> => {
const fetchOrCreateGroupCall = async (): Promise<
Pick<GroupCallLoaded, "room" | "rtcSession">
> => {
const room = await fetchOrCreateRoom();
activeRoom.current = room;
logger.debug(`Fetched / joined room ${roomIdOrAlias}`);
const rtcSession = client.matrixRTC.getRoomSession(room);
return rtcSession;
return { room, rtcSession };
};
const waitForClientSyncing = async (): Promise<void> => {
@@ -367,7 +370,9 @@ export const useLoadGroupCall = (
logger.log("Start loading group call");
waitForClientSyncing()
.then(fetchOrCreateGroupCall)
.then((rtcSession) => setState({ kind: "loaded", rtcSession }))
.then(({ room, rtcSession }) =>
setState({ kind: "loaded", room, rtcSession }),
)
.then(observeMyMembership)
.catch((error) => setState({ kind: "failed", error }));
}
+26 -14
View File
@@ -5,7 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
Please see LICENSE in the repository root for full details.
*/
import { test, expect } from "vitest";
import { test, expect, vi } from "vitest";
import { act, render, screen } from "@testing-library/react";
import { axe } from "vitest-axe";
import {
@@ -39,18 +39,15 @@ global.IntersectionObserver = class MockIntersectionObserver {
const fakeRtcSession = {
on: () => {},
off: () => {},
room: {
on: () => {},
off: () => {},
client: {
getUserId: () => null,
getDeviceId: () => null,
on: () => {},
off: () => {},
},
},
memberships: [],
} as unknown as MatrixRTCSession;
const fakeRoom = { roomId: "!room:example.org" };
const fakeClient = {
getUserId: () => null,
getDeviceId: () => null,
sendEvent: vi.fn(),
redactEvent: vi.fn(),
};
const callVm = {
reactions$: constant({}),
@@ -68,7 +65,12 @@ test("GridTile displays remote media", async () => {
);
const { container } = render(
<ReactionsSenderProvider vm={callVm} rtcSession={fakeRtcSession}>
<ReactionsSenderProvider
vm={callVm}
rtcSession={fakeRtcSession}
room={fakeRoom}
client={fakeClient}
>
<GridTile
vm={new GridTileViewModel(constant(vm))}
onOpenProfile={() => {}}
@@ -99,7 +101,12 @@ test("GridTile displays local media", async () => {
);
const { container } = render(
<ReactionsSenderProvider vm={callVm} rtcSession={fakeRtcSession}>
<ReactionsSenderProvider
vm={callVm}
rtcSession={fakeRtcSession}
room={fakeRoom}
client={fakeClient}
>
<GridTile
vm={new GridTileViewModel(constant(vm))}
onOpenProfile={() => {}}
@@ -132,7 +139,12 @@ test("GridTile displays ringing media", async () => {
});
const { container } = render(
<ReactionsSenderProvider vm={callVm} rtcSession={fakeRtcSession}>
<ReactionsSenderProvider
vm={callVm}
rtcSession={fakeRtcSession}
room={fakeRoom}
client={fakeClient}
>
<GridTile
vm={new GridTileViewModel(constant(vm))}
onOpenProfile={() => {}}
+37 -32
View File
@@ -53,7 +53,8 @@ export function getBasicRTCSession(
initialRtcMemberships: CallMembership[] = [localRtcMember, aliceRtcMember],
): {
rtcSession: MockRTCSession;
matrixRoom: Room;
room: Room;
client: MatrixClient;
rtcMemberships$: BehaviorSubject<CallMembership[]>;
} {
const matrixRoomId = "!myRoomId:example.com";
@@ -61,36 +62,37 @@ export function getBasicRTCSession(
const roomEmitter = new EventEmitter();
const clientEmitter = new EventEmitter();
const client = {
getUserId: () => localRtcMember.userId,
getDeviceId: () => localRtcMember.deviceId,
getSyncState: () => SyncState.Syncing,
getDomain: () => "example.com",
getAccessToken: () => "fake-token",
sendEvent: vitest.fn().mockResolvedValue({ event_id: "$fake:event" }),
redactEvent: vitest.fn().mockResolvedValue({ event_id: "$fake:event" }),
decryptEventIfNeeded: vitest.fn().mockResolvedValue(undefined),
on: vitest
.fn()
.mockImplementation(
(eventName: string, fn: (...args: unknown[]) => void) => {
clientEmitter.on(eventName, fn);
},
),
emit: (eventName: string, ...args: unknown[]) =>
clientEmitter.emit(eventName, ...args),
off: vitest
.fn()
.mockImplementation(
(eventName: string, fn: (...args: unknown[]) => void) => {
clientEmitter.off(eventName, fn);
},
),
} as Partial<MatrixClient> as MatrixClient;
const matrixRoom = mockMatrixRoom({
relations: {
getChildEventsForEvent: vitest.fn(),
} as Partial<RelationsContainer> as RelationsContainer,
client: {
getUserId: () => localRtcMember.userId,
getDeviceId: () => localRtcMember.deviceId,
getSyncState: () => SyncState.Syncing,
getDomain: () => "example.com",
getAccessToken: () => "fake-token",
sendEvent: vitest.fn().mockResolvedValue({ event_id: "$fake:event" }),
redactEvent: vitest.fn().mockResolvedValue({ event_id: "$fake:event" }),
decryptEventIfNeeded: vitest.fn().mockResolvedValue(undefined),
on: vitest
.fn()
.mockImplementation(
(eventName: string, fn: (...args: unknown[]) => void) => {
clientEmitter.on(eventName, fn);
},
),
emit: (eventName: string, ...args: unknown[]) =>
clientEmitter.emit(eventName, ...args),
off: vitest
.fn()
.mockImplementation(
(eventName: string, fn: (...args: unknown[]) => void) => {
clientEmitter.off(eventName, fn);
},
),
} as Partial<MatrixClient> as MatrixClient,
client,
getMember: (userId) => matrixRoomMembers.get(userId) ?? null,
getMembers: () => Array.from(matrixRoomMembers.values()),
getMembersWithMembership: () => Array.from(matrixRoomMembers.values()),
@@ -125,6 +127,7 @@ export function getBasicRTCSession(
return {
rtcSession: fakeRtcSession,
matrixRoom,
client,
rtcMemberships$,
};
}
@@ -146,13 +149,13 @@ export function getBasicCallViewModelEnvironment(
developerSettingsVm: ViewModel<DeveloperSettingsSnapshot>;
rtcMemberships$: BehaviorSubject<CallMembership[]>;
rtcSession: MockRTCSession;
matrixRoom: Room;
client: MatrixClient;
handRaisedSubject$: BehaviorSubject<Record<string, RaisedHandInfo>>;
reactionsSubject$: BehaviorSubject<Record<string, ReactionInfo>>;
} {
const { rtcSession, matrixRoom, rtcMemberships$ } = getBasicRTCSession(
members,
initialRtcMemberships,
);
const { rtcSession, matrixRoom, client, rtcMemberships$ } =
getBasicRTCSession(members, initialRtcMemberships);
const handRaisedSubject$ = new BehaviorSubject({});
const reactionsSubject$ = new BehaviorSubject({});
@@ -199,7 +202,7 @@ export function getBasicCallViewModelEnvironment(
{
rtcParticipation,
matrixRoom,
client: matrixRoom.client,
client,
mediaDevices,
muteStates,
encryptionSystem: { kind: E2eeType.PER_PARTICIPANT },
@@ -230,6 +233,8 @@ export function getBasicCallViewModelEnvironment(
developerSettingsVm: createDeveloperSettingsTabViewModel(testScope(), vm),
rtcMemberships$,
rtcSession,
matrixRoom,
client,
handRaisedSubject$: handRaisedSubject$,
reactionsSubject$: reactionsSubject$,
};