-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.js
executable file
·254 lines (200 loc) · 6.75 KB
/
main.js
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
const localVideo = document.getElementById('localVideo');
const remoteVideo = document.getElementById('remoteVideo');
const callButton = document.getElementById('callButton');
const hangupButton = document.getElementById('hangupButton');
const screenShareButton = document.getElementById('screenShareButton');
const socket = new WebSocket('wss://localhost:8888');
let peerConnection;
let dataChannel;
let localMediaStream;
let remoteId;
const remoteMediaStream = new MediaStream();
socket.onopen = () => {
console.log('socket::open');
};
socket.onmessage = async ({ data }) => {
try {
const jsonMessage = JSON.parse(data);
console.log('action', jsonMessage.action);
switch (jsonMessage.action) {
case 'start':
console.log('start', jsonMessage.id);
callButton.disabled = false;
document.getElementById('localId').innerHTML = jsonMessage.id;
break;
case 'offer':
remoteId = jsonMessage.data.remoteId;
delete jsonMessage.data.remoteId;
await initializePeerConnection(localMediaStream.getTracks());
await peerConnection.setRemoteDescription(new RTCSessionDescription(jsonMessage.data.offer));
const answer = await peerConnection.createAnswer();
await peerConnection.setLocalDescription(answer);
sendSocketMessage('answer', { remoteId, answer });
break;
case 'answer':
await peerConnection.setRemoteDescription(new RTCSessionDescription(jsonMessage.data.answer));
break;
case 'iceCandidate':
await peerConnection.addIceCandidate(jsonMessage.data.candidate);
break;
default: console.warn('unknown action', jsonMessage.action);
}
} catch (error) {
console.error('failed to handle socket message', error);
}
};
socket.onerror = (error) => {
console.error('socket::error', error);
};
socket.onclose = () => {
console.log('socket::close');
stop();
};
const sendSocketMessage = (action, data) => {
const message = { action, data };
socket.send(JSON.stringify(message));
};
const start = async () => {
try {
localMediaStream = await getLocalMediaStream();
sendSocketMessage('start');
} catch (error) {
console.error('failed to start stream', error);
}
};
const call = async () => {
try {
remoteId = document.getElementById('callId').value;
if (!remoteId) {
alert('Please enter a remote id');
return;
}
console.log('call: ', remoteId);
await initializePeerConnection(localMediaStream.getTracks());
initializeDataChannel();
const offer = await peerConnection.createOffer();
await peerConnection.setLocalDescription(offer);
sendSocketMessage('offer', { offer, remoteId });
} catch (error) {
console.error('failed to initialize call', error);
}
};
const hangup = () => socket.close();
const stop = () => {
if (!localVideo.srcObject) return;
for (const track of localVideo.srcObject.getTracks()) {
console.log('stop track', track);
track.stop();
}
for (const sender of peerConnection.getSenders()) {
sender.track.stop();
}
dataChannel.close();
peerConnection.close();
callButton.disabled = true;
hangupButton.disabled = true;
screenShareButton.disabled = true;
localVideo.srcObject = undefined;
remoteVideo.srcObject = undefined;
};
const getLocalMediaStream = async () => {
try {
const mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
console.log('got local media stream');
localVideo.srcObject = mediaStream;
return mediaStream;
} catch (error) {
console.error('failed to get local media stream', error);
}
};
const initializePeerConnection = async (mediaTracks) => {
const config = { iceServers: [{ urls: [ 'stun:stun1.l.google.com:19302' ] } ] };
peerConnection = new RTCPeerConnection(config);
peerConnection.onicecandidate = ({ candidate }) => {
if (!candidate) return;
console.log('peerConnection::icecandidate', candidate);
console.log('remote', remoteId);
sendSocketMessage('iceCandidate', { remoteId, candidate });
};
peerConnection.oniceconnectionstatechange = () => {
console.log('peerConnection::iceconnectionstatechange newState=', peerConnection.iceConnectionState);
// If ICE state is disconnected stop
if (peerConnection.iceConnectionState === 'disconnected') {
alert('Connection has been closed stopping...');
socket.close();
}
};
peerConnection.ontrack = ({ track }) => {
console.log('peerConnection::track', track);
remoteMediaStream.addTrack(track);
remoteVideo.srcObject = remoteMediaStream;
};
peerConnection.ondatachannel = ({ channel }) => {
console.log('peerConnection::ondatachannel');
dataChannel = channel;
initializeDataChannelListeners();
};
for (const track of mediaTracks) {
peerConnection.addTrack(track);
}
hangupButton.disabled = false;
screenShareButton.disabled = false;
};
const initializeDataChannel = () => {
const config = { ordered: true };
dataChannel = peerConnection.createDataChannel('dataChannel', config);
initializeDataChannelListeners();
};
const initializeDataChannelListeners = () => {
dataChannel.onopen = () => console.log('dataChannel opened');
dataChannel.onclose = () => console.log('dataChannel closed');
dataChannel.onerror = (error) => console.error('dataChannel error:', error);
dataChannel.onmessage = ({ data }) => {
console.log('dataChannel data', data);
};
};
const shareScreen = async () => {
const mediaStream = await getLocalScreenCaptureStream();
const screenTrack = mediaStream.getVideoTracks()[0];
if (screenTrack) {
console.log('replace camera track with screen track');
replaceTrack(screenTrack);
}
};
const getLocalScreenCaptureStream = async () => {
try {
const constraints = { video: { cursor: 'always' }, audio: false };
const screenCaptureStream = await navigator.mediaDevices.getDisplayMedia(constraints);
return screenCaptureStream;
} catch (error) {
console.error('failed to get local screen', error);
}
};
const replaceTrack = (newTrack) => {
const sender = peerConnection.getSenders().find(sender =>
sender.track.kind === newTrack.kind
);
if (!sender) {
console.warn('failed to find sender');
return;
}
sender.replaceTrack(newTrack);
};
const sendMessage = () => {
const message = document.getElementById('chatMessage').value;
if (!message) {
alert('no message entered');
return;
}
if (!dataChannel || dataChannel.readyState !== 'open') {
alert('data channel is undefined or is not connected');
return;
}
console.log('sending message', message);
const data = {
message,
time: new Date()
};
dataChannel.send(JSON.stringify(data));
document.getElementById('chatMessage').value = '';
};