PageRenderTime 58ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/files/peerjs/0.3.9/peer.js

https://gitlab.com/Mirros/jsdelivr
JavaScript | 1806 lines | 1445 code | 186 blank | 175 comment | 323 complexity | 47c9973dd16fd21aac61e5738b20e3e8 MD5 | raw file
  1. /*! peerjs.js build:0.3.9, development. Copyright(c) 2013 Michelle Bu <michelle@michellebu.com> */
  2. (function(exports){
  3. var binaryFeatures = {};
  4. binaryFeatures.useBlobBuilder = (function(){
  5. try {
  6. new Blob([]);
  7. return false;
  8. } catch (e) {
  9. return true;
  10. }
  11. })();
  12. binaryFeatures.useArrayBufferView = !binaryFeatures.useBlobBuilder && (function(){
  13. try {
  14. return (new Blob([new Uint8Array([])])).size === 0;
  15. } catch (e) {
  16. return true;
  17. }
  18. })();
  19. exports.binaryFeatures = binaryFeatures;
  20. exports.BlobBuilder = window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder || window.BlobBuilder;
  21. function BufferBuilder(){
  22. this._pieces = [];
  23. this._parts = [];
  24. }
  25. BufferBuilder.prototype.append = function(data) {
  26. if(typeof data === 'number') {
  27. this._pieces.push(data);
  28. } else {
  29. this.flush();
  30. this._parts.push(data);
  31. }
  32. };
  33. BufferBuilder.prototype.flush = function() {
  34. if (this._pieces.length > 0) {
  35. var buf = new Uint8Array(this._pieces);
  36. if(!binaryFeatures.useArrayBufferView) {
  37. buf = buf.buffer;
  38. }
  39. this._parts.push(buf);
  40. this._pieces = [];
  41. }
  42. };
  43. BufferBuilder.prototype.getBuffer = function() {
  44. this.flush();
  45. if(binaryFeatures.useBlobBuilder) {
  46. var builder = new BlobBuilder();
  47. for(var i = 0, ii = this._parts.length; i < ii; i++) {
  48. builder.append(this._parts[i]);
  49. }
  50. return builder.getBlob();
  51. } else {
  52. return new Blob(this._parts);
  53. }
  54. };
  55. exports.BinaryPack = {
  56. unpack: function(data){
  57. var unpacker = new Unpacker(data);
  58. return unpacker.unpack();
  59. },
  60. pack: function(data){
  61. var packer = new Packer();
  62. packer.pack(data);
  63. var buffer = packer.getBuffer();
  64. return buffer;
  65. }
  66. };
  67. function Unpacker (data){
  68. // Data is ArrayBuffer
  69. this.index = 0;
  70. this.dataBuffer = data;
  71. this.dataView = new Uint8Array(this.dataBuffer);
  72. this.length = this.dataBuffer.byteLength;
  73. }
  74. Unpacker.prototype.unpack = function(){
  75. var type = this.unpack_uint8();
  76. if (type < 0x80){
  77. var positive_fixnum = type;
  78. return positive_fixnum;
  79. } else if ((type ^ 0xe0) < 0x20){
  80. var negative_fixnum = (type ^ 0xe0) - 0x20;
  81. return negative_fixnum;
  82. }
  83. var size;
  84. if ((size = type ^ 0xa0) <= 0x0f){
  85. return this.unpack_raw(size);
  86. } else if ((size = type ^ 0xb0) <= 0x0f){
  87. return this.unpack_string(size);
  88. } else if ((size = type ^ 0x90) <= 0x0f){
  89. return this.unpack_array(size);
  90. } else if ((size = type ^ 0x80) <= 0x0f){
  91. return this.unpack_map(size);
  92. }
  93. switch(type){
  94. case 0xc0:
  95. return null;
  96. case 0xc1:
  97. return undefined;
  98. case 0xc2:
  99. return false;
  100. case 0xc3:
  101. return true;
  102. case 0xca:
  103. return this.unpack_float();
  104. case 0xcb:
  105. return this.unpack_double();
  106. case 0xcc:
  107. return this.unpack_uint8();
  108. case 0xcd:
  109. return this.unpack_uint16();
  110. case 0xce:
  111. return this.unpack_uint32();
  112. case 0xcf:
  113. return this.unpack_uint64();
  114. case 0xd0:
  115. return this.unpack_int8();
  116. case 0xd1:
  117. return this.unpack_int16();
  118. case 0xd2:
  119. return this.unpack_int32();
  120. case 0xd3:
  121. return this.unpack_int64();
  122. case 0xd4:
  123. return undefined;
  124. case 0xd5:
  125. return undefined;
  126. case 0xd6:
  127. return undefined;
  128. case 0xd7:
  129. return undefined;
  130. case 0xd8:
  131. size = this.unpack_uint16();
  132. return this.unpack_string(size);
  133. case 0xd9:
  134. size = this.unpack_uint32();
  135. return this.unpack_string(size);
  136. case 0xda:
  137. size = this.unpack_uint16();
  138. return this.unpack_raw(size);
  139. case 0xdb:
  140. size = this.unpack_uint32();
  141. return this.unpack_raw(size);
  142. case 0xdc:
  143. size = this.unpack_uint16();
  144. return this.unpack_array(size);
  145. case 0xdd:
  146. size = this.unpack_uint32();
  147. return this.unpack_array(size);
  148. case 0xde:
  149. size = this.unpack_uint16();
  150. return this.unpack_map(size);
  151. case 0xdf:
  152. size = this.unpack_uint32();
  153. return this.unpack_map(size);
  154. }
  155. }
  156. Unpacker.prototype.unpack_uint8 = function(){
  157. var byte = this.dataView[this.index] & 0xff;
  158. this.index++;
  159. return byte;
  160. };
  161. Unpacker.prototype.unpack_uint16 = function(){
  162. var bytes = this.read(2);
  163. var uint16 =
  164. ((bytes[0] & 0xff) * 256) + (bytes[1] & 0xff);
  165. this.index += 2;
  166. return uint16;
  167. }
  168. Unpacker.prototype.unpack_uint32 = function(){
  169. var bytes = this.read(4);
  170. var uint32 =
  171. ((bytes[0] * 256 +
  172. bytes[1]) * 256 +
  173. bytes[2]) * 256 +
  174. bytes[3];
  175. this.index += 4;
  176. return uint32;
  177. }
  178. Unpacker.prototype.unpack_uint64 = function(){
  179. var bytes = this.read(8);
  180. var uint64 =
  181. ((((((bytes[0] * 256 +
  182. bytes[1]) * 256 +
  183. bytes[2]) * 256 +
  184. bytes[3]) * 256 +
  185. bytes[4]) * 256 +
  186. bytes[5]) * 256 +
  187. bytes[6]) * 256 +
  188. bytes[7];
  189. this.index += 8;
  190. return uint64;
  191. }
  192. Unpacker.prototype.unpack_int8 = function(){
  193. var uint8 = this.unpack_uint8();
  194. return (uint8 < 0x80 ) ? uint8 : uint8 - (1 << 8);
  195. };
  196. Unpacker.prototype.unpack_int16 = function(){
  197. var uint16 = this.unpack_uint16();
  198. return (uint16 < 0x8000 ) ? uint16 : uint16 - (1 << 16);
  199. }
  200. Unpacker.prototype.unpack_int32 = function(){
  201. var uint32 = this.unpack_uint32();
  202. return (uint32 < Math.pow(2, 31) ) ? uint32 :
  203. uint32 - Math.pow(2, 32);
  204. }
  205. Unpacker.prototype.unpack_int64 = function(){
  206. var uint64 = this.unpack_uint64();
  207. return (uint64 < Math.pow(2, 63) ) ? uint64 :
  208. uint64 - Math.pow(2, 64);
  209. }
  210. Unpacker.prototype.unpack_raw = function(size){
  211. if ( this.length < this.index + size){
  212. throw new Error('BinaryPackFailure: index is out of range'
  213. + ' ' + this.index + ' ' + size + ' ' + this.length);
  214. }
  215. var buf = this.dataBuffer.slice(this.index, this.index + size);
  216. this.index += size;
  217. //buf = util.bufferToString(buf);
  218. return buf;
  219. }
  220. Unpacker.prototype.unpack_string = function(size){
  221. var bytes = this.read(size);
  222. var i = 0, str = '', c, code;
  223. while(i < size){
  224. c = bytes[i];
  225. if ( c < 128){
  226. str += String.fromCharCode(c);
  227. i++;
  228. } else if ((c ^ 0xc0) < 32){
  229. code = ((c ^ 0xc0) << 6) | (bytes[i+1] & 63);
  230. str += String.fromCharCode(code);
  231. i += 2;
  232. } else {
  233. code = ((c & 15) << 12) | ((bytes[i+1] & 63) << 6) |
  234. (bytes[i+2] & 63);
  235. str += String.fromCharCode(code);
  236. i += 3;
  237. }
  238. }
  239. this.index += size;
  240. return str;
  241. }
  242. Unpacker.prototype.unpack_array = function(size){
  243. var objects = new Array(size);
  244. for(var i = 0; i < size ; i++){
  245. objects[i] = this.unpack();
  246. }
  247. return objects;
  248. }
  249. Unpacker.prototype.unpack_map = function(size){
  250. var map = {};
  251. for(var i = 0; i < size ; i++){
  252. var key = this.unpack();
  253. var value = this.unpack();
  254. map[key] = value;
  255. }
  256. return map;
  257. }
  258. Unpacker.prototype.unpack_float = function(){
  259. var uint32 = this.unpack_uint32();
  260. var sign = uint32 >> 31;
  261. var exp = ((uint32 >> 23) & 0xff) - 127;
  262. var fraction = ( uint32 & 0x7fffff ) | 0x800000;
  263. return (sign == 0 ? 1 : -1) *
  264. fraction * Math.pow(2, exp - 23);
  265. }
  266. Unpacker.prototype.unpack_double = function(){
  267. var h32 = this.unpack_uint32();
  268. var l32 = this.unpack_uint32();
  269. var sign = h32 >> 31;
  270. var exp = ((h32 >> 20) & 0x7ff) - 1023;
  271. var hfrac = ( h32 & 0xfffff ) | 0x100000;
  272. var frac = hfrac * Math.pow(2, exp - 20) +
  273. l32 * Math.pow(2, exp - 52);
  274. return (sign == 0 ? 1 : -1) * frac;
  275. }
  276. Unpacker.prototype.read = function(length){
  277. var j = this.index;
  278. if (j + length <= this.length) {
  279. return this.dataView.subarray(j, j + length);
  280. } else {
  281. throw new Error('BinaryPackFailure: read index out of range');
  282. }
  283. }
  284. function Packer(){
  285. this.bufferBuilder = new BufferBuilder();
  286. }
  287. Packer.prototype.getBuffer = function(){
  288. return this.bufferBuilder.getBuffer();
  289. }
  290. Packer.prototype.pack = function(value){
  291. var type = typeof(value);
  292. if (type == 'string'){
  293. this.pack_string(value);
  294. } else if (type == 'number'){
  295. if (Math.floor(value) === value){
  296. this.pack_integer(value);
  297. } else{
  298. this.pack_double(value);
  299. }
  300. } else if (type == 'boolean'){
  301. if (value === true){
  302. this.bufferBuilder.append(0xc3);
  303. } else if (value === false){
  304. this.bufferBuilder.append(0xc2);
  305. }
  306. } else if (type == 'undefined'){
  307. this.bufferBuilder.append(0xc0);
  308. } else if (type == 'object'){
  309. if (value === null){
  310. this.bufferBuilder.append(0xc0);
  311. } else {
  312. var constructor = value.constructor;
  313. if (constructor == Array){
  314. this.pack_array(value);
  315. } else if (constructor == Blob || constructor == File) {
  316. this.pack_bin(value);
  317. } else if (constructor == ArrayBuffer) {
  318. if(binaryFeatures.useArrayBufferView) {
  319. this.pack_bin(new Uint8Array(value));
  320. } else {
  321. this.pack_bin(value);
  322. }
  323. } else if ('BYTES_PER_ELEMENT' in value){
  324. if(binaryFeatures.useArrayBufferView) {
  325. this.pack_bin(new Uint8Array(value.buffer));
  326. } else {
  327. this.pack_bin(value.buffer);
  328. }
  329. } else if (constructor == Object){
  330. this.pack_object(value);
  331. } else if (constructor == Date){
  332. this.pack_string(value.toString());
  333. } else if (typeof value.toBinaryPack == 'function'){
  334. this.bufferBuilder.append(value.toBinaryPack());
  335. } else {
  336. throw new Error('Type "' + constructor.toString() + '" not yet supported');
  337. }
  338. }
  339. } else {
  340. throw new Error('Type "' + type + '" not yet supported');
  341. }
  342. this.bufferBuilder.flush();
  343. }
  344. Packer.prototype.pack_bin = function(blob){
  345. var length = blob.length || blob.byteLength || blob.size;
  346. if (length <= 0x0f){
  347. this.pack_uint8(0xa0 + length);
  348. } else if (length <= 0xffff){
  349. this.bufferBuilder.append(0xda) ;
  350. this.pack_uint16(length);
  351. } else if (length <= 0xffffffff){
  352. this.bufferBuilder.append(0xdb);
  353. this.pack_uint32(length);
  354. } else{
  355. throw new Error('Invalid length');
  356. return;
  357. }
  358. this.bufferBuilder.append(blob);
  359. }
  360. Packer.prototype.pack_string = function(str){
  361. var length = utf8Length(str);
  362. if (length <= 0x0f){
  363. this.pack_uint8(0xb0 + length);
  364. } else if (length <= 0xffff){
  365. this.bufferBuilder.append(0xd8) ;
  366. this.pack_uint16(length);
  367. } else if (length <= 0xffffffff){
  368. this.bufferBuilder.append(0xd9);
  369. this.pack_uint32(length);
  370. } else{
  371. throw new Error('Invalid length');
  372. return;
  373. }
  374. this.bufferBuilder.append(str);
  375. }
  376. Packer.prototype.pack_array = function(ary){
  377. var length = ary.length;
  378. if (length <= 0x0f){
  379. this.pack_uint8(0x90 + length);
  380. } else if (length <= 0xffff){
  381. this.bufferBuilder.append(0xdc)
  382. this.pack_uint16(length);
  383. } else if (length <= 0xffffffff){
  384. this.bufferBuilder.append(0xdd);
  385. this.pack_uint32(length);
  386. } else{
  387. throw new Error('Invalid length');
  388. }
  389. for(var i = 0; i < length ; i++){
  390. this.pack(ary[i]);
  391. }
  392. }
  393. Packer.prototype.pack_integer = function(num){
  394. if ( -0x20 <= num && num <= 0x7f){
  395. this.bufferBuilder.append(num & 0xff);
  396. } else if (0x00 <= num && num <= 0xff){
  397. this.bufferBuilder.append(0xcc);
  398. this.pack_uint8(num);
  399. } else if (-0x80 <= num && num <= 0x7f){
  400. this.bufferBuilder.append(0xd0);
  401. this.pack_int8(num);
  402. } else if ( 0x0000 <= num && num <= 0xffff){
  403. this.bufferBuilder.append(0xcd);
  404. this.pack_uint16(num);
  405. } else if (-0x8000 <= num && num <= 0x7fff){
  406. this.bufferBuilder.append(0xd1);
  407. this.pack_int16(num);
  408. } else if ( 0x00000000 <= num && num <= 0xffffffff){
  409. this.bufferBuilder.append(0xce);
  410. this.pack_uint32(num);
  411. } else if (-0x80000000 <= num && num <= 0x7fffffff){
  412. this.bufferBuilder.append(0xd2);
  413. this.pack_int32(num);
  414. } else if (-0x8000000000000000 <= num && num <= 0x7FFFFFFFFFFFFFFF){
  415. this.bufferBuilder.append(0xd3);
  416. this.pack_int64(num);
  417. } else if (0x0000000000000000 <= num && num <= 0xFFFFFFFFFFFFFFFF){
  418. this.bufferBuilder.append(0xcf);
  419. this.pack_uint64(num);
  420. } else{
  421. throw new Error('Invalid integer');
  422. }
  423. }
  424. Packer.prototype.pack_double = function(num){
  425. var sign = 0;
  426. if (num < 0){
  427. sign = 1;
  428. num = -num;
  429. }
  430. var exp = Math.floor(Math.log(num) / Math.LN2);
  431. var frac0 = num / Math.pow(2, exp) - 1;
  432. var frac1 = Math.floor(frac0 * Math.pow(2, 52));
  433. var b32 = Math.pow(2, 32);
  434. var h32 = (sign << 31) | ((exp+1023) << 20) |
  435. (frac1 / b32) & 0x0fffff;
  436. var l32 = frac1 % b32;
  437. this.bufferBuilder.append(0xcb);
  438. this.pack_int32(h32);
  439. this.pack_int32(l32);
  440. }
  441. Packer.prototype.pack_object = function(obj){
  442. var keys = Object.keys(obj);
  443. var length = keys.length;
  444. if (length <= 0x0f){
  445. this.pack_uint8(0x80 + length);
  446. } else if (length <= 0xffff){
  447. this.bufferBuilder.append(0xde);
  448. this.pack_uint16(length);
  449. } else if (length <= 0xffffffff){
  450. this.bufferBuilder.append(0xdf);
  451. this.pack_uint32(length);
  452. } else{
  453. throw new Error('Invalid length');
  454. }
  455. for(var prop in obj){
  456. if (obj.hasOwnProperty(prop)){
  457. this.pack(prop);
  458. this.pack(obj[prop]);
  459. }
  460. }
  461. }
  462. Packer.prototype.pack_uint8 = function(num){
  463. this.bufferBuilder.append(num);
  464. }
  465. Packer.prototype.pack_uint16 = function(num){
  466. this.bufferBuilder.append(num >> 8);
  467. this.bufferBuilder.append(num & 0xff);
  468. }
  469. Packer.prototype.pack_uint32 = function(num){
  470. var n = num & 0xffffffff;
  471. this.bufferBuilder.append((n & 0xff000000) >>> 24);
  472. this.bufferBuilder.append((n & 0x00ff0000) >>> 16);
  473. this.bufferBuilder.append((n & 0x0000ff00) >>> 8);
  474. this.bufferBuilder.append((n & 0x000000ff));
  475. }
  476. Packer.prototype.pack_uint64 = function(num){
  477. var high = num / Math.pow(2, 32);
  478. var low = num % Math.pow(2, 32);
  479. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  480. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  481. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  482. this.bufferBuilder.append((high & 0x000000ff));
  483. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  484. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  485. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  486. this.bufferBuilder.append((low & 0x000000ff));
  487. }
  488. Packer.prototype.pack_int8 = function(num){
  489. this.bufferBuilder.append(num & 0xff);
  490. }
  491. Packer.prototype.pack_int16 = function(num){
  492. this.bufferBuilder.append((num & 0xff00) >> 8);
  493. this.bufferBuilder.append(num & 0xff);
  494. }
  495. Packer.prototype.pack_int32 = function(num){
  496. this.bufferBuilder.append((num >>> 24) & 0xff);
  497. this.bufferBuilder.append((num & 0x00ff0000) >>> 16);
  498. this.bufferBuilder.append((num & 0x0000ff00) >>> 8);
  499. this.bufferBuilder.append((num & 0x000000ff));
  500. }
  501. Packer.prototype.pack_int64 = function(num){
  502. var high = Math.floor(num / Math.pow(2, 32));
  503. var low = num % Math.pow(2, 32);
  504. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  505. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  506. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  507. this.bufferBuilder.append((high & 0x000000ff));
  508. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  509. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  510. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  511. this.bufferBuilder.append((low & 0x000000ff));
  512. }
  513. function _utf8Replace(m){
  514. var code = m.charCodeAt(0);
  515. if(code <= 0x7ff) return '00';
  516. if(code <= 0xffff) return '000';
  517. if(code <= 0x1fffff) return '0000';
  518. if(code <= 0x3ffffff) return '00000';
  519. return '000000';
  520. }
  521. function utf8Length(str){
  522. if (str.length > 600) {
  523. // Blob method faster for large strings
  524. return (new Blob([str])).size;
  525. } else {
  526. return str.replace(/[^\u0000-\u007F]/g, _utf8Replace).length;
  527. }
  528. }
  529. /**
  530. * Light EventEmitter. Ported from Node.js/events.js
  531. * Eric Zhang
  532. */
  533. /**
  534. * EventEmitter class
  535. * Creates an object with event registering and firing methods
  536. */
  537. function EventEmitter() {
  538. // Initialise required storage variables
  539. this._events = {};
  540. }
  541. var isArray = Array.isArray;
  542. EventEmitter.prototype.addListener = function(type, listener, scope, once) {
  543. if ('function' !== typeof listener) {
  544. throw new Error('addListener only takes instances of Function');
  545. }
  546. // To avoid recursion in the case that type == "newListeners"! Before
  547. // adding it to the listeners, first emit "newListeners".
  548. this.emit('newListener', type, typeof listener.listener === 'function' ?
  549. listener.listener : listener);
  550. if (!this._events[type]) {
  551. // Optimize the case of one listener. Don't need the extra array object.
  552. this._events[type] = listener;
  553. } else if (isArray(this._events[type])) {
  554. // If we've already got an array, just append.
  555. this._events[type].push(listener);
  556. } else {
  557. // Adding the second element, need to change to array.
  558. this._events[type] = [this._events[type], listener];
  559. }
  560. return this;
  561. };
  562. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  563. EventEmitter.prototype.once = function(type, listener, scope) {
  564. if ('function' !== typeof listener) {
  565. throw new Error('.once only takes instances of Function');
  566. }
  567. var self = this;
  568. function g() {
  569. self.removeListener(type, g);
  570. listener.apply(this, arguments);
  571. };
  572. g.listener = listener;
  573. self.on(type, g);
  574. return this;
  575. };
  576. EventEmitter.prototype.removeListener = function(type, listener, scope) {
  577. if ('function' !== typeof listener) {
  578. throw new Error('removeListener only takes instances of Function');
  579. }
  580. // does not use listeners(), so no side effect of creating _events[type]
  581. if (!this._events[type]) return this;
  582. var list = this._events[type];
  583. if (isArray(list)) {
  584. var position = -1;
  585. for (var i = 0, length = list.length; i < length; i++) {
  586. if (list[i] === listener ||
  587. (list[i].listener && list[i].listener === listener))
  588. {
  589. position = i;
  590. break;
  591. }
  592. }
  593. if (position < 0) return this;
  594. list.splice(position, 1);
  595. if (list.length == 0)
  596. delete this._events[type];
  597. } else if (list === listener ||
  598. (list.listener && list.listener === listener))
  599. {
  600. delete this._events[type];
  601. }
  602. return this;
  603. };
  604. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  605. EventEmitter.prototype.removeAllListeners = function(type) {
  606. if (arguments.length === 0) {
  607. this._events = {};
  608. return this;
  609. }
  610. // does not use listeners(), so no side effect of creating _events[type]
  611. if (type && this._events && this._events[type]) this._events[type] = null;
  612. return this;
  613. };
  614. EventEmitter.prototype.listeners = function(type) {
  615. if (!this._events[type]) this._events[type] = [];
  616. if (!isArray(this._events[type])) {
  617. this._events[type] = [this._events[type]];
  618. }
  619. return this._events[type];
  620. };
  621. EventEmitter.prototype.emit = function(type) {
  622. var type = arguments[0];
  623. var handler = this._events[type];
  624. if (!handler) return false;
  625. if (typeof handler == 'function') {
  626. switch (arguments.length) {
  627. // fast cases
  628. case 1:
  629. handler.call(this);
  630. break;
  631. case 2:
  632. handler.call(this, arguments[1]);
  633. break;
  634. case 3:
  635. handler.call(this, arguments[1], arguments[2]);
  636. break;
  637. // slower
  638. default:
  639. var l = arguments.length;
  640. var args = new Array(l - 1);
  641. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  642. handler.apply(this, args);
  643. }
  644. return true;
  645. } else if (isArray(handler)) {
  646. var l = arguments.length;
  647. var args = new Array(l - 1);
  648. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  649. var listeners = handler.slice();
  650. for (var i = 0, l = listeners.length; i < l; i++) {
  651. listeners[i].apply(this, args);
  652. }
  653. return true;
  654. } else {
  655. return false;
  656. }
  657. };
  658. /**
  659. * Reliable transfer for Chrome Canary DataChannel impl.
  660. * Author: @michellebu
  661. */
  662. function Reliable(dc, debug) {
  663. if (!(this instanceof Reliable)) return new Reliable(dc);
  664. this._dc = dc;
  665. util.debug = debug;
  666. // Messages sent/received so far.
  667. // id: { ack: n, chunks: [...] }
  668. this._outgoing = {};
  669. // id: { ack: ['ack', id, n], chunks: [...] }
  670. this._incoming = {};
  671. this._received = {};
  672. // Window size.
  673. this._window = 1000;
  674. // MTU.
  675. this._mtu = 500;
  676. // Interval for setInterval. In ms.
  677. this._interval = 0;
  678. // Messages sent.
  679. this._count = 0;
  680. // Outgoing message queue.
  681. this._queue = [];
  682. this._setupDC();
  683. };
  684. // Send a message reliably.
  685. Reliable.prototype.send = function(msg) {
  686. // Determine if chunking is necessary.
  687. var bl = util.pack(msg);
  688. if (bl.size < this._mtu) {
  689. this._handleSend(['no', bl]);
  690. return;
  691. }
  692. this._outgoing[this._count] = {
  693. ack: 0,
  694. chunks: this._chunk(bl)
  695. };
  696. if (util.debug) {
  697. this._outgoing[this._count].timer = new Date();
  698. }
  699. // Send prelim window.
  700. this._sendWindowedChunks(this._count);
  701. this._count += 1;
  702. };
  703. // Set up interval for processing queue.
  704. Reliable.prototype._setupInterval = function() {
  705. // TODO: fail gracefully.
  706. var self = this;
  707. this._timeout = setInterval(function() {
  708. // FIXME: String stuff makes things terribly async.
  709. var msg = self._queue.shift();
  710. if (msg._multiple) {
  711. for (var i = 0, ii = msg.length; i < ii; i += 1) {
  712. self._intervalSend(msg[i]);
  713. }
  714. } else {
  715. self._intervalSend(msg);
  716. }
  717. }, this._interval);
  718. };
  719. Reliable.prototype._intervalSend = function(msg) {
  720. var self = this;
  721. msg = util.pack(msg);
  722. util.blobToBinaryString(msg, function(str) {
  723. self._dc.send(str);
  724. });
  725. if (self._queue.length === 0) {
  726. clearTimeout(self._timeout);
  727. self._timeout = null;
  728. //self._processAcks();
  729. }
  730. };
  731. // Go through ACKs to send missing pieces.
  732. Reliable.prototype._processAcks = function() {
  733. for (var id in this._outgoing) {
  734. if (this._outgoing.hasOwnProperty(id)) {
  735. this._sendWindowedChunks(id);
  736. }
  737. }
  738. };
  739. // Handle sending a message.
  740. // FIXME: Don't wait for interval time for all messages...
  741. Reliable.prototype._handleSend = function(msg) {
  742. var push = true;
  743. for (var i = 0, ii = this._queue.length; i < ii; i += 1) {
  744. var item = this._queue[i];
  745. if (item === msg) {
  746. push = false;
  747. } else if (item._multiple && item.indexOf(msg) !== -1) {
  748. push = false;
  749. }
  750. }
  751. if (push) {
  752. this._queue.push(msg);
  753. if (!this._timeout) {
  754. this._setupInterval();
  755. }
  756. }
  757. };
  758. // Set up DataChannel handlers.
  759. Reliable.prototype._setupDC = function() {
  760. // Handle various message types.
  761. var self = this;
  762. this._dc.onmessage = function(e) {
  763. var msg = e.data;
  764. var datatype = msg.constructor;
  765. // FIXME: msg is String until binary is supported.
  766. // Once that happens, this will have to be smarter.
  767. if (datatype === String) {
  768. var ab = util.binaryStringToArrayBuffer(msg);
  769. msg = util.unpack(ab);
  770. self._handleMessage(msg);
  771. }
  772. };
  773. };
  774. // Handles an incoming message.
  775. Reliable.prototype._handleMessage = function(msg) {
  776. var id = msg[1];
  777. var idata = this._incoming[id];
  778. var odata = this._outgoing[id];
  779. var data;
  780. switch (msg[0]) {
  781. // No chunking was done.
  782. case 'no':
  783. var message = id;
  784. if (!!message) {
  785. this.onmessage(util.unpack(message));
  786. }
  787. break;
  788. // Reached the end of the message.
  789. case 'end':
  790. data = idata;
  791. // In case end comes first.
  792. this._received[id] = msg[2];
  793. if (!data) {
  794. break;
  795. }
  796. this._ack(id);
  797. break;
  798. case 'ack':
  799. data = odata;
  800. if (!!data) {
  801. var ack = msg[2];
  802. // Take the larger ACK, for out of order messages.
  803. data.ack = Math.max(ack, data.ack);
  804. // Clean up when all chunks are ACKed.
  805. if (data.ack >= data.chunks.length) {
  806. util.log('Time: ', new Date() - data.timer);
  807. delete this._outgoing[id];
  808. } else {
  809. this._processAcks();
  810. }
  811. }
  812. // If !data, just ignore.
  813. break;
  814. // Received a chunk of data.
  815. case 'chunk':
  816. // Create a new entry if none exists.
  817. data = idata;
  818. if (!data) {
  819. var end = this._received[id];
  820. if (end === true) {
  821. break;
  822. }
  823. data = {
  824. ack: ['ack', id, 0],
  825. chunks: []
  826. };
  827. this._incoming[id] = data;
  828. }
  829. var n = msg[2];
  830. var chunk = msg[3];
  831. data.chunks[n] = new Uint8Array(chunk);
  832. // If we get the chunk we're looking for, ACK for next missing.
  833. // Otherwise, ACK the same N again.
  834. if (n === data.ack[2]) {
  835. this._calculateNextAck(id);
  836. }
  837. this._ack(id);
  838. break;
  839. default:
  840. // Shouldn't happen, but would make sense for message to just go
  841. // through as is.
  842. this._handleSend(msg);
  843. break;
  844. }
  845. };
  846. // Chunks BL into smaller messages.
  847. Reliable.prototype._chunk = function(bl) {
  848. var chunks = [];
  849. var size = bl.size;
  850. var start = 0;
  851. while (start < size) {
  852. var end = Math.min(size, start + this._mtu);
  853. var b = bl.slice(start, end);
  854. var chunk = {
  855. payload: b
  856. }
  857. chunks.push(chunk);
  858. start = end;
  859. }
  860. util.log('Created', chunks.length, 'chunks.');
  861. return chunks;
  862. };
  863. // Sends ACK N, expecting Nth blob chunk for message ID.
  864. Reliable.prototype._ack = function(id) {
  865. var ack = this._incoming[id].ack;
  866. // if ack is the end value, then call _complete.
  867. if (this._received[id] === ack[2]) {
  868. this._complete(id);
  869. this._received[id] = true;
  870. }
  871. this._handleSend(ack);
  872. };
  873. // Calculates the next ACK number, given chunks.
  874. Reliable.prototype._calculateNextAck = function(id) {
  875. var data = this._incoming[id];
  876. var chunks = data.chunks;
  877. for (var i = 0, ii = chunks.length; i < ii; i += 1) {
  878. // This chunk is missing!!! Better ACK for it.
  879. if (chunks[i] === undefined) {
  880. data.ack[2] = i;
  881. return;
  882. }
  883. }
  884. data.ack[2] = chunks.length;
  885. };
  886. // Sends the next window of chunks.
  887. Reliable.prototype._sendWindowedChunks = function(id) {
  888. util.log('sendWindowedChunks for: ', id);
  889. var data = this._outgoing[id];
  890. var ch = data.chunks;
  891. var chunks = [];
  892. var limit = Math.min(data.ack + this._window, ch.length);
  893. for (var i = data.ack; i < limit; i += 1) {
  894. if (!ch[i].sent || i === data.ack) {
  895. ch[i].sent = true;
  896. chunks.push(['chunk', id, i, ch[i].payload]);
  897. }
  898. }
  899. if (data.ack + this._window >= ch.length) {
  900. chunks.push(['end', id, ch.length])
  901. }
  902. chunks._multiple = true;
  903. this._handleSend(chunks);
  904. };
  905. // Puts together a message from chunks.
  906. Reliable.prototype._complete = function(id) {
  907. util.log('Completed called for', id);
  908. var self = this;
  909. var chunks = this._incoming[id].chunks;
  910. var bl = new Blob(chunks);
  911. util.blobToArrayBuffer(bl, function(ab) {
  912. self.onmessage(util.unpack(ab));
  913. });
  914. delete this._incoming[id];
  915. };
  916. // Ups bandwidth limit on SDP. Meant to be called during offer/answer.
  917. Reliable.higherBandwidthSDP = function(sdp) {
  918. // AS stands for Application-Specific Maximum.
  919. // Bandwidth number is in kilobits / sec.
  920. // See RFC for more info: http://www.ietf.org/rfc/rfc2327.txt
  921. // Chrome 31+ doesn't want us munging the SDP, so we'll let them have their
  922. // way.
  923. var version = navigator.appVersion.match(/Chrome\/(.*?) /);
  924. if (version) {
  925. version = parseInt(version[1].split('.').shift());
  926. if (version < 31) {
  927. var parts = sdp.split('b=AS:30');
  928. var replace = 'b=AS:102400'; // 100 Mbps
  929. if (parts.length > 1) {
  930. return parts[0] + replace + parts[1];
  931. }
  932. }
  933. }
  934. return sdp;
  935. };
  936. // Overwritten, typically.
  937. Reliable.prototype.onmessage = function(msg) {};
  938. exports.Reliable = Reliable;
  939. exports.RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription;
  940. exports.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  941. exports.RTCIceCandidate = window.RTCIceCandidate || window.mozRTCIceCandidate;
  942. var defaultConfig = {'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }]};
  943. var dataCount = 1;
  944. var util = {
  945. noop: function() {},
  946. CLOUD_HOST: '0.peerjs.com',
  947. CLOUD_PORT: 9000,
  948. // Browsers that need chunking:
  949. chunkedBrowsers: {'Chrome': 1},
  950. chunkedMTU: 16300, // The original 60000 bytes setting does not work when sending data from Firefox to Chrome, which is "cut off" after 16384 bytes and delivered individually.
  951. // Logging logic
  952. logLevel: 0,
  953. setLogLevel: function(level) {
  954. var debugLevel = parseInt(level, 10);
  955. if (!isNaN(parseInt(level, 10))) {
  956. util.logLevel = debugLevel;
  957. } else {
  958. // If they are using truthy/falsy values for debug
  959. util.logLevel = level ? 3 : 0;
  960. }
  961. util.log = util.warn = util.error = util.noop;
  962. if (util.logLevel > 0) {
  963. util.error = util._printWith('ERROR');
  964. }
  965. if (util.logLevel > 1) {
  966. util.warn = util._printWith('WARNING');
  967. }
  968. if (util.logLevel > 2) {
  969. util.log = util._print;
  970. }
  971. },
  972. setLogFunction: function(fn) {
  973. if (fn.constructor !== Function) {
  974. util.warn('The log function you passed in is not a function. Defaulting to regular logs.');
  975. } else {
  976. util._print = fn;
  977. }
  978. },
  979. _printWith: function(prefix) {
  980. return function() {
  981. var copy = Array.prototype.slice.call(arguments);
  982. copy.unshift(prefix);
  983. util._print.apply(util, copy);
  984. };
  985. },
  986. _print: function () {
  987. var err = false;
  988. var copy = Array.prototype.slice.call(arguments);
  989. copy.unshift('PeerJS: ');
  990. for (var i = 0, l = copy.length; i < l; i++){
  991. if (copy[i] instanceof Error) {
  992. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  993. err = true;
  994. }
  995. }
  996. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  997. },
  998. //
  999. // Returns browser-agnostic default config
  1000. defaultConfig: defaultConfig,
  1001. //
  1002. // Returns the current browser.
  1003. browser: (function() {
  1004. if (window.mozRTCPeerConnection) {
  1005. return 'Firefox';
  1006. } else if (window.webkitRTCPeerConnection) {
  1007. return 'Chrome';
  1008. } else if (window.RTCPeerConnection) {
  1009. return 'Supported';
  1010. } else {
  1011. return 'Unsupported';
  1012. }
  1013. })(),
  1014. //
  1015. // Lists which features are supported
  1016. supports: (function() {
  1017. if (typeof RTCPeerConnection === 'undefined') {
  1018. return {};
  1019. }
  1020. var data = true;
  1021. var audioVideo = true;
  1022. var binaryBlob = false;
  1023. var sctp = false;
  1024. var onnegotiationneeded = !!window.webkitRTCPeerConnection;
  1025. var pc, dc;
  1026. try {
  1027. pc = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  1028. } catch (e) {
  1029. data = false;
  1030. audioVideo = false;
  1031. }
  1032. if (data) {
  1033. try {
  1034. dc = pc.createDataChannel('_PEERJSTEST');
  1035. } catch (e) {
  1036. data = false;
  1037. }
  1038. }
  1039. if (data) {
  1040. // Binary test
  1041. try {
  1042. dc.binaryType = 'blob';
  1043. binaryBlob = true;
  1044. } catch (e) {
  1045. }
  1046. // Reliable test.
  1047. // Unfortunately Chrome is a bit unreliable about whether or not they
  1048. // support reliable.
  1049. var reliablePC = new RTCPeerConnection(defaultConfig, {});
  1050. try {
  1051. var reliableDC = reliablePC.createDataChannel('_PEERJSRELIABLETEST', {});
  1052. sctp = reliableDC.reliable;
  1053. } catch (e) {
  1054. }
  1055. reliablePC.close();
  1056. }
  1057. // FIXME: not really the best check...
  1058. if (audioVideo) {
  1059. audioVideo = !!pc.addStream;
  1060. }
  1061. // FIXME: this is not great because in theory it doesn't work for
  1062. // av-only browsers (?).
  1063. if (!onnegotiationneeded && data) {
  1064. // sync default check.
  1065. var negotiationPC = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  1066. negotiationPC.onnegotiationneeded = function() {
  1067. onnegotiationneeded = true;
  1068. // async check.
  1069. if (util && util.supports) {
  1070. util.supports.onnegotiationneeded = true;
  1071. }
  1072. };
  1073. var negotiationDC = negotiationPC.createDataChannel('_PEERJSNEGOTIATIONTEST');
  1074. setTimeout(function() {
  1075. negotiationPC.close();
  1076. }, 1000);
  1077. }
  1078. if (pc) {
  1079. pc.close();
  1080. }
  1081. return {
  1082. audioVideo: audioVideo,
  1083. data: data,
  1084. binaryBlob: binaryBlob,
  1085. binary: sctp, // deprecated; sctp implies binary support.
  1086. reliable: sctp, // deprecated; sctp implies reliable data.
  1087. sctp: sctp,
  1088. onnegotiationneeded: onnegotiationneeded
  1089. };
  1090. }()),
  1091. //
  1092. // Ensure alphanumeric ids
  1093. validateId: function(id) {
  1094. // Allow empty ids
  1095. return !id || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id);
  1096. },
  1097. validateKey: function(key) {
  1098. // Allow empty keys
  1099. return !key || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(key);
  1100. },
  1101. debug: false,
  1102. inherits: function(ctor, superCtor) {
  1103. ctor.super_ = superCtor;
  1104. ctor.prototype = Object.create(superCtor.prototype, {
  1105. constructor: {
  1106. value: ctor,
  1107. enumerable: false,
  1108. writable: true,
  1109. configurable: true
  1110. }
  1111. });
  1112. },
  1113. extend: function(dest, source) {
  1114. for(var key in source) {
  1115. if(source.hasOwnProperty(key)) {
  1116. dest[key] = source[key];
  1117. }
  1118. }
  1119. return dest;
  1120. },
  1121. pack: BinaryPack.pack,
  1122. unpack: BinaryPack.unpack,
  1123. log: function () {
  1124. if (util.debug) {
  1125. var err = false;
  1126. var copy = Array.prototype.slice.call(arguments);
  1127. copy.unshift('PeerJS: ');
  1128. for (var i = 0, l = copy.length; i < l; i++){
  1129. if (copy[i] instanceof Error) {
  1130. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  1131. err = true;
  1132. }
  1133. }
  1134. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  1135. }
  1136. },
  1137. setZeroTimeout: (function(global) {
  1138. var timeouts = [];
  1139. var messageName = 'zero-timeout-message';
  1140. // Like setTimeout, but only takes a function argument. There's
  1141. // no time argument (always zero) and no arguments (you have to
  1142. // use a closure).
  1143. function setZeroTimeoutPostMessage(fn) {
  1144. timeouts.push(fn);
  1145. global.postMessage(messageName, '*');
  1146. }
  1147. function handleMessage(event) {
  1148. if (event.source == global && event.data == messageName) {
  1149. if (event.stopPropagation) {
  1150. event.stopPropagation();
  1151. }
  1152. if (timeouts.length) {
  1153. timeouts.shift()();
  1154. }
  1155. }
  1156. }
  1157. if (global.addEventListener) {
  1158. global.addEventListener('message', handleMessage, true);
  1159. } else if (global.attachEvent) {
  1160. global.attachEvent('onmessage', handleMessage);
  1161. }
  1162. return setZeroTimeoutPostMessage;
  1163. }(this)),
  1164. // Binary stuff
  1165. // chunks a blob.
  1166. chunk: function(bl) {
  1167. var chunks = [];
  1168. var size = bl.size;
  1169. var start = index = 0;
  1170. var total = Math.ceil(size / util.chunkedMTU);
  1171. while (start < size) {
  1172. var end = Math.min(size, start + util.chunkedMTU);
  1173. var b = bl.slice(start, end);
  1174. var chunk = {
  1175. __peerData: dataCount,
  1176. n: index,
  1177. data: b,
  1178. total: total
  1179. };
  1180. chunks.push(chunk);
  1181. start = end;
  1182. index += 1;
  1183. }
  1184. dataCount += 1;
  1185. return chunks;
  1186. },
  1187. blobToArrayBuffer: function(blob, cb){
  1188. var fr = new FileReader();
  1189. fr.onload = function(evt) {
  1190. cb(evt.target.result);
  1191. };
  1192. fr.readAsArrayBuffer(blob);
  1193. },
  1194. blobToBinaryString: function(blob, cb){
  1195. var fr = new FileReader();
  1196. fr.onload = function(evt) {
  1197. cb(evt.target.result);
  1198. };
  1199. fr.readAsBinaryString(blob);
  1200. },
  1201. binaryStringToArrayBuffer: function(binary) {
  1202. var byteArray = new Uint8Array(binary.length);
  1203. for (var i = 0; i < binary.length; i++) {
  1204. byteArray[i] = binary.charCodeAt(i) & 0xff;
  1205. }
  1206. return byteArray.buffer;
  1207. },
  1208. randomToken: function () {
  1209. return Math.random().toString(36).substr(2);
  1210. },
  1211. //
  1212. isSecure: function() {
  1213. return location.protocol === 'https:';
  1214. }
  1215. };
  1216. exports.util = util;
  1217. /**
  1218. * A peer who can initiate connections with other peers.
  1219. */
  1220. function Peer(id, options) {
  1221. if (!(this instanceof Peer)) return new Peer(id, options);
  1222. EventEmitter.call(this);
  1223. // Deal with overloading
  1224. if (id && id.constructor == Object) {
  1225. options = id;
  1226. id = undefined;
  1227. } else if (id) {
  1228. // Ensure id is a string
  1229. id = id.toString();
  1230. }
  1231. //
  1232. // Configurize options
  1233. options = util.extend({
  1234. debug: 0, // 1: Errors, 2: Warnings, 3: All logs
  1235. host: util.CLOUD_HOST,
  1236. port: util.CLOUD_PORT,
  1237. key: 'peerjs',
  1238. path: '/',
  1239. token: util.randomToken(),
  1240. config: util.defaultConfig
  1241. }, options);
  1242. this.options = options;
  1243. // Detect relative URL host.
  1244. if (options.host === '/') {
  1245. options.host = window.location.hostname;
  1246. }
  1247. // Set path correctly.
  1248. if (options.path[0] !== '/') {
  1249. options.path = '/' + options.path;
  1250. }
  1251. if (options.path[options.path.length - 1] !== '/') {
  1252. options.path += '/';
  1253. }
  1254. // Set whether we use SSL to same as current host
  1255. if (options.secure === undefined && options.host !== util.CLOUD_HOST) {
  1256. options.secure = util.isSecure();
  1257. }
  1258. // Set a custom log function if present
  1259. if (options.logFunction) {
  1260. util.setLogFunction(options.logFunction);
  1261. }
  1262. util.setLogLevel(options.debug);
  1263. //
  1264. // Sanity checks
  1265. // Ensure WebRTC supported
  1266. if (!util.supports.audioVideo && !util.supports.data ) {
  1267. this._delayedAbort('browser-incompatible', 'The current browser does not support WebRTC');
  1268. return;
  1269. }
  1270. // Ensure alphanumeric id
  1271. if (!util.validateId(id)) {
  1272. this._delayedAbort('invalid-id', 'ID "' + id + '" is invalid');
  1273. return;
  1274. }
  1275. // Ensure valid key
  1276. if (!util.validateKey(options.key)) {
  1277. this._delayedAbort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  1278. return;
  1279. }
  1280. // Ensure not using unsecure cloud server on SSL page
  1281. if (options.secure && options.host === '0.peerjs.com') {
  1282. this._delayedAbort('ssl-unavailable',
  1283. 'The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS.');
  1284. return;
  1285. }
  1286. //
  1287. // States.
  1288. this.destroyed = false; // Connections have been killed
  1289. this.disconnected = false; // Connection to PeerServer killed but P2P connections still active
  1290. this.open = false; // Sockets and such are not yet open.
  1291. //
  1292. // References
  1293. this.connections = {}; // DataConnections for this peer.
  1294. this._lostMessages = {}; // src => [list of messages]
  1295. //
  1296. // Start the server connection
  1297. this._initializeServerConnection();
  1298. if (id) {
  1299. this._initialize(id);
  1300. } else {
  1301. this._retrieveId();
  1302. }
  1303. //
  1304. };
  1305. util.inherits(Peer, EventEmitter);
  1306. // Initialize the 'socket' (which is actually a mix of XHR streaming and
  1307. // websockets.)
  1308. Peer.prototype._initializeServerConnection = function() {
  1309. var self = this;
  1310. this.socket = new Socket(this.options.secure, this.options.host, this.options.port, this.options.path, this.options.key);
  1311. this.socket.on('message', function(data) {
  1312. self._handleMessage(data);
  1313. });
  1314. this.socket.on('error', function(error) {
  1315. self._abort('socket-error', error);
  1316. });
  1317. this.socket.on('disconnected', function() {
  1318. // If we haven't explicitly disconnected, emit error and disconnect.
  1319. if (!self.disconnected) {
  1320. self.emitError('network', 'Lost connection to server.')
  1321. self.disconnect();
  1322. }
  1323. });
  1324. this.socket.on('close', function() {
  1325. // If we haven't explicitly disconnected, emit error.
  1326. if (!self.disconnected) {
  1327. self._abort('socket-closed', 'Underlying socket is already closed.');
  1328. }
  1329. });
  1330. };
  1331. /** Get a unique ID from the server via XHR. */
  1332. Peer.prototype._retrieveId = function(cb) {
  1333. var self = this;
  1334. var http = new XMLHttpRequest();
  1335. var protocol = this.options.secure ? 'https://' : 'http://';
  1336. var url = protocol + this.options.host + ':' + this.options.port
  1337. + this.options.path + this.options.key + '/id';
  1338. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  1339. url += queryString;
  1340. // If there's no ID we need to wait for one before trying to init socket.
  1341. http.open('get', url, true);
  1342. http.onerror = function(e) {
  1343. util.error('Error retrieving ID', e);
  1344. var pathError = '';
  1345. if (self.options.path === '/' && self.options.host !== util.CLOUD_HOST) {
  1346. pathError = ' If you passed in a `path` to your self-hosted PeerServer, '
  1347. + 'you\'ll also need to pass in that same path when creating a new'
  1348. + ' Peer.';
  1349. }
  1350. self._abort('server-error', 'Could not get an ID from the server.' + pathError);
  1351. }
  1352. http.onreadystatechange = function() {
  1353. if (http.readyState !== 4) {
  1354. return;
  1355. }
  1356. if (http.status !== 200) {
  1357. http.onerror();
  1358. return;
  1359. }
  1360. self._initialize(http.responseText);
  1361. };
  1362. http.send(null);
  1363. };
  1364. /** Initialize a connection with the server. */
  1365. Peer.prototype._initialize = function(id) {
  1366. this.id = id;
  1367. this.socket.start(this.id, this.options.token);
  1368. }
  1369. /** Handles messages from the server. */
  1370. Peer.prototype._handleMessage = function(message) {
  1371. var type = message.type;
  1372. var payload = message.payload;
  1373. var peer = message.src;
  1374. switch (type) {
  1375. case 'OPEN': // The connection to the server is open.
  1376. this.emit('open', this.id);
  1377. this.open = true;
  1378. break;
  1379. case 'ERROR': // Server error.
  1380. this._abort('server-error', payload.msg);
  1381. break;
  1382. case 'ID-TAKEN': // The selected ID is taken.
  1383. this._abort('unavailable-id', 'ID `' + this.id + '` is taken');
  1384. break;
  1385. case 'INVALID-KEY': // The given API key cannot be found.
  1386. this._abort('invalid-key', 'API KEY "' + this.options.key + '" is invalid');
  1387. break;
  1388. //
  1389. case 'LEAVE': // Another peer has closed its connection to this peer.
  1390. util.log('Received leave message from', peer);
  1391. this._cleanupPeer(peer);
  1392. break;
  1393. case 'EXPIRE': // The offer sent to a peer has expired without response.
  1394. this.emitError('peer-unavailable', 'Could not connect to peer ' + peer);
  1395. break;
  1396. case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  1397. var connectionId = payload.connectionId;
  1398. var connection = this.getConnection(peer, connectionId);
  1399. if (connection) {
  1400. util.warn('Offer received for existing Connection ID:', connectionId);
  1401. //connection.handleMessage(message);
  1402. } else {
  1403. // Create a new connection.
  1404. if (payload.type === 'media') {
  1405. var connection = new MediaConnection(peer, this, {
  1406. connectionId: connectionId,
  1407. _payload: payload,
  1408. metadata: payload.metadata
  1409. });
  1410. this._addConnection(peer, connection);
  1411. this.emit('call', connection);
  1412. } else if (payload.type === 'data') {
  1413. connection = new DataConnection(peer, this, {
  1414. connectionId: connectionId,
  1415. _payload: payload,
  1416. metadata: payload.metadata,
  1417. label: payload.label,
  1418. serialization: payload.serialization,
  1419. reliable: payload.reliable
  1420. });
  1421. this._addConnection(peer, connection);
  1422. this.emit('connection', connection);
  1423. } else {
  1424. util.warn('Received malformed connection type:', payload.type);
  1425. return;
  1426. }
  1427. // Find messages.
  1428. var messages = this._getMessages(connectionId);
  1429. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  1430. connection.handleMessage(messages[i]);
  1431. }
  1432. }
  1433. break;
  1434. default:
  1435. if (!payload) {
  1436. util.warn('You received a malformed message from ' + peer + ' of type ' + type);
  1437. return;
  1438. }
  1439. var id = payload.connectionId;
  1440. var connection = this.getConnection(peer, id);
  1441. if (connection && connection.pc) {
  1442. // Pass it on.
  1443. connection.handleMessage(message);
  1444. } else if (id) {
  1445. // Store for possible later use
  1446. this._storeMessage(id, message);
  1447. } else {
  1448. util.warn('You received an unrecognized message:', message);
  1449. }
  1450. break;
  1451. }
  1452. }
  1453. /** Stores messages without a set up connection, to be claimed later. */
  1454. Peer.prototype._storeMessage = function(connectionId, message) {
  1455. if (!this._lostMessages[connectionId]) {
  1456. this._lostMessages[connectionId] = [];
  1457. }
  1458. this._lostMessages[connectionId].push(message);
  1459. }
  1460. /** Retrieve messages from lost message store */
  1461. Peer.prototype._getMessages = function(connectionId) {
  1462. var messages = this._lostMessages[connectionId];
  1463. if (messages) {
  1464. delete this._lostMessages[connectionId];
  1465. return messages;
  1466. } else {
  1467. return [];
  1468. }
  1469. }
  1470. /**
  1471. * Returns a DataConnection to the specified peer. See documentation for a
  1472. * complete list of options.
  1473. */
  1474. Peer.prototype.connect = function(peer, options) {
  1475. if (this.disconnected) {
  1476. util.warn('You cannot connect to a new Peer because you called '
  1477. + '.disconnect() on this Peer and ended your connection with the'
  1478. + ' server. You can create a new Peer to reconnect, or call reconnect'
  1479. + ' on this peer if you believe its ID to still be available.');
  1480. this.emitError('disconnected', 'Cannot connect to new Peer after disconnecting from server.');
  1481. return;
  1482. }
  1483. var connection = new DataConnection(peer, this, options);
  1484. this._addConnection(peer, connection);
  1485. return connection;
  1486. }
  1487. /**
  1488. * Returns a MediaConnection to the specified peer. See documentation for a
  1489. * complete list of options.
  1490. */
  1491. Peer.prototype.call = function(peer, stream, options) {
  1492. if (this.disconnected) {
  1493. util.warn('You cannot connect to a new Peer because you called '
  1494. + '.disconnect() on this Peer and ended your connection with the'
  1495. + ' server. You can create a new Peer to reconnect.');
  1496. this.emitError('disconnected', 'Cannot connect to new Peer after disconnecting from server.');
  1497. return;
  1498. }
  1499. if (!stream) {
  1500. util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.');
  1501. return;
  1502. }
  1503. options = options || {};
  1504. options._stream = stream;
  1505. var call = new MediaConnection(peer, this, options);
  1506. this._addConnection(peer, call);
  1507. return call;
  1508. }
  1509. /** Add a data/media connection to this peer. */
  1510. Peer.prototype._addConnection = function(peer, connection) {
  1511. if (!this.connections[peer]) {
  1512. this.connections[peer] = [];
  1513. }
  1514. this.connections[peer].push(connection);
  1515. }
  1516. /** Retrieve a data/media connection for this peer. */
  1517. Peer.prototype.getConnection = function(peer, id) {
  1518. var connections = this.connections[peer];
  1519. if (!connections) {
  1520. return null;
  1521. }
  1522. for (var i = 0, ii = connections.length; i < ii; i++) {
  1523. if (connections[i].id === id) {
  1524. return connections[i];
  1525. }
  1526. }
  1527. return null;
  1528. }
  1529. Peer.prototype._delayedAbort = function(type, message) {
  1530. var self = this;
  1531. util.setZeroTimeout(function(){
  1532. self._abort(type, message);
  1533. });
  1534. }
  1535. /**
  1536. * Destroys the Peer and emits an error message.
  1537. * The Peer is not destroyed if it's in a disconnected state, in which case
  1538. * it retains its disconnected state and its existing connections.
  1539. */
  1540. Peer.prototype._abort = function(type, message) {
  1541. util.error('Aborting!');
  1542. if (!this._lastServerId) {
  1543. this.destroy();
  1544. } else {
  1545. this.disconnect();
  1546. }
  1547. this.emitError(type, message);
  1548. };
  1549. /** Emits a typed error message. */
  1550. Peer.prototype.emitError = function(type, err) {
  1551. util.error('Error:', err);
  1552. if (typeof err === 'string') {
  1553. err = new Error(err);
  1554. }
  1555. err.type = type;
  1556. this.emit('error', err);
  1557. };
  1558. /**
  1559. * Destroys the Peer: closes all active connections as well as the connection
  1560. * to the server.
  1561. * Warning: The peer can no longer create or accept connections after being
  1562. * destroyed.
  1563. */
  1564. Peer.prototype.destroy = function() {
  1565. if (!this.destroyed) {
  1566. this._cleanup();
  1567. this.disconnect();
  1568. this.destroyed = true;
  1569. }
  1570. }
  1571. /** Disconnects every connection on this peer. */
  1572. Peer.prototype._cleanup = function() {
  1573. if (this.connections) {
  1574. var peers = Object.keys(this.connections);
  1575. for (var i = 0, ii = peers.length; i < ii; i++) {
  1576. this._cleanupPeer(peers[i]);
  1577. }
  1578. }
  1579. this.emit('close');
  1580. }
  1581. /** Closes all connections to this peer. */
  1582. Peer.prototype._cleanupPeer = function(peer) {
  1583. var connections = this.connections[peer];
  1584. for (var j = 0, jj = connections.length; j < jj; j += 1) {
  1585. connections[j].close();
  1586. }
  1587. }
  1588. /**
  1589. * Disconnects the Peer's connection to the PeerServer. Does not close any
  1590. * active connections.
  1591. * Warning: The peer can no longer create or accept connections after being
  1592. * disconnected. It also cannot reconnect to the server.
  1593. */
  1594. Peer.prototype.disconnect = function() {
  1595. var self = this;
  1596. util.setZeroTimeout(function(){
  1597. if (!self.disconnected) {
  1598. self.disconnected = true;
  1599. self.open = false;
  1600. if (self.socket) {
  1601. self.socket.close();
  1602. }
  1603. self.emit('disconnected', self.id);
  1604. self._lastServerId = self.id;
  1605. self.id = null;
  1606. }
  1607. });
  1608. }
  1609. /** Attempts to reconnect with the same ID. */
  1610. Peer.prototype.reconnect = function() {
  1611. if (this.disconnected && !this.destroyed) {
  1612. util.log('Attempting reconnection to server with ID ' + this._lastServerId);
  1613. this.disconnected = false;
  1614. this._initializeServerConnection();
  1615. this._initialize(this._lastServerId);
  1616. } else if (this.destroyed) {
  1617. throw new Error('This peer cannot reconnect to the server. It has already been destroyed.');
  1618. } else if (!this.disconnected && !this.open) {
  1619. // Do nothing. We're still connecting the first time.
  1620. util.error('In a hurry? We\'re still trying t