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

Commit

Permalink
Make CallHandler more EventEmittery (#6704)
Browse files Browse the repository at this point in the history
* sharedInstance() -> instance

Signed-off-by: Šimon Brandner <[email protected]>

* Use CallState event instead of dispatching

Signed-off-by: Šimon Brandner <[email protected]>

* Simplifie some code

Signed-off-by: Šimon Brandner <[email protected]>

* Use a method to start a call instead of the dispatcher

Signed-off-by: Šimon Brandner <[email protected]>

* Use a method instead of place_conference_call

Signed-off-by: Šimon Brandner <[email protected]>

* Make terminateCallApp() and hangupCallApp() public

Signed-off-by: Šimon Brandner <[email protected]>

* Use hangupAllCalls() instead of the dispatcher

Signed-off-by: Šimon Brandner <[email protected]>

* Make dialNumber(), startTransferToMatrixID() and startTransferToPhoneNumber() public instead of using the dispatcher

Signed-off-by: Šimon Brandner <[email protected]>

* Use answerCall() instead of using the dispatcher

Signed-off-by: Šimon Brandner <[email protected]>

* Use hangupOrReject() instead of the dispatcher

Signed-off-by: Šimon Brandner <[email protected]>

* Update docs

Signed-off-by: Šimon Brandner <[email protected]>

* Improve TS

Signed-off-by: Šimon Brandner <[email protected]>

* Dispatch call_state, see element-hq/element-web#18823 (comment)

Signed-off-by: Šimon Brandner <[email protected]>

* Add missing import

Signed-off-by: Šimon Brandner <[email protected]>
  • Loading branch information
SimonBrandner authored Nov 30, 2021
1 parent e3187ed commit cbb34d8
Show file tree
Hide file tree
Showing 23 changed files with 287 additions and 498 deletions.
415 changes: 167 additions & 248 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 @@ -794,7 +794,7 @@ async function startMatrixClient(startSyncing = true): Promise<void> {
DMRoomMap.makeShared().start();
IntegrationManagers.sharedInstance().startWatching();
ActiveWidgetStore.instance.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 @@ -897,7 +897,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 @@ -1037,7 +1037,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 @@ -1089,7 +1089,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 @@ -1103,7 +1103,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 @@ -36,7 +36,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 @@ -97,11 +97,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();
logger.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
37 changes: 13 additions & 24 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 @@ -52,8 +51,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 @@ -114,41 +113,31 @@ export default class CallEventGrouper extends EventEmitter {
}

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

private onLengthChanged = (length: number): void => {
this.emit(CallEventGrouperEvent.LengthChanged, length);
};

public answerCall = () => {
defaultDispatcher.dispatch({
action: 'answer',
room_id: this.roomId,
});
public answerCall = (): void => {
CallHandler.instance.answerCall(this.roomId);
};

public rejectCall = () => {
defaultDispatcher.dispatch({
action: 'reject',
room_id: this.roomId,
});
public rejectCall = (): void => {
CallHandler.instance.hangupOrReject(this.roomId, true);
};

public callBack = () => {
defaultDispatcher.dispatch({
action: 'place_call',
type: this.isVoice ? CallType.Voice : CallType.Video,
room_id: this.roomId,
});
public callBack = (): void => {
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 @@ -174,7 +163,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 @@ -340,7 +340,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 @@ -164,7 +164,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 @@ -181,7 +181,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 @@ -212,6 +212,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 @@ -222,6 +223,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 @@ -233,18 +240,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 @@ -108,6 +108,7 @@ import { makeRoomPermalink } from "../../utils/permalinks/Permalinks";
import { copyPlaintext } from "../../utils/strings";
import { PosthogAnalytics } from '../../PosthogAnalytics';
import { initSentry } from "../../sentry";
import CallHandler from "../../CallHandler";

import { logger } from "matrix-js-sdk/src/logger";
import { showSpaceInvite } from "../../utils/space";
Expand Down Expand Up @@ -604,7 +605,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 @@ -669,6 +669,7 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
}

componentDidUpdate() {
CallHandler.instance.addListener(CallHandlerEvent.CallState, this.onCallState);
if (this.roomView.current) {
const roomView = this.roomView.current;
if (!roomView.ondrop) {
Expand Down Expand Up @@ -699,6 +700,8 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
// (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 @@ -822,6 +825,15 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
}
};

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 @@ -843,21 +855,6 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
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 @@ -1531,12 +1528,8 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
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 onAppsClick = () => {
Expand Down Expand Up @@ -1748,7 +1741,7 @@ export class RoomView extends React.Component<IRoomProps, IRoomState> {
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/spaces/SpaceStore";
import CallHandler from "../../../CallHandler";

import { logger } from "matrix-js-sdk/src/logger";

Expand Down Expand Up @@ -806,19 +806,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
Loading

0 comments on commit cbb34d8

Please sign in to comment.