/
nextRTC.js
393 lines (361 loc) · 12.1 KB
/
nextRTC.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var adapter = require('webrtc-adapter');
var Message = function () {
function Message(signal, from, to, content, custom) {
_classCallCheck(this, Message);
this.signal = signal;
this.from = from;
this.to = to;
this.content = content;
this.custom = custom;
}
_createClass(Message, [{
key: 'toJson',
value: function toJson() {
return JSON.stringify(this);
}
}], [{
key: 'offerResponse',
value: function offerResponse(to, content) {
return new Message('offerResponse', null, to, content);
}
}, {
key: 'answerResponse',
value: function answerResponse(to, content) {
return new Message('answerResponse', null, to, content);
}
}, {
key: 'create',
value: function create(conversationId, custom) {
return new Message('create', null, null, conversationId, custom);
}
}, {
key: 'join',
value: function join(conversationId, custom) {
return new Message('join', null, null, conversationId, custom);
}
}, {
key: 'left',
value: function left() {
return new Message('left');
}
}, {
key: 'candidate',
value: function candidate(to, _candidate) {
return new Message('candidate', null, to, _candidate);
}
}]);
return Message;
}();
var SignalingChannel = function () {
function SignalingChannel(wsURL, debug) {
var _this = this;
_classCallCheck(this, SignalingChannel);
this.debug = debug;
this.onSignal = function () {};
this.waiting = [];
this.channelReady = false;
this.websocket = new WebSocket(wsURL);
this.websocket.onopen = function () {
_this.channelReady = true;
while (_this.waiting.length > 0) {
_this.send(_this.waiting.pop());
}
};
this.websocket.onmessage = function (event) {
if (debug) {
console.log('res: ' + event.data);
}
var signal = JSON.parse(event.data);
_this.onSignal(signal.signal, signal);
};
this.websocket.onclose = function (event) {
_this.onSignal('close', event);
};
this.websocket.onerror = function (error) {
if (debug) {
console.log('Communication channel is broken', error);
}
_this.onSignal('error', error);
};
}
_createClass(SignalingChannel, [{
key: 'send',
value: function send(payload) {
if (!this.channelReady) {
if (payload.signal && payload.signal !== '') {
this.waiting.push(payload);
}
}
if (this.debug) {
console.log('req: ', payload);
}
this.websocket.send(JSON.stringify(payload));
}
}, {
key: 'close',
value: function close() {
this.websocket.onclose = function () {};
this.websocket.close();
}
}, {
key: 'setSignal',
value: function setSignal(callback) {
this.onSignal = callback;
}
}]);
return SignalingChannel;
}();
var NextRTCClient = function () {
function NextRTCClient(configuration) {
var _this2 = this;
var debug = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
_classCallCheck(this, NextRTCClient);
this.debug = debug;
this.configuration = configuration;
this.handlers = this.initHandlers();
this.channel = new SignalingChannel(configuration.wsURL, this.debug);
this.localStream = undefined;
this.peerConnections = {};
this.channel.setSignal(function (s, p) {
return _this2.execute(s, p);
});
}
_createClass(NextRTCClient, [{
key: 'on',
value: function on(signal, handler) {
if (this.handlers[signal]) {
if (this.debug) {
console.log("Replacing handler for signal: " + signal);
}
}
this.handlers[signal] = handler;
}
}, {
key: 'initHandlers',
value: function initHandlers() {
var _this3 = this;
return {
'offerRequest': function offerRequest(message) {
return _this3.offerRequest(message);
},
'answerRequest': function answerRequest(message) {
return _this3.answerRequest(message);
},
'finalize': function finalize(message) {
return _this3.finalize(message);
},
'candidate': function candidate(message) {
return _this3.candidate(message);
},
'close': function close() {
return _this3.close();
},
'error': function error(_error) {
console.log("Unexpected situation: ", _error);
},
'ping': function ping() {}
};
}
}, {
key: 'getLocalStream',
value: function getLocalStream(onSuccess) {
var _this4 = this;
if (this.localStream) {
onSuccess(this.localStream);
} else {
window.navigator.mediaDevices.getUserMedia(this.configuration.mediaConfig).then(function (stream) {
onSuccess(stream);
_this4.localStream = stream;
_this4.execute('localStream', {
stream: stream
});
}).catch(function (err) {
_this4.execute('error', 'LocalStream: Unable to get user media ' + err);
});
}
}
}, {
key: 'assignTrack',
value: function assignTrack(peer, stream) {
stream.getTracks().forEach(function (track) {
return peer.addTrack(track, stream);
});
}
}, {
key: 'getRemoteStream',
value: function getRemoteStream(member) {
if (this.peerConnections[member] && this.peerConnections[member].stream) return this.peerConnections[member].stream;
return undefined;
}
}, {
key: 'onRemoteStream',
value: function onRemoteStream(member, streams) {
this.peerConnections[member].streams = streams;
this.execute('remoteStream', {
member: member,
stream: streams[0]
});
}
}, {
key: 'offerRequest',
value: function offerRequest(message) {
var _this5 = this;
this.getLocalStream(function (stream) {
return _this5.offerResponse(message, stream);
});
}
}, {
key: 'offerResponse',
value: function offerResponse(message, stream) {
var _this6 = this;
this.onPeerConnection(message.from, function (peer) {
_this6.assignTrack(peer, stream);
peer.createOffer({
offerToReceiveAudio: _this6.configuration.mediaConfig.audio ? 1 : 0,
offerToReceiveVideo: _this6.configuration.mediaConfig.video ? 1 : 0
}).then(function (localDescription) {
peer.setLocalDescription(localDescription).then(function () {
return _this6.channel.send(Message.offerResponse(message.from, localDescription.sdp));
}).catch(function (err) {
return _this6.execute('error', 'OfferResponse: Could not set local description' + err);
});
}).catch(function (err) {
return _this6.execute('error', 'OfferResponse: Could not get local description' + err);
});
});
}
}, {
key: 'answerRequest',
value: function answerRequest(message) {
var _this7 = this;
this.getLocalStream(function (stream) {
return _this7.answerResponse(message, stream);
});
}
}, {
key: 'answerResponse',
value: function answerResponse(message, stream) {
var _this8 = this;
this.onPeerConnection(message.from, function (peer) {
_this8.assignTrack(peer, stream);
peer.setRemoteDescription(new RTCSessionDescription({
type: 'offer',
sdp: message.content
})).then(function () {
peer.createAnswer().then(function (localDescription) {
return peer.setLocalDescription(localDescription).then(function () {
return _this8.channel.send(Message.answerResponse(message.from, localDescription.sdp));
}).catch(function (error) {
return _this8.execute('error', 'AnswerResponse: Could not set local description of remote stream' + error);
});
}).catch(function (error) {
return _this8.execute('error', 'AnswerResponse: Could not create answer' + error);
});
}).catch(function (error) {
return _this8.execute('error', 'AnswerResponse: Could not get remote description' + error);
});
});
}
}, {
key: 'finalize',
value: function finalize(message) {
var _this9 = this;
this.onPeerConnection(message.from, function (peer) {
peer.setRemoteDescription(new RTCSessionDescription({
type: 'answer',
sdp: message.content
})).then(function () {}).catch(function (error) {
return _this9.execute('error', 'Finalize: Could not set remote description' + error);
});
});
}
}, {
key: 'candidate',
value: function candidate(message) {
var _this10 = this;
this.onPeerConnection(message.from, function (peer) {
peer.addIceCandidate(new RTCIceCandidate(JSON.parse(message.content.replace(new RegExp('\'', 'g'), '"')), function () {
return _this10.debug ? console.log('candidates exchanged') : null;
}, function (err) {
return _this10.execute('error', 'Candidate: Failed to exchange candidates ' + err);
}));
});
}
}, {
key: 'onPeerConnection',
value: function onPeerConnection(connectionName, cb) {
var _this11 = this;
var remoteConnection = this.peerConnections[connectionName];
if (!remoteConnection) {
remoteConnection = this.peerConnections[connectionName] = new RTCPeerConnection(this.configuration.peerConfig);
remoteConnection.ontrack = function (e) {
return _this11.onRemoteStream(connectionName, e.streams);
};
remoteConnection.onicecandidate = function (event) {
return _this11.onIceCandidate(connectionName, event);
};
remoteConnection.oniceconnectionstatechange = function (change) {
return _this11.debug ? console.log('(' + connectionName + ') changed state to', remoteConnection.iceConnectionState) : null;
};
}
cb(remoteConnection);
}
}, {
key: 'onIceCandidate',
value: function onIceCandidate(member, event) {
if (event.candidate) this.channel.send(Message.candidate(member, JSON.stringify(event.candidate)));
}
}, {
key: 'execute',
value: function execute(signal, event) {
if (this.handlers.hasOwnProperty(signal)) try {
this.handlers[signal](event);
} catch (err) {
if (this.debug) {
console.log('User handler on ' + signal + ' failed!', err);
}
} else if (this.debug) {
console.log('Missing handler for ' + signal);
}
}
}, {
key: 'create',
value: function create(conversationId, custom) {
this.channel.send(Message.create(conversationId, custom));
}
}, {
key: 'join',
value: function join(conversationId, custom) {
this.channel.send(Message.join(conversationId, custom));
}
}, {
key: 'close',
value: function close() {
this.channel.close();
for (var member in this.peerConnections) {
this.release(member);
}
}
}, {
key: 'release',
value: function release(member) {
if (this.peerConnections[member]) {
this.peerConnections[member].close();
delete this.peerConnections[member];
}
}
}, {
key: 'leave',
value: function leave() {
this.channel.send(Message.left());
for (var name in this.peerConnections) {
this.release(name);
}
}
}]);
return NextRTCClient;
}();
module.exports = NextRTCClient;