Skip to content

Commit

Permalink
fix: minor fixes in subscription
Browse files Browse the repository at this point in the history
  • Loading branch information
muke1908 committed Sep 21, 2024
1 parent a468e32 commit be942c7
Show file tree
Hide file tree
Showing 4 changed files with 71 additions and 38 deletions.
25 changes: 16 additions & 9 deletions client/src/components/Messaging/UserStatusInfo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import ThemeToggle from "../ThemeToggle/index";
import imageRetryIcon from "./assets/image-retry.png";
import DeleteChatLink from "../DeleteChatLink";
import Button from "../Button";
import { IChatE2EE } from "@chat-e2ee/service";
import { IChatE2EE, IE2ECall } from "@chat-e2ee/service";

export const UserStatusInfo = ({
online,
Expand All @@ -19,9 +19,9 @@ export const UserStatusInfo = ({
handleDeleteLink: any;
chate2ee: IChatE2EE
}) => {
const [ call, setCall ] = useState(null);
const [ call, setCall ] = useState<IE2ECall>(null);
const [loading, setLoading] = useState(false);
const [ callState, setCallState ] = useState(undefined);
const [ callState, setCallState ] = useState<RTCPeerConnectionState>(undefined);

useEffect(() => {
chate2ee.on('call-added', (call) => {
Expand All @@ -31,20 +31,27 @@ export const UserStatusInfo = ({
chate2ee.on('call-removed', () => {
setCall(null);
});

chate2ee.on('pc-state-changed', (state) => {
setCallState(state);
});
}, [chate2ee]);

useEffect(() => {
if(call) {
call.on('state-changed', () => {
setCallState(call.state);
})
}
}, [call])
const makeCall = async () => {
if(call) {
console.error('call is already active');
return;
}

const newCall = await chate2ee.startCall();
setCall(newCall);
try {
const newCall = await chate2ee.startCall();
setCall(newCall);
}catch(err) {
alert('Not supported.');
}
}

const stopCall = async() => {
Expand Down
15 changes: 6 additions & 9 deletions service/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,14 @@ const call = await chatInstance.startCall();
// end the call
call.endCall();
// call state change
call.on('state-changed', () => {
console.log('Call state changed', call.state)
})
```


---
### Event listeners:

Expand All @@ -83,7 +89,6 @@ chate2ee.on(events, callback);
`delivered` - a message is delivered to the receiver callback returns the ID of the message that's delivered.
`call-added` - a new incoming call.
`call-removed` - an active call is removed/disconnected.
`pc-state-changed` - peer connection state changed.

New message:

Expand Down Expand Up @@ -131,14 +136,6 @@ chate2ee.on('call-removed', () => {
console.log('Call removed')
})
```

Call state change:
```
chate2ee.on('pc-state-changed', (state: RTCPeerConnectionState) => {
console.log('Call state', state)
})
```

---

**chatInstance.getLink():**
Expand Down
21 changes: 12 additions & 9 deletions service/src/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Logger } from './utils/logger';
export { setConfig } from './configContext';
import { generateUUID } from './utils/uuid';
import { WebRTCCall, E2ECall, peerConnectionEvents, PeerConnectionEventType } from './webrtc';
export { IE2ECall } from './webrtc';

export const utils = {
decryptMessage: (ciphertext: string, privateKey: string) => _cryptoUtils.decryptMessage(ciphertext, privateKey),
Expand Down Expand Up @@ -53,12 +54,13 @@ class ChatE2EE implements IChatE2EE {

private symEncryption = new AesGcmEncryption();

private onPcConnectionChanged(state: RTCPeerConnectionState): void {
this.callSubscriptions.get("pc-state-changed")?.forEach((cb) => cb(state));
if(state === 'failed' || state === 'closed') {
this.callLogger.log(`Ending call, RTCPeerConnectionState: ${state}`);
this.endCall();
}
private setupCallSubs(call: WebRTCCall): void {
call.on('state-changed', (state) => {
if(state === 'failed' || state === 'closed') {
this.callLogger.log(`Ending call, RTCPeerConnectionState: ${state}`);
this.endCall();
}
})
}
constructor(config?: Partial<configType>) {
config && setConfig(config);
Expand Down Expand Up @@ -234,8 +236,9 @@ class ChatE2EE implements IChatE2EE {
if(this.call) {
throw new Error('Call already active');
}
const call = new E2ECall(this.getWebRtcCall());
await call.startCall();
const webrtcCall = this.getWebRtcCall();
await webrtcCall.startCall()
const call = new E2ECall(webrtcCall);
return call;
}

Expand Down Expand Up @@ -271,12 +274,12 @@ class ChatE2EE implements IChatE2EE {
private getWebRtcCall(): WebRTCCall {
this.checkInitialized();
this.call = new WebRTCCall(
this.onPcConnectionChanged.bind(this),
this.symEncryption,
this.userId,
this.channelId,
this.callLogger,
);
this.setupCallSubs(this.call)
return this.call;
}
}
Expand Down
48 changes: 37 additions & 11 deletions service/src/webrtc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,44 @@ import { AesGcmEncryption } from "./cryptoAES";
import { Logger } from "./utils/logger";
import { webrtcSession } from "./webrtcSession";

export interface IE2ECall {
on(event: callEvents, cb: () => void): void;
state: RTCPeerConnectionState;
endCall(): Promise<void>;
}

interface SignalData {
type: RTCSdpType;
sdp: string;
}
export type PeerConnectionEventType = "call-added" | "call-removed" | "pc-state-changed";
export const peerConnectionEvents: PeerConnectionEventType[] = [ "call-added", "call-removed", "pc-state-changed" ];
export type callEvents = 'state-changed';
export type PeerConnectionEventType = "call-added" | "call-removed";
export const peerConnectionEvents: PeerConnectionEventType[] = [ "call-added", "call-removed" ];

export class WebRTCCall {
private peer: Peer;
private subs: Map<callEvents, Set<Function>> = new Map()

public static isSupported(): boolean {
return !!(RTCRtpSender.prototype as any).createEncodedStreams;
}

constructor(onPcConnectionChanged: (state: RTCPeerConnectionState) => void, encryption: AesGcmEncryption, sender: string, channel: string, private logger: Logger) {
public on(listener: callEvents, cb: (state: RTCPeerConnectionState) => void): void {
const sub = this.subs.get(listener);
if (sub) {
if (sub.has(cb)) {
return;
}
sub.add(cb);
} else {
this.subs.set(listener, new Set([cb]));
}
}

constructor(encryption: AesGcmEncryption, sender: string, channel: string, private logger: Logger) {
this.logger.log('Creating WebRTCCall');
this.peer = new Peer(
onPcConnectionChanged,
() => this.subs,
encryption,
sender,
channel,
Expand All @@ -37,7 +58,9 @@ export class WebRTCCall {

public endCall(): void {
this.logger.log('endCall');
this.subs.clear();
this.peer?.dispose();
this.peer = null;
}

public signal(data: SignalData): void {
Expand All @@ -58,7 +81,7 @@ class Peer {

private localStreamAcquisatonPromise?: Promise<void>
constructor(
private onPcConnectionChanged: (state: RTCPeerConnectionState) => void,
private subCtx: () => Map<callEvents, Set<Function>>,
private encryption: AesGcmEncryption,
private sender: string,
private channel: string,
Expand All @@ -83,7 +106,9 @@ class Peer {
this.pc.onconnectionstatechange = () => {
this.logger.log('Peer Connection State: ', this.pc.connectionState);
this.state = this.pc.connectionState;
this.onPcConnectionChanged(this.state);
const sub = this.subCtx();
const stateChangeHanlder = sub.get('state-changed');
stateChangeHanlder?.forEach(cb => cb(this.state));
};

this.pc.onicecandidate = (event) => {
Expand Down Expand Up @@ -165,7 +190,8 @@ class Peer {
this.audioEl = null;
}
this.logger.log('Dispose');
this.pc.close();
this.pc?.close();
this.pc = null;
}

private async addLocalAudioTracks(): Promise<void> {
Expand Down Expand Up @@ -278,14 +304,14 @@ class Peer {
}

// Public facing class
export class E2ECall {
export class E2ECall implements IE2ECall {
constructor(private readonly webRtcCall: WebRTCCall) {}
public on(event: callEvents, cb: () => void): void {
this.webRtcCall.on(event, cb);
}
public get state(): RTCPeerConnectionState {
return this.webRtcCall.callState;
}
public async startCall(): Promise<void> {
return this.webRtcCall.startCall();
}
public async endCall(): Promise<void> {
return this.webRtcCall.endCall();
}
Expand Down

0 comments on commit be942c7

Please sign in to comment.