Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Make CallHandler more EventEmittery #6704

Merged
merged 19 commits into from
Nov 30, 2021
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
61d5bd8
sharedInstance() -> instance
SimonBrandner Aug 28, 2021
790d079
Use CallState event instead of dispatching
SimonBrandner Aug 28, 2021
2d6160c
Simplifie some code
SimonBrandner Aug 28, 2021
c96ecc3
Use a method to start a call instead of the dispatcher
SimonBrandner Aug 28, 2021
4424371
Use a method instead of place_conference_call
SimonBrandner Aug 28, 2021
447f4d6
Make terminateCallApp() and hangupCallApp() public
SimonBrandner Aug 28, 2021
c9e42bb
Use hangupAllCalls() instead of the dispatcher
SimonBrandner Aug 28, 2021
09882b2
Make dialNumber(), startTransferToMatrixID() and startTransferToPhone…
SimonBrandner Aug 28, 2021
9b86230
Use answerCall() instead of using the dispatcher
SimonBrandner Aug 28, 2021
969e7bc
Use hangupOrReject() instead of the dispatcher
SimonBrandner Aug 28, 2021
b8dcf1c
Update docs
SimonBrandner Aug 28, 2021
ec9123c
Merge remote-tracking branch 'upstream/develop' into task/call-handle…
SimonBrandner Sep 11, 2021
be5619f
Improve TS
SimonBrandner Sep 11, 2021
2acc662
Dispatch call_state, see https://github.com/vector-im/element-web/pul…
SimonBrandner Sep 11, 2021
c1c91f3
Merge remote-tracking branch 'upstream/develop' into task/call-handle…
SimonBrandner Sep 22, 2021
ea6c6c9
Merge remote-tracking branch 'upstream/develop' into task/call-handle…
SimonBrandner Oct 25, 2021
216cd49
Merge remote-tracking branch 'upstream/develop' into task/call-handle…
SimonBrandner Nov 17, 2021
d20bba0
Merge remote-tracking branch 'upstream/develop' into task/call-handle…
SimonBrandner Nov 26, 2021
3de75e7
Add missing import
SimonBrandner Nov 26, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
375 changes: 143 additions & 232 deletions src/CallHandler.tsx

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/Lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -784,7 +784,7 @@ async function startMatrixClient(startSyncing = true): Promise<void> {
DMRoomMap.makeShared().start();
IntegrationManagers.sharedInstance().startWatching();
ActiveWidgetStore.start();
CallHandler.sharedInstance().start();
CallHandler.instance.start();

// Start Mjolnir even though we haven't checked the feature flag yet. Starting
// the thing just wastes CPU cycles, but should result in no actual functionality
Expand Down Expand Up @@ -885,7 +885,7 @@ async function clearStorage(opts?: { deleteEverything?: boolean }): Promise<void
*/
export function stopMatrixClient(unsetClient = true): void {
Notifier.stop();
CallHandler.sharedInstance().stop();
CallHandler.instance.stop();
UserActivity.sharedInstance().stop();
TypingStore.sharedInstance().reset();
Presence.stop();
Expand Down
6 changes: 3 additions & 3 deletions src/SlashCommands.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1006,7 +1006,7 @@ export const Commands = [

return success((async () => {
if (isPhoneNumber) {
const results = await CallHandler.sharedInstance().pstnLookup(this.state.value);
const results = await CallHandler.instance.pstnLookup(this.state.value);
if (!results || results.length === 0 || !results[0].userid) {
throw new Error("Unable to find Matrix ID for phone number");
}
Expand Down Expand Up @@ -1056,7 +1056,7 @@ export const Commands = [
description: _td("Places the call in the current room on hold"),
category: CommandCategories.other,
runFn: function(roomId, args) {
const call = CallHandler.sharedInstance().getCallForRoom(roomId);
const call = CallHandler.instance.getCallForRoom(roomId);
if (!call) {
return reject("No active call in this room");
}
Expand All @@ -1069,7 +1069,7 @@ export const Commands = [
description: _td("Takes the call in the current room off hold"),
category: CommandCategories.other,
runFn: function(roomId, args) {
const call = CallHandler.sharedInstance().getCallForRoom(roomId);
const call = CallHandler.instance.getCallForRoom(roomId);
if (!call) {
return reject("No active call in this room");
}
Expand Down
6 changes: 3 additions & 3 deletions src/VoipUserMapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export default class VoipUserMapper {
}

private async userToVirtualUser(userId: string): Promise<string> {
const results = await CallHandler.sharedInstance().sipVirtualLookup(userId);
const results = await CallHandler.instance.sipVirtualLookup(userId);
if (results.length === 0 || !results[0].fields.lookup_success) return null;
return results[0].userid;
}
Expand Down Expand Up @@ -95,11 +95,11 @@ export default class VoipUserMapper {
}

public async onNewInvitedRoom(invitedRoom: Room): Promise<void> {
if (!CallHandler.sharedInstance().getSupportsVirtualRooms()) return;
if (!CallHandler.instance.getSupportsVirtualRooms()) return;

const inviterId = invitedRoom.getDMInviter();
console.log(`Checking virtual-ness of room ID ${invitedRoom.roomId}, invited by ${inviterId}`);
const result = await CallHandler.sharedInstance().sipNativeLookup(inviterId);
const result = await CallHandler.instance.sipNativeLookup(inviterId);
if (result.length === 0) {
return;
}
Expand Down
25 changes: 12 additions & 13 deletions src/components/structures/CallEventGrouper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ import { CallEvent, CallState, CallType, MatrixCall } from "matrix-js-sdk/src/we
import CallHandler, { CallHandlerEvent } from '../../CallHandler';
import { EventEmitter } from 'events';
import { MatrixClientPeg } from "../../MatrixClientPeg";
import defaultDispatcher from "../../dispatcher/dispatcher";

export enum CallEventGrouperEvent {
StateChanged = "state_changed",
Expand Down Expand Up @@ -51,8 +50,8 @@ export default class CallEventGrouper extends EventEmitter {
constructor() {
super();

CallHandler.sharedInstance().addListener(CallHandlerEvent.CallsChanged, this.setCall);
CallHandler.sharedInstance().addListener(CallHandlerEvent.SilencedCallsChanged, this.onSilencedCallsChanged);
CallHandler.instance.addListener(CallHandlerEvent.CallsChanged, this.setCall);
CallHandler.instance.addListener(CallHandlerEvent.SilencedCallsChanged, this.onSilencedCallsChanged);
}

private get invite(): MatrixEvent {
Expand Down Expand Up @@ -108,8 +107,12 @@ export default class CallEventGrouper extends EventEmitter {
return [...this.events][0].getContent().call_id;
}

private get roomId(): string {
return [...this.events][0]?.getRoomId();
}

private onSilencedCallsChanged = () => {
const newState = CallHandler.sharedInstance().isCallSilenced(this.callId);
const newState = CallHandler.instance.isCallSilenced(this.callId);
this.emit(CallEventGrouperEvent.SilencedChanged, newState);
};

Expand All @@ -122,18 +125,14 @@ export default class CallEventGrouper extends EventEmitter {
};

public callBack = () => {
defaultDispatcher.dispatch({
action: 'place_call',
type: this.isVoice ? CallType.Voice : CallType.Video,
room_id: [...this.events][0]?.getRoomId(),
});
CallHandler.instance.placeCall(this.roomId, this.isVoice ? CallType.Voice : CallType.Video);
};

public toggleSilenced = () => {
const silenced = CallHandler.sharedInstance().isCallSilenced(this.callId);
const silenced = CallHandler.instance.isCallSilenced(this.callId);
silenced ?
CallHandler.sharedInstance().unSilenceCall(this.callId) :
CallHandler.sharedInstance().silenceCall(this.callId);
CallHandler.instance.unSilenceCall(this.callId) :
CallHandler.instance.silenceCall(this.callId);
};

private setCallListeners() {
Expand All @@ -158,7 +157,7 @@ export default class CallEventGrouper extends EventEmitter {
private setCall = () => {
if (this.call) return;

this.call = CallHandler.sharedInstance().getCallById(this.callId);
this.call = CallHandler.instance.getCallById(this.callId);
this.setCallListeners();
this.setState();
};
Expand Down
2 changes: 1 addition & 1 deletion src/components/structures/LeftPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ export default class LeftPanel extends React.Component<IProps, IState> {

// If we have dialer support, show a button to bring up the dial pad
// to start a new call
if (CallHandler.sharedInstance().getSupportsPstnProtocol()) {
if (CallHandler.instance.getSupportsPstnProtocol()) {
dialPadButton =
<AccessibleTooltipButton
className={classNames("mx_LeftPanel_dialPadButton", {})}
Expand Down
25 changes: 10 additions & 15 deletions src/components/structures/LoggedInView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ import { getKeyBindingsManager, NavigationAction, RoomAction } from '../../KeyBi
import { IOpts } from "../../createRoom";
import SpacePanel from "../views/spaces/SpacePanel";
import { replaceableComponent } from "../../utils/replaceableComponent";
import CallHandler from '../../CallHandler';
import CallHandler, { CallHandlerEvent } from '../../CallHandler';
import { MatrixCall } from 'matrix-js-sdk/src/webrtc/call';
import AudioFeedArrayForCall from '../views/voip/AudioFeedArrayForCall';
import { OwnProfileStore } from '../../stores/OwnProfileStore';
Expand Down Expand Up @@ -165,7 +165,7 @@ class LoggedInView extends React.Component<IProps, IState> {
// use compact timeline view
useCompactLayout: SettingsStore.getValue('useCompactLayout'),
usageLimitDismissed: false,
activeCalls: CallHandler.sharedInstance().getAllActiveCalls(),
activeCalls: CallHandler.instance.getAllActiveCalls(),
};

// stash the MatrixClient in case we log out before we are unmounted
Expand All @@ -182,7 +182,7 @@ class LoggedInView extends React.Component<IProps, IState> {

componentDidMount() {
document.addEventListener('keydown', this.onNativeKeyDown, false);
this.dispatcherRef = dis.register(this.onAction);
CallHandler.instance.addListener(CallHandlerEvent.CallState, this.onCallState);

this.updateServerNoticeEvents();

Expand Down Expand Up @@ -213,6 +213,7 @@ class LoggedInView extends React.Component<IProps, IState> {

componentWillUnmount() {
document.removeEventListener('keydown', this.onNativeKeyDown, false);
CallHandler.instance.removeListener(CallHandlerEvent.CallState, this.onCallState);
dis.unregister(this.dispatcherRef);
this._matrixClient.removeListener("accountData", this.onAccountData);
this._matrixClient.removeListener("sync", this.onSync);
Expand All @@ -223,6 +224,12 @@ class LoggedInView extends React.Component<IProps, IState> {
this.resizer.detach();
}

private onCallState = (): void => {
const activeCalls = CallHandler.instance.getAllActiveCalls();
if (activeCalls === this.state.activeCalls) return;
this.setState({ activeCalls });
};

private refreshBackgroundImage = async (): Promise<void> => {
let backgroundImage = SettingsStore.getValue("RoomList.backgroundImage");
if (backgroundImage) {
Expand All @@ -234,18 +241,6 @@ class LoggedInView extends React.Component<IProps, IState> {
this.setState({ backgroundImage });
};

private onAction = (payload): void => {
switch (payload.action) {
case 'call_state': {
const activeCalls = CallHandler.sharedInstance().getAllActiveCalls();
if (activeCalls !== this.state.activeCalls) {
this.setState({ activeCalls });
}
break;
}
}
};

public canResetTimelineInRoom = (roomId: string) => {
if (!this._roomView.current) {
return true;
Expand Down
3 changes: 2 additions & 1 deletion src/components/structures/MatrixChat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ import { makeRoomPermalink } from "../../utils/permalinks/Permalinks";
import { copyPlaintext } from "../../utils/strings";
import { PosthogAnalytics } from '../../PosthogAnalytics';
import { initSentry } from "../../sentry";
import CallHandler from "../../CallHandler";

/** constants for MatrixChat.state.view */
export enum Views {
Expand Down Expand Up @@ -594,7 +595,7 @@ export default class MatrixChat extends React.PureComponent<IProps, IState> {
}
break;
case 'logout':
dis.dispatch({ action: "hangup_all" });
CallHandler.instance.hangupAllCalls();
Lifecycle.logout();
break;
case 'require_registration':
Expand Down
41 changes: 17 additions & 24 deletions src/components/structures/RoomView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import { RoomPermalinkCreator } from '../../utils/permalinks/Permalinks';
import ResizeNotifier from '../../utils/ResizeNotifier';
import ContentMessages from '../../ContentMessages';
import Modal from '../../Modal';
import CallHandler, { PlaceCallType } from '../../CallHandler';
import CallHandler, { CallHandlerEvent } from '../../CallHandler';
import dis from '../../dispatcher/dispatcher';
import * as Rooms from '../../Rooms';
import eventSearch, { searchPagination } from '../../Searching';
Expand Down Expand Up @@ -66,7 +66,7 @@ import { IOOBData, IThreepidInvite } from "../../stores/ThreepidInviteStore";
import EffectsOverlay from "../views/elements/EffectsOverlay";
import { containsEmoji } from '../../effects/utils';
import { CHAT_EFFECTS } from '../../effects';
import { CallState, MatrixCall } from "matrix-js-sdk/src/webrtc/call";
import { CallState, CallType, MatrixCall } from "matrix-js-sdk/src/webrtc/call";
import WidgetStore from "../../stores/WidgetStore";
import { UPDATE_EVENT } from "../../stores/AsyncStore";
import Notifier from "../../Notifier";
Expand Down Expand Up @@ -583,6 +583,7 @@ export default class RoomView extends React.Component<IProps, IState> {
}

componentDidUpdate() {
CallHandler.instance.addListener(CallHandlerEvent.CallState, this.onCallState);
if (this.roomView.current) {
const roomView = this.roomView.current;
if (!roomView.ondrop) {
Expand Down Expand Up @@ -613,6 +614,8 @@ export default class RoomView extends React.Component<IProps, IState> {
// (We could use isMounted, but facebook have deprecated that.)
this.unmounted = true;

CallHandler.instance.removeListener(CallHandlerEvent.CallState, this.onCallState);

// update the scroll map before we get unmounted
if (this.state.roomId) {
RoomScrollStateStore.setScrollState(this.state.roomId, this.getScrollState());
Expand Down Expand Up @@ -739,6 +742,15 @@ export default class RoomView extends React.Component<IProps, IState> {
}
};

private onCallState = (roomId: string): void => {
// don't filter out payloads for room IDs other than props.room because
// we may be interested in the conf 1:1 room

if (!roomId) return;
const call = this.getCallForRoom();
this.setState({ callState: call ? call.state : null });
};

private onAction = payload => {
switch (payload.action) {
case 'message_sent':
Expand All @@ -760,21 +772,6 @@ export default class RoomView extends React.Component<IProps, IState> {
case Action.UploadCanceled:
this.forceUpdate();
break;
case 'call_state': {
// don't filter out payloads for room IDs other than props.room because
// we may be interested in the conf 1:1 room

if (!payload.room_id) {
return;
}

const call = this.getCallForRoom();

this.setState({
callState: call ? call.state : null,
});
break;
}
case 'appsDrawer':
this.setState({
showApps: payload.show,
Expand Down Expand Up @@ -1432,12 +1429,8 @@ export default class RoomView extends React.Component<IProps, IState> {
return ret;
}

private onCallPlaced = (type: PlaceCallType) => {
dis.dispatch({
action: 'place_call',
type: type,
room_id: this.state.room.roomId,
});
private onCallPlaced = (type: CallType): void => {
CallHandler.instance.placeCall(this.state.room?.roomId, type);
};

private onSettingsClick = () => {
Expand Down Expand Up @@ -1675,7 +1668,7 @@ export default class RoomView extends React.Component<IProps, IState> {
if (!this.state.room) {
return null;
}
return CallHandler.sharedInstance().getCallForRoom(this.state.room.roomId);
return CallHandler.instance.getCallForRoom(this.state.room.roomId);
}

// this has to be a proper method rather than an unnamed function,
Expand Down
2 changes: 1 addition & 1 deletion src/components/views/context_menus/CallContextMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export default class CallContextMenu extends React.Component<IProps> {
};

onUnholdClick = () => {
CallHandler.sharedInstance().setActiveCallRoomId(this.props.call.roomId);
CallHandler.instance.setActiveCallRoomId(this.props.call.roomId);

this.props.onFinished();
};
Expand Down
24 changes: 11 additions & 13 deletions src/components/views/dialogs/InviteDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ import { copyPlaintext, selectText } from "../../../utils/strings";
import * as ContextMenu from "../../structures/ContextMenu";
import { toRightOf } from "../../structures/ContextMenu";
import GenericTextContextMenu from "../context_menus/GenericTextContextMenu";
import { TransferCallPayload } from '../../../dispatcher/payloads/TransferCallPayload';
import Field from '../elements/Field';
import TabbedView, { Tab, TabLocation } from '../../structures/TabbedView';
import Dialpad from '../voip/DialPad';
Expand All @@ -72,6 +71,7 @@ import Spinner from "../elements/Spinner";
import BaseDialog from "./BaseDialog";
import DialPadBackspaceButton from "../elements/DialPadBackspaceButton";
import SpaceStore from "../../../stores/SpaceStore";
import CallHandler from "../../../CallHandler";

// we have a number of types defined from the Matrix spec which can't reasonably be altered here.
/* eslint-disable camelcase */
Expand Down Expand Up @@ -804,19 +804,17 @@ export default class InviteDialog extends React.PureComponent<IInviteDialogProps
return;
}

dis.dispatch({
action: Action.TransferCallToMatrixID,
call: this.props.call,
destination: targetIds[0],
consultFirst: this.state.consultFirst,
} as TransferCallPayload);
CallHandler.instance.startTransferToMatrixID(
this.props.call,
targetIds[0],
this.state.consultFirst,
);
} else {
dis.dispatch({
action: Action.TransferCallToPhoneNumber,
call: this.props.call,
destination: this.state.dialPadValue,
consultFirst: this.state.consultFirst,
} as TransferCallPayload);
CallHandler.instance.startTransferToPhoneNumber(
this.props.call,
this.state.dialPadValue,
this.state.consultFirst,
);
}
this.props.onFinished();
};
Expand Down
3 changes: 2 additions & 1 deletion src/components/views/elements/AppTile.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import { MatrixCapabilities } from "matrix-widget-api";
import RoomWidgetContextMenu from "../context_menus/WidgetContextMenu";
import WidgetAvatar from "../avatars/WidgetAvatar";
import { replaceableComponent } from "../../../utils/replaceableComponent";
import CallHandler from '../../../CallHandler';

@replaceableComponent("views.elements.AppTile")
export default class AppTile extends React.Component {
Expand Down Expand Up @@ -213,7 +214,7 @@ export default class AppTile extends React.Component {
}

if (WidgetType.JITSI.matches(this.props.app.type)) {
dis.dispatch({ action: 'hangup_conference' });
CallHandler.instance.hangupCallApp(this.props.room.roomId);
}

// Delete the widget from the persisted store for good measure.
Expand Down
Loading