This repository was archived by the owner on May 16, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathuseWebRTC.ts
157 lines (139 loc) · 4.41 KB
/
useWebRTC.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import { Channel, Socket, MessageRef } from 'phoenix';
import { useCallback, useEffect, useState, useRef } from 'react';
import { ConnectionOptions, Metadata } from '../MembraneWebRTC.types';
import MembraneWebRTCModule from '../MembraneWebRTCModule';
import { ReceivableEvents, eventEmitter } from '../common/eventEmitter';
/**
* The hook used to manage a connection with membrane server.
* @returns An object with functions to manage membrane server connection and `error` if connection failed.
*/
export function useWebRTC() {
const [error, setError] = useState<string | null>(null);
// prevent user from calling connect methods multiple times
const lock = useRef(false);
const socket = useRef<Socket | null>(null);
const webrtcChannel = useRef<Channel | null>(null);
const onSocketError = useRef<MessageRef | null>(null);
const onSocketClose = useRef<MessageRef | null>(null);
useEffect(() => {
const eventListener = eventEmitter.addListener(
ReceivableEvents.SendMediaEvent,
sendMediaEvent
);
return () => eventListener.remove();
}, []);
const sendMediaEvent = ({ event }: { event: string }) => {
if (webrtcChannel.current) {
webrtcChannel.current.push('mediaEvent', { data: event });
}
};
const withLock =
(f: any) =>
async (...args: any) => {
if (lock.current) return Promise.resolve();
lock.current = true;
try {
await f(...args);
} catch (e) {
throw e;
} finally {
lock.current = false;
}
};
/**
* Connects to a server.
* @returns A promise that resolves on success or rejects in case of an error.
*/
const connect: <ConnectionOptionsMetadataType extends Metadata>(
/**
* server url
*/
url: string,
roomName: string,
connectionOptions?: Partial<
ConnectionOptions<ConnectionOptionsMetadataType>
>
) => Promise<void> = useCallback(
withLock(
async <ConnectionOptionsMetadataType extends Metadata>(
url: string,
roomName: string,
connectionOptions: Partial<
ConnectionOptions<ConnectionOptionsMetadataType>
> = {}
) => {
setError(null);
const _socket = new Socket(url, {
params: connectionOptions.connectionParams,
});
_socket.connect();
onSocketClose.current = _socket.onClose(cleanUp);
onSocketError.current = _socket.onError(() => {
setError(`Socket error occured.`);
cleanUp();
});
const _webrtcChannel = _socket.channel(
`room:${roomName}`,
connectionOptions.socketChannelParams
);
_webrtcChannel.on('mediaEvent', (event) => {
MembraneWebRTCModule.receiveMediaEvent(event.data);
});
_webrtcChannel.on('error', (error) => {
console.error(error);
setError(
`Received error report from the server: ${error.message ?? ''}`
);
cleanUp();
});
_webrtcChannel.onError((reason) => {
console.error(reason);
setError(`Webrtc channel error occurred: ${reason}.`);
cleanUp();
});
socket.current = _socket;
webrtcChannel.current = _webrtcChannel;
await MembraneWebRTCModule.create();
await new Promise<void>((resolve, reject) => {
_webrtcChannel
.join()
.receive('ok', () => {
resolve();
})
.receive('error', (_response) => {
console.error(_response);
reject(_response);
});
});
await MembraneWebRTCModule.connect(
connectionOptions.endpointMetadata || {}
);
}
),
[]
);
/**
* Call this to gracefully disconnect from the server. After that you can connect again.
* @returns A promise that resolves on success or rejects in case of an error.
*/
const disconnect: () => Promise<void> = useCallback(
withLock((): Promise<void> => {
setError(null);
return cleanUp();
}),
[]
);
const cleanUp = (): Promise<void> => {
webrtcChannel.current?.leave();
const refs: MessageRef[] = [];
if (onSocketClose.current) refs.push(onSocketClose.current);
if (onSocketError.current) refs.push(onSocketError.current);
socket.current?.off(refs);
return MembraneWebRTCModule.disconnect();
};
return {
connect,
disconnect,
error,
};
}