-
Notifications
You must be signed in to change notification settings - Fork 0
/
grapevine-client.js
4595 lines (4101 loc) · 377 KB
/
grapevine-client.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************\
* GRAPEVINE-PEER *
\****************/
// TODO factor server-message out into something that can interface with peerjs-client
/*! peerjs build:0.3.13, development. Copyright(c) 2013 Michelle Bu <michelle@michellebu.com> */(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports.RTCSessionDescription = window.RTCSessionDescription ||
window.mozRTCSessionDescription;
module.exports.RTCPeerConnection = window.RTCPeerConnection ||
window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
module.exports.RTCIceCandidate = window.RTCIceCandidate ||
window.mozRTCIceCandidate;
},{}],2:[function(require,module,exports){
var util = require('./util');
var EventEmitter = require('eventemitter3');
var Negotiator = require('./negotiator');
var Reliable = require('reliable');
/**
* Wraps a DataChannel between two Peers.
*/
function DataConnection(peer, provider, options) {
if (!(this instanceof DataConnection)) return new DataConnection(peer, provider, options);
EventEmitter.call(this);
this.options = util.extend({
serialization: 'binary',
reliable: false
}, options);
// Connection is not open yet.
this.open = false;
this.type = 'data';
this.peer = peer;
this.provider = provider;
this.id = this.options.connectionId || DataConnection._idPrefix + util.randomToken();
this.label = this.options.label || this.id;
this.metadata = this.options.metadata;
this.serialization = this.options.serialization;
this.reliable = this.options.reliable;
// Data channel buffering.
this._buffer = [];
this._buffering = false;
this.bufferSize = 0;
// For storing large data.
this._chunkedData = {};
if (this.options._payload) {
this._peerBrowser = this.options._payload.browser;
}
Negotiator.startConnection(
this,
this.options._payload || {
originator: true
}
);
}
util.inherits(DataConnection, EventEmitter);
DataConnection._idPrefix = 'dc_';
/** Called by the Negotiator when the DataChannel is ready. */
DataConnection.prototype.initialize = function(dc) {
this._dc = this.dataChannel = dc;
this._configureDataChannel();
}
DataConnection.prototype._configureDataChannel = function() {
var self = this;
if (util.supports.sctp) {
this._dc.binaryType = 'arraybuffer';
}
this._dc.onopen = function() {
util.log('Data channel connection success');
self.open = true;
self.emit('open');
}
// Use the Reliable shim for non Firefox browsers
if (!util.supports.sctp && this.reliable) {
this._reliable = new Reliable(this._dc, util.debug);
}
if (this._reliable) {
this._reliable.onmessage = function(msg) {
self.emit('data', msg);
};
} else {
this._dc.onmessage = function(e) {
self._handleDataMessage(e);
};
}
this._dc.onclose = function(e) {
util.log('DataChannel closed for:', self.peer);
self.close();
};
}
// Handles a DataChannel message.
DataConnection.prototype._handleDataMessage = function(e) {
var self = this;
var data = e.data;
var datatype = data.constructor;
if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
if (datatype === Blob) {
// Datatype should never be blob
util.blobToArrayBuffer(data, function(ab) {
data = util.unpack(ab);
self.emit('data', data);
});
return;
} else if (datatype === ArrayBuffer) {
data = util.unpack(data);
} else if (datatype === String) {
// String fallback for binary data for browsers that don't support binary yet
var ab = util.binaryStringToArrayBuffer(data);
data = util.unpack(ab);
}
} else if (this.serialization === 'json') {
data = JSON.parse(data);
}
// Check if we've chunked--if so, piece things back together.
// We're guaranteed that this isn't 0.
if (data.__peerData) {
var id = data.__peerData;
var chunkInfo = this._chunkedData[id] || {data: [], count: 0, total: data.total};
chunkInfo.data[data.n] = data.data;
chunkInfo.count += 1;
if (chunkInfo.total === chunkInfo.count) {
// Clean up before making the recursive call to `_handleDataMessage`.
delete this._chunkedData[id];
// We've received all the chunks--time to construct the complete data.
data = new Blob(chunkInfo.data);
this._handleDataMessage({data: data});
}
this._chunkedData[id] = chunkInfo;
return;
}
this.emit('data', data);
}
/**
* Exposed functionality for users.
*/
/** Allows user to close connection. */
DataConnection.prototype.close = function() {
if (!this.open) {
return;
}
this.open = false;
Negotiator.cleanup(this);
this.emit('close');
}
/** Allows user to send data. */
DataConnection.prototype.send = function(data, chunked) {
if (!this.open) {
this.emit('error', new Error('Connection is not open. You should listen for the `open` event before sending messages.'));
return;
}
if (this._reliable) {
// Note: reliable shim sending will make it so that you cannot customize
// serialization.
this._reliable.send(data);
return;
}
var self = this;
if (this.serialization === 'json') {
this._bufferedSend(JSON.stringify(data));
} else if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
var blob = util.pack(data);
// For Chrome-Firefox interoperability, we need to make Firefox "chunk"
// the data it sends out.
var needsChunking = util.chunkedBrowsers[this._peerBrowser] || util.chunkedBrowsers[util.browser];
if (needsChunking && !chunked && blob.size > util.chunkedMTU) {
this._sendChunks(blob);
return;
}
// DataChannel currently only supports strings.
if (!util.supports.sctp) {
util.blobToBinaryString(blob, function(str) {
self._bufferedSend(str);
});
} else if (!util.supports.binaryBlob) {
// We only do this if we really need to (e.g. blobs are not supported),
// because this conversion is costly.
util.blobToArrayBuffer(blob, function(ab) {
self._bufferedSend(ab);
});
} else {
this._bufferedSend(blob);
}
} else {
this._bufferedSend(data);
}
}
DataConnection.prototype._bufferedSend = function(msg) {
if (this._buffering || !this._trySend(msg)) {
this._buffer.push(msg);
this.bufferSize = this._buffer.length;
}
}
// Returns true if the send succeeds.
DataConnection.prototype._trySend = function(msg) {
try {
this._dc.send(msg);
} catch (e) {
this._buffering = true;
var self = this;
setTimeout(function() {
// Try again.
self._buffering = false;
self._tryBuffer();
}, 100);
return false;
}
return true;
}
// Try to send the first message in the buffer.
DataConnection.prototype._tryBuffer = function() {
if (this._buffer.length === 0) {
return;
}
var msg = this._buffer[0];
if (this._trySend(msg)) {
this._buffer.shift();
this.bufferSize = this._buffer.length;
this._tryBuffer();
}
}
DataConnection.prototype._sendChunks = function(blob) {
var blobs = util.chunk(blob);
for (var i = 0, ii = blobs.length; i < ii; i += 1) {
var blob = blobs[i];
this.send(blob, true);
}
}
DataConnection.prototype.handleMessage = function(message) {
var payload = message.payload;
switch (message.type) {
case 'ANSWER':
this._peerBrowser = payload.browser;
// Forward to negotiator
Negotiator.handleSDP(message.type, this, payload.sdp);
break;
case 'CANDIDATE':
Negotiator.handleCandidate(this, payload.candidate);
break;
default:
util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
break;
}
}
module.exports = DataConnection;
},{"./negotiator":5,"./util":8,"eventemitter3":9,"reliable":12}],3:[function(require,module,exports){
window.Socket = require('./socket');
window.MediaConnection = require('./mediaconnection');
window.DataConnection = require('./dataconnection');
window.Peer = require('./peer');
window.RTCPeerConnection = require('./adapter').RTCPeerConnection;
window.RTCSessionDescription = require('./adapter').RTCSessionDescription;
window.RTCIceCandidate = require('./adapter').RTCIceCandidate;
window.Negotiator = require('./negotiator');
window.util = require('./util');
window.BinaryPack = require('js-binarypack');
},{"./adapter":1,"./dataconnection":2,"./mediaconnection":4,"./negotiator":5,"./peer":6,"./socket":7,"./util":8,"js-binarypack":10}],4:[function(require,module,exports){
var util = require('./util');
var EventEmitter = require('eventemitter3');
var Negotiator = require('./negotiator');
/**
* Wraps the streaming interface between two Peers.
*/
function MediaConnection(peer, provider, options) {
if (!(this instanceof MediaConnection)) return new MediaConnection(peer, provider, options);
EventEmitter.call(this);
this.options = util.extend({}, options);
this.open = false;
this.type = 'media';
this.peer = peer;
this.provider = provider;
this.metadata = this.options.metadata;
this.localStream = this.options._stream;
this.id = this.options.connectionId || MediaConnection._idPrefix + util.randomToken();
if (this.localStream) {
Negotiator.startConnection(
this,
{_stream: this.localStream, originator: true}
);
}
};
util.inherits(MediaConnection, EventEmitter);
MediaConnection._idPrefix = 'mc_';
MediaConnection.prototype.addStream = function(remoteStream) {
util.log('Receiving stream', remoteStream);
this.remoteStream = remoteStream;
this.emit('stream', remoteStream); // Should we call this `open`?
};
MediaConnection.prototype.handleMessage = function(message) {
var payload = message.payload;
switch (message.type) {
case 'ANSWER':
// Forward to negotiator
Negotiator.handleSDP(message.type, this, payload.sdp);
this.open = true;
break;
case 'CANDIDATE':
Negotiator.handleCandidate(this, payload.candidate);
break;
default:
util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
break;
}
}
MediaConnection.prototype.answer = function(stream) {
if (this.localStream) {
util.warn('Local stream already exists on this MediaConnection. Are you answering a call twice?');
return;
}
this.options._payload._stream = stream;
this.localStream = stream;
Negotiator.startConnection(
this,
this.options._payload
)
// Retrieve lost messages stored because PeerConnection not set up.
var messages = this.provider._getMessages(this.id);
for (var i = 0, ii = messages.length; i < ii; i += 1) {
this.handleMessage(messages[i]);
}
this.open = true;
};
/**
* Exposed functionality for users.
*/
/** Allows user to close connection. */
MediaConnection.prototype.close = function() {
if (!this.open) {
return;
}
this.open = false;
Negotiator.cleanup(this);
this.emit('close')
};
module.exports = MediaConnection;
},{"./negotiator":5,"./util":8,"eventemitter3":9}],5:[function(require,module,exports){
var util = require('./util');
var RTCPeerConnection = require('./adapter').RTCPeerConnection;
var RTCSessionDescription = require('./adapter').RTCSessionDescription;
var RTCIceCandidate = require('./adapter').RTCIceCandidate;
/**
* Manages all negotiations between Peers.
*/
var Negotiator = {
pcs: {
data: {},
media: {}
}, // type => {peerId: {pc_id: pc}}.
//providers: {}, // provider's id => providers (there may be multiple providers/client.
queue: [] // connections that are delayed due to a PC being in use.
}
Negotiator._idPrefix = 'pc_';
/** Returns a PeerConnection object set up correctly (for data, media). */
Negotiator.startConnection = function(connection, options) {
var pc = Negotiator._getPeerConnection(connection, options);
if (connection.type === 'media' && options._stream) {
// Add the stream.
pc.addStream(options._stream);
}
// Set the connection's PC.
connection.pc = connection.peerConnection = pc;
// What do we need to do now?
if (options.originator) {
if (connection.type === 'data') {
// Create the datachannel.
var config = {};
// Dropping reliable:false support, since it seems to be crashing
// Chrome.
/*if (util.supports.sctp && !options.reliable) {
// If we have canonical reliable support...
config = {maxRetransmits: 0};
}*/
// Fallback to ensure older browsers don't crash.
if (!util.supports.sctp) {
config = {reliable: options.reliable};
}
var dc = pc.createDataChannel(connection.label, config);
connection.initialize(dc);
}
if (!util.supports.onnegotiationneeded) {
Negotiator._makeOffer(connection);
}
} else {
Negotiator.handleSDP('OFFER', connection, options.sdp);
}
}
Negotiator._getPeerConnection = function(connection, options) {
if (!Negotiator.pcs[connection.type]) {
util.error(connection.type + ' is not a valid connection type. Maybe you overrode the `type` property somewhere.');
}
if (!Negotiator.pcs[connection.type][connection.peer]) {
Negotiator.pcs[connection.type][connection.peer] = {};
}
var peerConnections = Negotiator.pcs[connection.type][connection.peer];
var pc;
// Not multiplexing while FF and Chrome have not-great support for it.
/*if (options.multiplex) {
ids = Object.keys(peerConnections);
for (var i = 0, ii = ids.length; i < ii; i += 1) {
pc = peerConnections[ids[i]];
if (pc.signalingState === 'stable') {
break; // We can go ahead and use this PC.
}
}
} else */
if (options.pc) { // Simplest case: PC id already provided for us.
pc = Negotiator.pcs[connection.type][connection.peer][options.pc];
}
if (!pc || pc.signalingState !== 'stable') {
pc = Negotiator._startPeerConnection(connection);
}
return pc;
}
/*
Negotiator._addProvider = function(provider) {
if ((!provider.id && !provider.disconnected) || !provider.socket.open) {
// Wait for provider to obtain an ID.
provider.on('open', function(id) {
Negotiator._addProvider(provider);
});
} else {
Negotiator.providers[provider.id] = provider;
}
}*/
/** Start a PC. */
Negotiator._startPeerConnection = function(connection) {
util.log('Creating RTCPeerConnection.');
var id = Negotiator._idPrefix + util.randomToken();
var optional = {};
if (connection.type === 'data' && !util.supports.sctp) {
optional = {optional: [{RtpDataChannels: true}]};
} else if (connection.type === 'media') {
// Interop req for chrome.
optional = {optional: [{DtlsSrtpKeyAgreement: true}]};
}
var pc = new RTCPeerConnection(connection.provider.options.config, optional);
Negotiator.pcs[connection.type][connection.peer][id] = pc;
Negotiator._setupListeners(connection, pc, id);
return pc;
}
/** Set up various WebRTC listeners. */
Negotiator._setupListeners = function(connection, pc, pc_id) {
var peerId = connection.peer;
var connectionId = connection.id;
var provider = connection.provider;
// ICE CANDIDATES.
util.log('Listening for ICE candidates.');
pc.onicecandidate = function(evt) {
if (evt.candidate) {
util.log('Received ICE candidates for:', connection.peer);
provider.socket.send({
type: 'CANDIDATE',
payload: {
candidate: evt.candidate,
type: connection.type,
connectionId: connection.id
},
dst: peerId
});
}
};
pc.oniceconnectionstatechange = function() {
switch (pc.iceConnectionState) {
case 'disconnected':
case 'failed':
util.log('iceConnectionState is disconnected, closing connections to ' + peerId);
connection.close();
break;
case 'completed':
pc.onicecandidate = util.noop;
break;
}
};
// Fallback for older Chrome impls.
pc.onicechange = pc.oniceconnectionstatechange;
// ONNEGOTIATIONNEEDED (Chrome)
util.log('Listening for `negotiationneeded`');
pc.onnegotiationneeded = function() {
util.log('`negotiationneeded` triggered');
if (pc.signalingState == 'stable') {
Negotiator._makeOffer(connection);
} else {
util.log('onnegotiationneeded triggered when not stable. Is another connection being established?');
}
};
// DATACONNECTION.
util.log('Listening for data channel');
// Fired between offer and answer, so options should already be saved
// in the options hash.
pc.ondatachannel = function(evt) {
util.log('Received data channel');
var dc = evt.channel;
var connection = provider.getConnection(peerId, connectionId);
connection.initialize(dc);
};
// MEDIACONNECTION.
util.log('Listening for remote stream');
pc.onaddstream = function(evt) {
util.log('Received remote stream');
var stream = evt.stream;
var connection = provider.getConnection(peerId, connectionId);
// 10/10/2014: looks like in Chrome 38, onaddstream is triggered after
// setting the remote description. Our connection object in these cases
// is actually a DATA connection, so addStream fails.
// TODO: This is hopefully just a temporary fix. We should try to
// understand why this is happening.
if (connection.type === 'media') {
connection.addStream(stream);
}
};
}
Negotiator.cleanup = function(connection) {
util.log('Cleaning up PeerConnection to ' + connection.peer);
var pc = connection.pc;
if (!!pc && (pc.readyState !== 'closed' || pc.signalingState !== 'closed')) {
pc.close();
connection.pc = null;
}
}
Negotiator._makeOffer = function(connection) {
var pc = connection.pc;
pc.createOffer(function(offer) {
util.log('Created offer.');
if (!util.supports.sctp && connection.type === 'data' && connection.reliable) {
offer.sdp = Reliable.higherBandwidthSDP(offer.sdp);
}
pc.setLocalDescription(offer, function() {
util.log('Set localDescription: offer', 'for:', connection.peer);
connection.provider.socket.send({
type: 'OFFER',
payload: {
sdp: offer,
type: connection.type,
label: connection.label,
connectionId: connection.id,
reliable: connection.reliable,
serialization: connection.serialization,
metadata: connection.metadata,
browser: util.browser
},
dst: connection.peer
});
}, function(err) {
connection.provider.emitError('webrtc', err);
util.log('Failed to setLocalDescription, ', err);
});
}, function(err) {
connection.provider.emitError('webrtc', err);
util.log('Failed to createOffer, ', err);
}, connection.options.constraints);
}
Negotiator._makeAnswer = function(connection) {
var pc = connection.pc;
pc.createAnswer(function(answer) {
util.log('Created answer.');
if (!util.supports.sctp && connection.type === 'data' && connection.reliable) {
answer.sdp = Reliable.higherBandwidthSDP(answer.sdp);
}
pc.setLocalDescription(answer, function() {
util.log('Set localDescription: answer', 'for:', connection.peer);
connection.provider.socket.send({
type: 'ANSWER',
payload: {
sdp: answer,
type: connection.type,
connectionId: connection.id,
browser: util.browser
},
dst: connection.peer
});
}, function(err) {
connection.provider.emitError('webrtc', err);
util.log('Failed to setLocalDescription, ', err);
});
}, function(err) {
connection.provider.emitError('webrtc', err);
util.log('Failed to create answer, ', err);
});
}
/** Handle an SDP. */
Negotiator.handleSDP = function(type, connection, sdp) {
sdp = new RTCSessionDescription(sdp);
var pc = connection.pc;
util.log('Setting remote description', sdp);
pc.setRemoteDescription(sdp, function() {
util.log('Set remoteDescription:', type, 'for:', connection.peer);
if (type === 'OFFER') {
Negotiator._makeAnswer(connection);
}
}, function(err) {
connection.provider.emitError('webrtc', err);
util.log('Failed to setRemoteDescription, ', err);
});
}
/** Handle a candidate. */
Negotiator.handleCandidate = function(connection, ice) {
var candidate = ice.candidate;
var sdpMLineIndex = ice.sdpMLineIndex;
connection.pc.addIceCandidate(new RTCIceCandidate({
sdpMLineIndex: sdpMLineIndex,
candidate: candidate
}));
util.log('Added ICE candidate for:', connection.peer);
}
module.exports = Negotiator;
},{"./adapter":1,"./util":8}],6:[function(require,module,exports){
var util = require('./util');
var EventEmitter = require('eventemitter3');
var Socket = require('./socket');
var MediaConnection = require('./mediaconnection');
var DataConnection = require('./dataconnection');
/**
* A peer who can initiate connections with other peers.
*/
function Peer(id, options) {
if (!(this instanceof Peer)) return new Peer(id, options);
EventEmitter.call(this);
// Deal with overloading
if (id && id.constructor == Object) {
options = id;
id = undefined;
} else if (id) {
// Ensure id is a string
id = id.toString();
}
//
// Configurize options
options = util.extend({
debug: 0, // 1: Errors, 2: Warnings, 3: All logs
host: util.CLOUD_HOST,
port: util.CLOUD_PORT,
key: 'peerjs',
path: '/',
token: util.randomToken(),
config: util.defaultConfig
}, options);
this.options = options;
// Detect relative URL host.
if (options.host === '/') {
options.host = window.location.hostname;
}
// Set path correctly.
if (options.path[0] !== '/') {
options.path = '/' + options.path;
}
if (options.path[options.path.length - 1] !== '/') {
options.path += '/';
}
// Set whether we use SSL to same as current host
if (options.secure === undefined && options.host !== util.CLOUD_HOST) {
options.secure = util.isSecure();
}
// Set a custom log function if present
if (options.logFunction) {
util.setLogFunction(options.logFunction);
}
util.setLogLevel(options.debug);
//
// Sanity checks
// Ensure WebRTC supported
if (!util.supports.audioVideo && !util.supports.data ) {
this._delayedAbort('browser-incompatible', 'The current browser does not support WebRTC');
return;
}
// Ensure alphanumeric id
if (!util.validateId(id)) {
this._delayedAbort('invalid-id', 'ID "' + id + '" is invalid');
return;
}
// Ensure valid key
if (!util.validateKey(options.key)) {
this._delayedAbort('invalid-key', 'API KEY "' + options.key + '" is invalid');
return;
}
// Ensure not using unsecure cloud server on SSL page
if (options.secure && options.host === '0.peerjs.com') {
this._delayedAbort('ssl-unavailable',
'The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS.');
return;
}
//
// States.
this.destroyed = false; // Connections have been killed
this.disconnected = false; // Connection to PeerServer killed but P2P connections still active
this.open = false; // Sockets and such are not yet open.
//
// References
this.connections = {}; // DataConnections for this peer.
this._lostMessages = {}; // src => [list of messages]
//
// Start the server connection
this._initializeServerConnection();
if (id) {
this._initialize(id);
} else {
this._retrieveId();
}
//
}
util.inherits(Peer, EventEmitter);
// Initialize the 'socket' (which is actually a mix of XHR streaming and
// websockets.)
Peer.prototype._initializeServerConnection = function() {
var self = this;
this.socket = new Socket(this.options.secure, this.options.host, this.options.port, this.options.path, this.options.key);
this.socket.on('message', function(data) {
self._handleMessage(data);
});
this.socket.on('error', function(error) {
self._abort('socket-error', error);
});
this.socket.on('disconnected', function() {
// If we haven't explicitly disconnected, emit error and disconnect.
if (!self.disconnected) {
self.emitError('network', 'Lost connection to server.');
self.disconnect();
}
});
this.socket.on('close', function() {
// If we haven't explicitly disconnected, emit error.
if (!self.disconnected) {
self._abort('socket-closed', 'Underlying socket is already closed.');
}
});
};
/** Get a unique ID from the server via XHR. */
Peer.prototype._retrieveId = function(cb) {
var self = this;
var http = new XMLHttpRequest();
var protocol = this.options.secure ? 'https://' : 'http://';
var url = protocol + this.options.host + ':' + this.options.port +
this.options.path + this.options.key + '/id';
var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
url += queryString;
// If there's no ID we need to wait for one before trying to init socket.
http.open('get', url, true);
http.onerror = function(e) {
util.error('Error retrieving ID', e);
var pathError = '';
if (self.options.path === '/' && self.options.host !== util.CLOUD_HOST) {
pathError = ' If you passed in a `path` to your self-hosted PeerServer, ' +
'you\'ll also need to pass in that same path when creating a new ' +
'Peer.';
}
self._abort('server-error', 'Could not get an ID from the server.' + pathError);
};
http.onreadystatechange = function() {
if (http.readyState !== 4) {
return;
}
if (http.status !== 200) {
http.onerror();
return;
}
self._initialize(http.responseText);
};
http.send(null);
};
/** Initialize a connection with the server. */
Peer.prototype._initialize = function(id) {
this.id = id;
this.socket.start(this.id, this.options.token);
};
/** Handles messages from the server. */
Peer.prototype._handleMessage = function(message) {
var type = message.type;
var payload = message.payload;
var peer = message.src;
var connection;
switch (type) {
case 'OPEN': // The connection to the server is open.
this.emit('open', this.id);
this.open = true;
break;
case 'ERROR': // Server error.
this._abort('server-error', payload.msg);
break;
case 'ID-TAKEN': // The selected ID is taken.
this._abort('unavailable-id', 'ID `' + this.id + '` is taken');
break;
case 'INVALID-KEY': // The given API key cannot be found.
this._abort('invalid-key', 'API KEY "' + this.options.key + '" is invalid');
break;
case 'LEAVE': // Another peer has closed its connection to this peer.
util.log('Received leave message from', peer);
this._cleanupPeer(peer);
break;
case 'EXPIRE': // The offer sent to a peer has expired without response.
this.emitError('peer-unavailable', 'Could not connect to peer ' + peer);
break;
case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
var connectionId = payload.connectionId;
connection = this.getConnection(peer, connectionId);
if (connection) {
util.warn('Offer received for existing Connection ID:', connectionId);
//connection.handleMessage(message);
} else {
// Create a new connection.
if (payload.type === 'media') {
connection = new MediaConnection(peer, this, {
connectionId: connectionId,
_payload: payload,
metadata: payload.metadata
});
this._addConnection(peer, connection);
this.emit('call', connection);
} else if (payload.type === 'data') {
connection = new DataConnection(peer, this, {
connectionId: connectionId,
_payload: payload,
metadata: payload.metadata,
label: payload.label,
serialization: payload.serialization,
reliable: payload.reliable
});
this._addConnection(peer, connection);
this.emit('connection', connection);
} else {
util.warn('Received malformed connection type:', payload.type);
return;
}
// Find messages.
var messages = this._getMessages(connectionId);
for (var i = 0, ii = messages.length; i < ii; i += 1) {
connection.handleMessage(messages[i]);
}
}
break;
// IGG: Server message emission
case 'MESSAGE':
this.emit('server-message', payload);
break;
default:
if (!payload) {
util.warn('You received a malformed message from ' + peer + ' of type ' + type);
return;
}
var id = payload.connectionId;
connection = this.getConnection(peer, id);
if (connection && connection.pc) {
// Pass it on.
connection.handleMessage(message);
} else if (id) {
// Store for possible later use
this._storeMessage(id, message);
} else {
util.warn('You received an unrecognized message:', message);
}
break;
}
};
/** Stores messages without a set up connection, to be claimed later. */
Peer.prototype._storeMessage = function(connectionId, message) {
if (!this._lostMessages[connectionId]) {
this._lostMessages[connectionId] = [];
}
this._lostMessages[connectionId].push(message);
};
/** Retrieve messages from lost message store */
Peer.prototype._getMessages = function(connectionId) {
var messages = this._lostMessages[connectionId];
if (messages) {
delete this._lostMessages[connectionId];
return messages;
} else {
return [];
}
};
/**
* Returns a DataConnection to the specified peer. See documentation for a
* complete list of options.
*/
Peer.prototype.connect = function(peer, options) {
if (this.disconnected) {
util.warn('You cannot connect to a new Peer because you called ' +
'.disconnect() on this Peer and ended your connection with the ' +
'server. You can create a new Peer to reconnect, or call reconnect ' +