peer.js 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  1. /*! peerjs.js build:0.1.0, 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. var buffer = packer.pack(data);
  63. return buffer;
  64. }
  65. };
  66. function Unpacker (data){
  67. // Data is ArrayBuffer
  68. this.index = 0;
  69. this.dataBuffer = data;
  70. this.dataView = new Uint8Array(this.dataBuffer);
  71. this.length = this.dataBuffer.byteLength;
  72. }
  73. Unpacker.prototype.unpack = function(){
  74. var type = this.unpack_uint8();
  75. if (type < 0x80){
  76. var positive_fixnum = type;
  77. return positive_fixnum;
  78. } else if ((type ^ 0xe0) < 0x20){
  79. var negative_fixnum = (type ^ 0xe0) - 0x20;
  80. return negative_fixnum;
  81. }
  82. var size;
  83. if ((size = type ^ 0xa0) <= 0x0f){
  84. return this.unpack_raw(size);
  85. } else if ((size = type ^ 0xb0) <= 0x0f){
  86. return this.unpack_string(size);
  87. } else if ((size = type ^ 0x90) <= 0x0f){
  88. return this.unpack_array(size);
  89. } else if ((size = type ^ 0x80) <= 0x0f){
  90. return this.unpack_map(size);
  91. }
  92. switch(type){
  93. case 0xc0:
  94. return null;
  95. case 0xc1:
  96. return undefined;
  97. case 0xc2:
  98. return false;
  99. case 0xc3:
  100. return true;
  101. case 0xca:
  102. return this.unpack_float();
  103. case 0xcb:
  104. return this.unpack_double();
  105. case 0xcc:
  106. return this.unpack_uint8();
  107. case 0xcd:
  108. return this.unpack_uint16();
  109. case 0xce:
  110. return this.unpack_uint32();
  111. case 0xcf:
  112. return this.unpack_uint64();
  113. case 0xd0:
  114. return this.unpack_int8();
  115. case 0xd1:
  116. return this.unpack_int16();
  117. case 0xd2:
  118. return this.unpack_int32();
  119. case 0xd3:
  120. return this.unpack_int64();
  121. case 0xd4:
  122. return undefined;
  123. case 0xd5:
  124. return undefined;
  125. case 0xd6:
  126. return undefined;
  127. case 0xd7:
  128. return undefined;
  129. case 0xd8:
  130. size = this.unpack_uint16();
  131. return this.unpack_string(size);
  132. case 0xd9:
  133. size = this.unpack_uint32();
  134. return this.unpack_string(size);
  135. case 0xda:
  136. size = this.unpack_uint16();
  137. return this.unpack_raw(size);
  138. case 0xdb:
  139. size = this.unpack_uint32();
  140. return this.unpack_raw(size);
  141. case 0xdc:
  142. size = this.unpack_uint16();
  143. return this.unpack_array(size);
  144. case 0xdd:
  145. size = this.unpack_uint32();
  146. return this.unpack_array(size);
  147. case 0xde:
  148. size = this.unpack_uint16();
  149. return this.unpack_map(size);
  150. case 0xdf:
  151. size = this.unpack_uint32();
  152. return this.unpack_map(size);
  153. }
  154. }
  155. Unpacker.prototype.unpack_uint8 = function(){
  156. var byte = this.dataView[this.index] & 0xff;
  157. this.index++;
  158. return byte;
  159. };
  160. Unpacker.prototype.unpack_uint16 = function(){
  161. var bytes = this.read(2);
  162. var uint16 =
  163. ((bytes[0] & 0xff) * 256) + (bytes[1] & 0xff);
  164. this.index += 2;
  165. return uint16;
  166. }
  167. Unpacker.prototype.unpack_uint32 = function(){
  168. var bytes = this.read(4);
  169. var uint32 =
  170. ((bytes[0] * 256 +
  171. bytes[1]) * 256 +
  172. bytes[2]) * 256 +
  173. bytes[3];
  174. this.index += 4;
  175. return uint32;
  176. }
  177. Unpacker.prototype.unpack_uint64 = function(){
  178. var bytes = this.read(8);
  179. var uint64 =
  180. ((((((bytes[0] * 256 +
  181. bytes[1]) * 256 +
  182. bytes[2]) * 256 +
  183. bytes[3]) * 256 +
  184. bytes[4]) * 256 +
  185. bytes[5]) * 256 +
  186. bytes[6]) * 256 +
  187. bytes[7];
  188. this.index += 8;
  189. return uint64;
  190. }
  191. Unpacker.prototype.unpack_int8 = function(){
  192. var uint8 = this.unpack_uint8();
  193. return (uint8 < 0x80 ) ? uint8 : uint8 - (1 << 8);
  194. };
  195. Unpacker.prototype.unpack_int16 = function(){
  196. var uint16 = this.unpack_uint16();
  197. return (uint16 < 0x8000 ) ? uint16 : uint16 - (1 << 16);
  198. }
  199. Unpacker.prototype.unpack_int32 = function(){
  200. var uint32 = this.unpack_uint32();
  201. return (uint32 < Math.pow(2, 31) ) ? uint32 :
  202. uint32 - Math.pow(2, 32);
  203. }
  204. Unpacker.prototype.unpack_int64 = function(){
  205. var uint64 = this.unpack_uint64();
  206. return (uint64 < Math.pow(2, 63) ) ? uint64 :
  207. uint64 - Math.pow(2, 64);
  208. }
  209. Unpacker.prototype.unpack_raw = function(size){
  210. if ( this.length < this.index + size){
  211. throw new Error('BinaryPackFailure: index is out of range'
  212. + ' ' + this.index + ' ' + size + ' ' + this.length);
  213. }
  214. var buf = this.dataBuffer.slice(this.index, this.index + size);
  215. this.index += size;
  216. //buf = util.bufferToString(buf);
  217. return buf;
  218. }
  219. Unpacker.prototype.unpack_string = function(size){
  220. var bytes = this.read(size);
  221. var i = 0, str = '', c, code;
  222. while(i < size){
  223. c = bytes[i];
  224. if ( c < 128){
  225. str += String.fromCharCode(c);
  226. i++;
  227. } else if ((c ^ 0xc0) < 32){
  228. code = ((c ^ 0xc0) << 6) | (bytes[i+1] & 63);
  229. str += String.fromCharCode(code);
  230. i += 2;
  231. } else {
  232. code = ((c & 15) << 12) | ((bytes[i+1] & 63) << 6) |
  233. (bytes[i+2] & 63);
  234. str += String.fromCharCode(code);
  235. i += 3;
  236. }
  237. }
  238. this.index += size;
  239. return str;
  240. }
  241. Unpacker.prototype.unpack_array = function(size){
  242. var objects = new Array(size);
  243. for(var i = 0; i < size ; i++){
  244. objects[i] = this.unpack();
  245. }
  246. return objects;
  247. }
  248. Unpacker.prototype.unpack_map = function(size){
  249. var map = {};
  250. for(var i = 0; i < size ; i++){
  251. var key = this.unpack();
  252. var value = this.unpack();
  253. map[key] = value;
  254. }
  255. return map;
  256. }
  257. Unpacker.prototype.unpack_float = function(){
  258. var uint32 = this.unpack_uint32();
  259. var sign = uint32 >> 31;
  260. var exp = ((uint32 >> 23) & 0xff) - 127;
  261. var fraction = ( uint32 & 0x7fffff ) | 0x800000;
  262. return (sign == 0 ? 1 : -1) *
  263. fraction * Math.pow(2, exp - 23);
  264. }
  265. Unpacker.prototype.unpack_double = function(){
  266. var h32 = this.unpack_uint32();
  267. var l32 = this.unpack_uint32();
  268. var sign = h32 >> 31;
  269. var exp = ((h32 >> 20) & 0x7ff) - 1023;
  270. var hfrac = ( h32 & 0xfffff ) | 0x100000;
  271. var frac = hfrac * Math.pow(2, exp - 20) +
  272. l32 * Math.pow(2, exp - 52);
  273. return (sign == 0 ? 1 : -1) * frac;
  274. }
  275. Unpacker.prototype.read = function(length){
  276. var j = this.index;
  277. if (j + length <= this.length) {
  278. return this.dataView.subarray(j, j + length);
  279. } else {
  280. throw new Error('BinaryPackFailure: read index out of range');
  281. }
  282. }
  283. function Packer (){
  284. this.bufferBuilder = new BufferBuilder();
  285. }
  286. Packer.prototype.pack = function(value){
  287. var type = typeof(value);
  288. if (type == 'string'){
  289. this.pack_string(value);
  290. } else if (type == 'number'){
  291. if (Math.floor(value) === value){
  292. this.pack_integer(value);
  293. } else{
  294. this.pack_double(value);
  295. }
  296. } else if (type == 'boolean'){
  297. if (value === true){
  298. this.bufferBuilder.append(0xc3);
  299. } else if (value === false){
  300. this.bufferBuilder.append(0xc2);
  301. }
  302. } else if (type == 'undefined'){
  303. this.bufferBuilder.append(0xc0);
  304. } else if (type == 'object'){
  305. if (value === null){
  306. this.bufferBuilder.append(0xc0);
  307. } else {
  308. var constructor = value.constructor;
  309. if (constructor == Array){
  310. this.pack_array(value);
  311. } else if (constructor == Blob || constructor == File) {
  312. this.pack_bin(value);
  313. } else if (constructor == ArrayBuffer) {
  314. if(binaryFeatures.useArrayBufferView) {
  315. this.pack_bin(new Uint8Array(value));
  316. } else {
  317. this.pack_bin(value);
  318. }
  319. } else if ('BYTES_PER_ELEMENT' in value){
  320. if(binaryFeatures.useArrayBufferView) {
  321. this.pack_bin(value);
  322. } else {
  323. this.pack_bin(value.buffer);
  324. }
  325. } else if (constructor == Object){
  326. this.pack_object(value);
  327. } else if (constructor == Date){
  328. this.pack_string(value.toString());
  329. } else if (typeof value.toBinaryPack == 'function'){
  330. this.bufferBuilder.append(value.toBinaryPack());
  331. } else {
  332. throw new Error('Type "' + constructor.toString() + '" not yet supported');
  333. }
  334. }
  335. } else {
  336. throw new Error('Type "' + type + '" not yet supported');
  337. }
  338. return this.bufferBuilder.getBuffer();
  339. }
  340. Packer.prototype.pack_bin = function(blob){
  341. var length = blob.length || blob.byteLength || blob.size;
  342. if (length <= 0x0f){
  343. this.pack_uint8(0xa0 + length);
  344. } else if (length <= 0xffff){
  345. this.bufferBuilder.append(0xda) ;
  346. this.pack_uint16(length);
  347. } else if (length <= 0xffffffff){
  348. this.bufferBuilder.append(0xdb);
  349. this.pack_uint32(length);
  350. } else{
  351. throw new Error('Invalid length');
  352. return;
  353. }
  354. this.bufferBuilder.append(blob);
  355. }
  356. Packer.prototype.pack_string = function(str){
  357. var length = str.length;
  358. if (length <= 0x0f){
  359. this.pack_uint8(0xb0 + length);
  360. } else if (length <= 0xffff){
  361. this.bufferBuilder.append(0xd8) ;
  362. this.pack_uint16(length);
  363. } else if (length <= 0xffffffff){
  364. this.bufferBuilder.append(0xd9);
  365. this.pack_uint32(length);
  366. } else{
  367. throw new Error('Invalid length');
  368. return;
  369. }
  370. this.bufferBuilder.append(str);
  371. }
  372. Packer.prototype.pack_array = function(ary){
  373. var length = ary.length;
  374. if (length <= 0x0f){
  375. this.pack_uint8(0x90 + length);
  376. } else if (length <= 0xffff){
  377. this.bufferBuilder.append(0xdc)
  378. this.pack_uint16(length);
  379. } else if (length <= 0xffffffff){
  380. this.bufferBuilder.append(0xdd);
  381. this.pack_uint32(length);
  382. } else{
  383. throw new Error('Invalid length');
  384. }
  385. for(var i = 0; i < length ; i++){
  386. this.pack(ary[i]);
  387. }
  388. }
  389. Packer.prototype.pack_integer = function(num){
  390. if ( -0x20 <= num && num <= 0x7f){
  391. this.bufferBuilder.append(num & 0xff);
  392. } else if (0x00 <= num && num <= 0xff){
  393. this.bufferBuilder.append(0xcc);
  394. this.pack_uint8(num);
  395. } else if (-0x80 <= num && num <= 0x7f){
  396. this.bufferBuilder.append(0xd0);
  397. this.pack_int8(num);
  398. } else if ( 0x0000 <= num && num <= 0xffff){
  399. this.bufferBuilder.append(0xcd);
  400. this.pack_uint16(num);
  401. } else if (-0x8000 <= num && num <= 0x7fff){
  402. this.bufferBuilder.append(0xd1);
  403. this.pack_int16(num);
  404. } else if ( 0x00000000 <= num && num <= 0xffffffff){
  405. this.bufferBuilder.append(0xce);
  406. this.pack_uint32(num);
  407. } else if (-0x80000000 <= num && num <= 0x7fffffff){
  408. this.bufferBuilder.append(0xd2);
  409. this.pack_int32(num);
  410. } else if (-0x8000000000000000 <= num && num <= 0x7FFFFFFFFFFFFFFF){
  411. this.bufferBuilder.append(0xd3);
  412. this.pack_int64(num);
  413. } else if (0x0000000000000000 <= num && num <= 0xFFFFFFFFFFFFFFFF){
  414. this.bufferBuilder.append(0xcf);
  415. this.pack_uint64(num);
  416. } else{
  417. throw new Error('Invalid integer');
  418. }
  419. }
  420. Packer.prototype.pack_double = function(num){
  421. var sign = 0;
  422. if (num < 0){
  423. sign = 1;
  424. num = -num;
  425. }
  426. var exp = Math.floor(Math.log(num) / Math.LN2);
  427. var frac0 = num / Math.pow(2, exp) - 1;
  428. var frac1 = Math.floor(frac0 * Math.pow(2, 52));
  429. var b32 = Math.pow(2, 32);
  430. var h32 = (sign << 31) | ((exp+1023) << 20) |
  431. (frac1 / b32) & 0x0fffff;
  432. var l32 = frac1 % b32;
  433. this.bufferBuilder.append(0xcb);
  434. this.pack_int32(h32);
  435. this.pack_int32(l32);
  436. }
  437. Packer.prototype.pack_object = function(obj){
  438. var keys = Object.keys(obj);
  439. var length = keys.length;
  440. if (length <= 0x0f){
  441. this.pack_uint8(0x80 + length);
  442. } else if (length <= 0xffff){
  443. this.bufferBuilder.append(0xde);
  444. this.pack_uint16(length);
  445. } else if (length <= 0xffffffff){
  446. this.bufferBuilder.append(0xdf);
  447. this.pack_uint32(length);
  448. } else{
  449. throw new Error('Invalid length');
  450. }
  451. for(var prop in obj){
  452. if (obj.hasOwnProperty(prop)){
  453. this.pack(prop);
  454. this.pack(obj[prop]);
  455. }
  456. }
  457. }
  458. Packer.prototype.pack_uint8 = function(num){
  459. this.bufferBuilder.append(num);
  460. }
  461. Packer.prototype.pack_uint16 = function(num){
  462. this.bufferBuilder.append(num >> 8);
  463. this.bufferBuilder.append(num & 0xff);
  464. }
  465. Packer.prototype.pack_uint32 = function(num){
  466. var n = num & 0xffffffff;
  467. this.bufferBuilder.append((n & 0xff000000) >>> 24);
  468. this.bufferBuilder.append((n & 0x00ff0000) >>> 16);
  469. this.bufferBuilder.append((n & 0x0000ff00) >>> 8);
  470. this.bufferBuilder.append((n & 0x000000ff));
  471. }
  472. Packer.prototype.pack_uint64 = function(num){
  473. var high = num / Math.pow(2, 32);
  474. var low = num % Math.pow(2, 32);
  475. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  476. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  477. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  478. this.bufferBuilder.append((high & 0x000000ff));
  479. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  480. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  481. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  482. this.bufferBuilder.append((low & 0x000000ff));
  483. }
  484. Packer.prototype.pack_int8 = function(num){
  485. this.bufferBuilder.append(num & 0xff);
  486. }
  487. Packer.prototype.pack_int16 = function(num){
  488. this.bufferBuilder.append((num & 0xff00) >> 8);
  489. this.bufferBuilder.append(num & 0xff);
  490. }
  491. Packer.prototype.pack_int32 = function(num){
  492. this.bufferBuilder.append((num >>> 24) & 0xff);
  493. this.bufferBuilder.append((num & 0x00ff0000) >>> 16);
  494. this.bufferBuilder.append((num & 0x0000ff00) >>> 8);
  495. this.bufferBuilder.append((num & 0x000000ff));
  496. }
  497. Packer.prototype.pack_int64 = function(num){
  498. var high = Math.floor(num / Math.pow(2, 32));
  499. var low = num % Math.pow(2, 32);
  500. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  501. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  502. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  503. this.bufferBuilder.append((high & 0x000000ff));
  504. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  505. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  506. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  507. this.bufferBuilder.append((low & 0x000000ff));
  508. }
  509. /**
  510. * Light EventEmitter. Ported from Node.js/events.js
  511. * Eric Zhang
  512. */
  513. /**
  514. * EventEmitter class
  515. * Creates an object with event registering and firing methods
  516. */
  517. function EventEmitter() {
  518. // Initialise required storage variables
  519. this._events = {};
  520. }
  521. var isArray = Array.isArray;
  522. EventEmitter.prototype.addListener = function(type, listener, scope, once) {
  523. if ('function' !== typeof listener) {
  524. throw new Error('addListener only takes instances of Function');
  525. }
  526. // To avoid recursion in the case that type == "newListeners"! Before
  527. // adding it to the listeners, first emit "newListeners".
  528. this.emit('newListener', type, typeof listener.listener === 'function' ?
  529. listener.listener : listener);
  530. if (!this._events[type]) {
  531. // Optimize the case of one listener. Don't need the extra array object.
  532. this._events[type] = listener;
  533. } else if (isArray(this._events[type])) {
  534. // If we've already got an array, just append.
  535. this._events[type].push(listener);
  536. } else {
  537. // Adding the second element, need to change to array.
  538. this._events[type] = [this._events[type], listener];
  539. }
  540. return this;
  541. };
  542. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  543. EventEmitter.prototype.once = function(type, listener, scope) {
  544. if ('function' !== typeof listener) {
  545. throw new Error('.once only takes instances of Function');
  546. }
  547. var self = this;
  548. function g() {
  549. self.removeListener(type, g);
  550. listener.apply(this, arguments);
  551. };
  552. g.listener = listener;
  553. self.on(type, g);
  554. return this;
  555. };
  556. EventEmitter.prototype.removeListener = function(type, listener, scope) {
  557. if ('function' !== typeof listener) {
  558. throw new Error('removeListener only takes instances of Function');
  559. }
  560. // does not use listeners(), so no side effect of creating _events[type]
  561. if (!this._events[type]) return this;
  562. var list = this._events[type];
  563. if (isArray(list)) {
  564. var position = -1;
  565. for (var i = 0, length = list.length; i < length; i++) {
  566. if (list[i] === listener ||
  567. (list[i].listener && list[i].listener === listener))
  568. {
  569. position = i;
  570. break;
  571. }
  572. }
  573. if (position < 0) return this;
  574. list.splice(position, 1);
  575. if (list.length == 0)
  576. delete this._events[type];
  577. } else if (list === listener ||
  578. (list.listener && list.listener === listener))
  579. {
  580. delete this._events[type];
  581. }
  582. return this;
  583. };
  584. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  585. EventEmitter.prototype.removeAllListeners = function(type) {
  586. if (arguments.length === 0) {
  587. this._events = {};
  588. return this;
  589. }
  590. // does not use listeners(), so no side effect of creating _events[type]
  591. if (type && this._events && this._events[type]) this._events[type] = null;
  592. return this;
  593. };
  594. EventEmitter.prototype.listeners = function(type) {
  595. if (!this._events[type]) this._events[type] = [];
  596. if (!isArray(this._events[type])) {
  597. this._events[type] = [this._events[type]];
  598. }
  599. return this._events[type];
  600. };
  601. EventEmitter.prototype.emit = function(type) {
  602. var type = arguments[0];
  603. var handler = this._events[type];
  604. if (!handler) return false;
  605. if (typeof handler == 'function') {
  606. switch (arguments.length) {
  607. // fast cases
  608. case 1:
  609. handler.call(this);
  610. break;
  611. case 2:
  612. handler.call(this, arguments[1]);
  613. break;
  614. case 3:
  615. handler.call(this, arguments[1], arguments[2]);
  616. break;
  617. // slower
  618. default:
  619. var l = arguments.length;
  620. var args = new Array(l - 1);
  621. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  622. handler.apply(this, args);
  623. }
  624. return true;
  625. } else if (isArray(handler)) {
  626. var l = arguments.length;
  627. var args = new Array(l - 1);
  628. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  629. var listeners = handler.slice();
  630. for (var i = 0, l = listeners.length; i < l; i++) {
  631. listeners[i].apply(this, args);
  632. }
  633. return true;
  634. } else {
  635. return false;
  636. }
  637. };
  638. var util = {
  639. debug: false,
  640. browserisms: '',
  641. inherits: function(ctor, superCtor) {
  642. ctor.super_ = superCtor;
  643. ctor.prototype = Object.create(superCtor.prototype, {
  644. constructor: {
  645. value: ctor,
  646. enumerable: false,
  647. writable: true,
  648. configurable: true
  649. }
  650. });
  651. },
  652. extend: function(dest, source) {
  653. for(var key in source) {
  654. if(source.hasOwnProperty(key)) {
  655. dest[key] = source[key];
  656. }
  657. }
  658. return dest;
  659. },
  660. pack: BinaryPack.pack,
  661. unpack: BinaryPack.unpack,
  662. randomPort: function() {
  663. return Math.round(Math.random() * 60535) + 5000;
  664. },
  665. log: function () {
  666. if (util.debug) {
  667. var copy = [];
  668. for (var i = 0; i < arguments.length; i++) {
  669. copy[i] = arguments[i];
  670. }
  671. copy.unshift('PeerJS: ');
  672. console.log.apply(console, copy);
  673. }
  674. },
  675. setZeroTimeout: (function(global) {
  676. var timeouts = [];
  677. var messageName = 'zero-timeout-message';
  678. // Like setTimeout, but only takes a function argument. There's
  679. // no time argument (always zero) and no arguments (you have to
  680. // use a closure).
  681. function setZeroTimeoutPostMessage(fn) {
  682. timeouts.push(fn);
  683. global.postMessage(messageName, '*');
  684. }
  685. function handleMessage(event) {
  686. if (event.source == global && event.data == messageName) {
  687. if (event.stopPropagation) {
  688. event.stopPropagation();
  689. }
  690. if (timeouts.length) {
  691. timeouts.shift()();
  692. }
  693. }
  694. }
  695. if (global.addEventListener) {
  696. global.addEventListener('message', handleMessage, true);
  697. } else if (global.attachEvent) {
  698. global.attachEvent('onmessage', handleMessage);
  699. }
  700. return setZeroTimeoutPostMessage;
  701. }(this)),
  702. blobToArrayBuffer: function(blob, cb){
  703. var fr = new FileReader();
  704. fr.onload = function(evt) {
  705. cb(evt.target.result);
  706. };
  707. fr.readAsArrayBuffer(blob);
  708. },
  709. blobToBinaryString: function(blob, cb){
  710. var fr = new FileReader();
  711. fr.onload = function(evt) {
  712. cb(evt.target.result);
  713. };
  714. fr.readAsBinaryString(blob);
  715. },
  716. binaryStringToArrayBuffer: function(binary) {
  717. var byteArray = new Uint8Array(binary.length);
  718. for (var i = 0; i < binary.length; i++) {
  719. byteArray[i] = binary.charCodeAt(i) & 0xff;
  720. }
  721. return byteArray.buffer;
  722. },
  723. randomToken: function () {
  724. return Math.random().toString(36).substr(2);
  725. }
  726. };
  727. var RTCPeerConnection = null;
  728. var getUserMedia = null;
  729. var attachMediaStream = null;
  730. if (navigator.mozGetUserMedia) {
  731. util.browserisms = 'Firefox'
  732. RTCPeerConnection = mozRTCPeerConnection;
  733. getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  734. } else if (navigator.webkitGetUserMedia) {
  735. util.browserisms = 'Webkit'
  736. RTCPeerConnection = webkitRTCPeerConnection;
  737. getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  738. }
  739. exports.RTCPeerConnection = RTCPeerConnection;
  740. exports.getUserMedia = getUserMedia;
  741. /**
  742. * A peer who can initiate connections with other peers.
  743. */
  744. function Peer(id, options) {
  745. if (id.constructor == Object) {
  746. options = id;
  747. id = undefined;
  748. }
  749. if (!(this instanceof Peer)) return new Peer(options);
  750. EventEmitter.call(this);
  751. options = util.extend({
  752. debug: false,
  753. host: '0.peerjs.com',
  754. port: 9000,
  755. key: 'peerjs',
  756. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  757. }, options);
  758. this._options = options;
  759. util.debug = options.debug;
  760. // Ensure alphanumeric_-
  761. if (id && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id)) {
  762. throw new Error('Peer ID can only contain alphanumerics, "_", and "-".');
  763. }
  764. if (options.key && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(options.key)) {
  765. throw new Error('API key can only contain alphanumerics, "_", and "-".');
  766. }
  767. // Connections for this peer.
  768. this.connections = {};
  769. // Queued connections to make.
  770. this._queued = [];
  771. // Init immediately if ID is given, otherwise ask server for ID
  772. if (id) {
  773. this.id = id;
  774. this._init();
  775. } else {
  776. this._getId();
  777. }
  778. };
  779. util.inherits(Peer, EventEmitter);
  780. Peer.prototype._getId = function(cb) {
  781. var self = this;
  782. try {
  783. var http = new XMLHttpRequest();
  784. var url = 'http://' + this._options.host + ':' + this._options.port + '/' + this._options.key + '/id';
  785. // If there's no ID we need to wait for one before trying to init socket.
  786. http.open('get', url, true);
  787. http.onreadystatechange = function() {
  788. if (http.readyState === 4) {
  789. self.id = http.responseText;
  790. self._init();
  791. }
  792. };
  793. http.send(null);
  794. } catch(e) {
  795. this.emit('error', 'Could not get an ID from the server');
  796. }
  797. };
  798. Peer.prototype._init = function() {
  799. var self = this;
  800. this._socket = new Socket(this._options.host, this._options.port, this._options.key, this.id);
  801. this._socket.on('message', function(data) {
  802. self._handleServerJSONMessage(data);
  803. });
  804. this._socket.on('error', function(error) {
  805. util.log(error);
  806. self.emit('error', error);
  807. self.destroy();
  808. });
  809. this._socket.on('close', function() {
  810. var msg = 'Underlying socket has closed';
  811. util.log('error', msg);
  812. self.emit('error', msg);
  813. self.destroy();
  814. });
  815. this._socket.start();
  816. }
  817. Peer.prototype._handleServerJSONMessage = function(message) {
  818. var peer = message.src;
  819. var connection = this.connections[peer];
  820. payload = message.payload;
  821. switch (message.type) {
  822. case 'OPEN':
  823. this._processQueue();
  824. this.emit('open', this.id);
  825. break;
  826. case 'ERROR':
  827. this.emit('error', payload.msg);
  828. util.log(payload.msg);
  829. break;
  830. case 'ID-TAKEN':
  831. this.emit('error', 'ID `'+this.id+'` is taken');
  832. this.destroy();
  833. break;
  834. case 'OFFER':
  835. var options = {
  836. metadata: payload.metadata,
  837. serialization: payload.serialization,
  838. sdp: payload.sdp,
  839. config: this._options.config
  840. };
  841. var connection = new DataConnection(this.id, peer, this._socket, options);
  842. this._attachConnectionListeners(connection);
  843. this.connections[peer] = connection;
  844. this.emit('connection', connection, payload.metadata);
  845. break;
  846. case 'EXPIRE':
  847. connection = this.connections[peer];
  848. if (connection) {
  849. connection.close();
  850. connection.emit('error', 'Could not connect to peer ' + connection.peer);
  851. }
  852. break;
  853. case 'ANSWER':
  854. if (connection) {
  855. connection.handleSDP(payload.sdp, message.type);
  856. }
  857. break;
  858. case 'CANDIDATE':
  859. if (connection) {
  860. connection.handleCandidate(payload);
  861. }
  862. break;
  863. case 'LEAVE':
  864. if (connection) {
  865. connection.handleLeave();
  866. }
  867. break;
  868. case 'INVALID-KEY':
  869. this.emit('error', 'API KEY "' + this._key + '" is invalid');
  870. this.destroy();
  871. break;
  872. case 'PORT':
  873. //if (util.browserisms === 'Firefox') {
  874. // connection.handlePort(payload);
  875. // break;
  876. //}
  877. default:
  878. util.log('Unrecognized message type:', message.type);
  879. break;
  880. }
  881. };
  882. /** Process queued calls to connect. */
  883. Peer.prototype._processQueue = function() {
  884. while (this._queued.length > 0) {
  885. var conn = this._queued.pop();
  886. conn.initialize(this.id, this._socket);
  887. }
  888. };
  889. Peer.prototype._cleanup = function() {
  890. var self = this;
  891. var peers = Object.keys(this.connections);
  892. for (var i = 0, ii = peers.length; i < ii; i++) {
  893. this.connections[peers[i]].close();
  894. }
  895. util.setZeroTimeout(function(){
  896. self._socket.close();
  897. });
  898. this.emit('close');
  899. };
  900. /** Listeners for DataConnection events. */
  901. Peer.prototype._attachConnectionListeners = function(connection) {
  902. var self = this;
  903. connection.on('close', function(peer) {
  904. if (self.connections[peer]) {
  905. delete self.connections[peer];
  906. }
  907. });
  908. };
  909. /** Exposed connect function for users. Will try to connect later if user
  910. * is waiting for an ID. */
  911. // TODO: pause XHR streaming when not in use and start again when this is
  912. // called.
  913. Peer.prototype.connect = function(peer, options) {
  914. options = util.extend({
  915. config: this._options.config
  916. }, options);
  917. var connection = new DataConnection(this.id, peer, this._socket, options);
  918. this._attachConnectionListeners(connection);
  919. this.connections[peer] = connection;
  920. if (!this.id) {
  921. this._queued.push(connection);
  922. }
  923. return connection;
  924. };
  925. Peer.prototype.destroy = function() {
  926. this._cleanup();
  927. };
  928. exports.Peer = Peer;
  929. /**
  930. * A DataChannel|PeerConnection between two Peers.
  931. */
  932. function DataConnection(id, peer, socket, options) {
  933. if (!(this instanceof DataConnection)) return new DataConnection(options);
  934. EventEmitter.call(this);
  935. options = util.extend({
  936. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] },
  937. reliable: false,
  938. serialization: 'binary'
  939. }, options);
  940. this._options = options;
  941. // Connection is not open yet.
  942. this.open = false;
  943. this.id = id;
  944. this.peer = peer;
  945. this.metadata = options.metadata;
  946. this.serialization = options.serialization;
  947. this._originator = (options.sdp === undefined);
  948. this._socket = socket;
  949. this._sdp = options.sdp;
  950. if (!!this.id) {
  951. this.initialize();
  952. }
  953. };
  954. util.inherits(DataConnection, EventEmitter);
  955. DataConnection.prototype.initialize = function(id, socket) {
  956. if (!!id) {
  957. this.id = id;
  958. }
  959. if (!!socket) {
  960. this._socket = socket;
  961. }
  962. // Firefoxism: connectDataConnection ports.
  963. /*if (util.browserisms === 'Firefox') {
  964. this._firefoxPortSetup();
  965. }*/
  966. // Set up PeerConnection.
  967. this._startPeerConnection();
  968. // Listen for ICE candidates
  969. this._setupIce();
  970. // Listen for negotiation needed
  971. // ** Chrome only.
  972. if (util.browserisms !== 'Firefox' && !!this.id) {
  973. this._setupOffer();
  974. }
  975. // Listen for or create a data channel
  976. this._setupDataChannel();
  977. var self = this;
  978. if (!!this._sdp) {
  979. this.handleSDP(this._sdp, 'OFFER');
  980. }
  981. // Makes offer if Firefox
  982. /*if (util.browserisms === 'Firefox') {
  983. this._firefoxAdditional();
  984. }*/
  985. // No-op this.
  986. this.initialize = function() {};
  987. };
  988. DataConnection.prototype._setupOffer = function() {
  989. var self = this;
  990. util.log('Listening for `negotiationneeded`');
  991. this._pc.onnegotiationneeded = function() {
  992. util.log('`negotiationneeded` triggered');
  993. self._makeOffer();
  994. };
  995. };
  996. DataConnection.prototype._setupDataChannel = function() {
  997. var self = this;
  998. if (this._originator) {
  999. util.log('Creating data channel');
  1000. this._dc = this._pc.createDataChannel(this.peer, { reliable: this._options.reliable });
  1001. this._configureDataChannel();
  1002. } else {
  1003. util.log('Listening for data channel');
  1004. this._pc.ondatachannel = function(evt) {
  1005. util.log('Received data channel');
  1006. self._dc = evt.channel;
  1007. self._configureDataChannel();
  1008. };
  1009. }
  1010. };
  1011. /** Starts a PeerConnection and sets up handlers. */
  1012. DataConnection.prototype._startPeerConnection = function() {
  1013. util.log('Creating RTCPeerConnection');
  1014. this._pc = new RTCPeerConnection(this._options.config, { optional:[ { RtpDataChannels: true } ]});
  1015. };
  1016. /** Takes care of ice handlers. */
  1017. DataConnection.prototype._setupIce = function() {
  1018. util.log('Listening for ICE candidates');
  1019. var self = this;
  1020. this._pc.onicecandidate = function(evt) {
  1021. if (evt.candidate) {
  1022. util.log('Received ICE candidates');
  1023. self._socket.send({
  1024. type: 'CANDIDATE',
  1025. payload: {
  1026. candidate: evt.candidate
  1027. },
  1028. dst: self.peer
  1029. });
  1030. }
  1031. };
  1032. };
  1033. /*DataConnection.prototype._firefoxPortSetup = function() {
  1034. if (!DataConnection.usedPorts) {
  1035. DataConnection.usedPorts = [];
  1036. }
  1037. this.localPort = util.randomPort();
  1038. while (DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  1039. this.localPort = util.randomPort();
  1040. }
  1041. this.remotePort = util.randomPort();
  1042. while (this.remotePort === this.localPort ||
  1043. DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  1044. this.remotePort = util.randomPort();
  1045. }
  1046. DataConnection.usedPorts.push(this.remotePort);
  1047. DataConnection.usedPorts.push(this.localPort);
  1048. }*/
  1049. DataConnection.prototype._configureDataChannel = function() {
  1050. var self = this;
  1051. if (util.browserisms !== 'Webkit') {
  1052. this._dc.binaryType = 'arraybuffer';
  1053. }
  1054. this._dc.onopen = function() {
  1055. util.log('Data channel connection success');
  1056. self.open = true;
  1057. self.emit('open');
  1058. };
  1059. this._dc.onmessage = function(e) {
  1060. self._handleDataMessage(e);
  1061. };
  1062. this._dc.onclose = function(e) {
  1063. self.emit('close');
  1064. };
  1065. };
  1066. /** Decide whether to handle Firefoxisms. */
  1067. /*DataConnection.prototype._firefoxAdditional = function() {
  1068. var self = this;
  1069. getUserMedia({ audio: true, fake: true }, function(s) {
  1070. self._pc.addStream(s);
  1071. if (self._originator) {
  1072. self._makeOffer();
  1073. }
  1074. }, function(err) { util.log('Could not getUserMedia'); });
  1075. };*/
  1076. DataConnection.prototype._makeOffer = function() {
  1077. var self = this;
  1078. this._pc.createOffer(function(offer) {
  1079. util.log('Created offer');
  1080. self._pc.setLocalDescription(offer, function() {
  1081. util.log('Set localDescription to offer');
  1082. self._socket.send({
  1083. type: 'OFFER',
  1084. payload: {
  1085. sdp: offer,
  1086. serialization: self.serialization,
  1087. metadata: self.metadata
  1088. },
  1089. dst: self.peer
  1090. });
  1091. }, function(err) {
  1092. self.emit('error', 'Failed to setLocalDescription');
  1093. util.log('Failed to setLocalDescription, ', err);
  1094. });
  1095. });
  1096. };
  1097. /** Create an answer for PC. */
  1098. DataConnection.prototype._makeAnswer = function() {
  1099. var self = this;
  1100. this._pc.createAnswer(function(answer) {
  1101. util.log('Created answer');
  1102. self._pc.setLocalDescription(answer, function() {
  1103. util.log('Set localDescription to answer');
  1104. self._socket.send({
  1105. type: 'ANSWER',
  1106. payload: {
  1107. sdp: answer
  1108. },
  1109. dst: self.peer
  1110. });
  1111. }, function(err) {
  1112. self.emit('error', 'Failed to setLocalDescription');
  1113. util.log('Failed to setLocalDescription, ', err)
  1114. });
  1115. }, function(err) {
  1116. self.emit('error', 'Failed to create answer');
  1117. util.log('Failed to create answer, ', err)
  1118. });
  1119. };
  1120. DataConnection.prototype._cleanup = function() {
  1121. if (!!this._dc && this._dc.readyState != 'closed') {
  1122. this._dc.close();
  1123. this._dc = null;
  1124. }
  1125. if (!!this._pc && this._pc.readyState != 'closed') {
  1126. this._pc.close();
  1127. this._pc = null;
  1128. }
  1129. };
  1130. // Handles a DataChannel message.
  1131. DataConnection.prototype._handleDataMessage = function(e) {
  1132. var self = this;
  1133. var data = e.data;
  1134. var datatype = data.constructor;
  1135. if (this.serialization === 'binary') {
  1136. if (datatype === Blob) {
  1137. util.blobToArrayBuffer(data, function(ab) {
  1138. data = BinaryPack.unpack(ab);
  1139. self.emit('data', data);
  1140. });
  1141. return;
  1142. } else if (datatype === ArrayBuffer) {
  1143. data = BinaryPack.unpack(data);
  1144. } else if (datatype === String) {
  1145. var ab = util.binaryStringToArrayBuffer(data);
  1146. data = BinaryPack.unpack(ab);
  1147. }
  1148. } else if (this.serialization === 'json') {
  1149. data = JSON.parse(data);
  1150. }
  1151. this.emit('data', data);
  1152. };
  1153. /**
  1154. * Exposed functionality for users.
  1155. */
  1156. /** Allows user to close connection. */
  1157. DataConnection.prototype.close = function() {
  1158. this._cleanup();
  1159. var self = this;
  1160. if (this.open) {
  1161. this._socket.send({
  1162. type: 'LEAVE',
  1163. dst: self.peer
  1164. });
  1165. }
  1166. this.open = false;
  1167. this.emit('close', this.peer);
  1168. };
  1169. /** Allows user to send data. */
  1170. DataConnection.prototype.send = function(data) {
  1171. var self = this;
  1172. if (this.serialization === 'none') {
  1173. this._dc.send(data);
  1174. } else if (this.serialization === 'json') {
  1175. this._dc.send(JSON.stringify(data));
  1176. } else {
  1177. var blob = BinaryPack.pack(data);
  1178. // DataChannel currently only supports strings.
  1179. if (util.browserisms === 'Webkit') {
  1180. util.blobToBinaryString(blob, function(str){
  1181. self._dc.send(str);
  1182. });
  1183. } else {
  1184. this._dc.send(blob);
  1185. }
  1186. }
  1187. };
  1188. DataConnection.prototype.handleSDP = function(sdp, type) {
  1189. if (util.browserisms != 'Firefox') {
  1190. sdp = new RTCSessionDescription(sdp);
  1191. }
  1192. var self = this;
  1193. this._pc.setRemoteDescription(sdp, function() {
  1194. util.log('Set remoteDescription: ' + type);
  1195. // Firefoxism
  1196. /**if (type === 'ANSWER' && util.browserisms === 'Firefox') {
  1197. self._pc.connectDataConnection(self.localPort, self.remotePort);
  1198. self._socket.send({
  1199. type: 'PORT',
  1200. dst: self.peer,
  1201. payload: {
  1202. remote: self.localPort,
  1203. local: self.remotePort
  1204. }
  1205. });
  1206. } else*/ if (type === 'OFFER') {
  1207. self._makeAnswer();
  1208. }
  1209. }, function(err) {
  1210. self.emit('error', 'Failed to setRemoteDescription');
  1211. util.log('Failed to setRemoteDescription, ', err);
  1212. });
  1213. };
  1214. DataConnection.prototype.handleCandidate = function(message) {
  1215. var candidate = new RTCIceCandidate(message.candidate);
  1216. this._pc.addIceCandidate(candidate);
  1217. util.log('Added ice candidate');
  1218. };
  1219. DataConnection.prototype.handleLeave = function() {
  1220. util.log('Peer ' + this.peer + ' disconnected');
  1221. this.close();
  1222. };
  1223. /*
  1224. DataConnection.prototype.handlePort = function(message) {
  1225. if (!DataConnection.usedPorts) {
  1226. DataConnection.usedPorts = [];
  1227. }
  1228. DataConnection.usedPorts.push(message.local);
  1229. DataConnection.usedPorts.push(message.remote);
  1230. this._pc.connectDataConnection(message.local, message.remote);
  1231. };
  1232. */
  1233. /**
  1234. * An abstraction on top of WebSockets and XHR streaming to provide fastest
  1235. * possible connection for peers.
  1236. */
  1237. function Socket(host, port, key, id) {
  1238. if (!(this instanceof Socket)) return new Socket(server, id, key);
  1239. EventEmitter.call(this);
  1240. this._id = id;
  1241. var token = util.randomToken();
  1242. this._httpUrl = 'http://' + host + ':' + port + '/' + key + '/' + id + '/' + token;
  1243. this._wsUrl = 'ws://' + host + ':' + port + '/peerjs?key='+key+'&id='+id+'&token='+token;
  1244. };
  1245. util.inherits(Socket, EventEmitter);
  1246. /** Check in with ID or get one from server. */
  1247. Socket.prototype.start = function() {
  1248. this._startXhrStream();
  1249. this._startWebSocket();
  1250. };
  1251. /** Start up websocket communications. */
  1252. Socket.prototype._startWebSocket = function() {
  1253. var self = this;
  1254. if (!!this._socket) {
  1255. return;
  1256. }
  1257. this._socket = new WebSocket(this._wsUrl);
  1258. this._socket.onmessage = function(event) {
  1259. var data;
  1260. try {
  1261. data = JSON.parse(event.data);
  1262. } catch(e) {
  1263. util.log('Invalid server message', event.data);
  1264. return;
  1265. }
  1266. self.emit('message', data);
  1267. };
  1268. // Take care of the queue of connections if necessary and make sure Peer knows
  1269. // socket is open.
  1270. this._socket.onopen = function() {
  1271. if (!!self._timeout) {
  1272. clearTimeout(self._timeout);
  1273. setTimeout(function(){
  1274. self._http.abort();
  1275. self._http = null;
  1276. }, 5000);
  1277. }
  1278. util.log('Socket open');
  1279. };
  1280. };
  1281. /** Start XHR streaming. */
  1282. Socket.prototype._startXhrStream = function(n) {
  1283. try {
  1284. var self = this;
  1285. this._http = new XMLHttpRequest();
  1286. this._http._index = 1;
  1287. this._http._streamIndex = n || 0;
  1288. this._http.open('post', this._httpUrl + '/id?i=' + this._http._streamIndex, true);
  1289. this._http.onreadystatechange = function() {
  1290. if (this.readyState == 2 && !!this.old) {
  1291. this.old.abort();
  1292. delete this.old;
  1293. }
  1294. if (this.readyState > 2 && this.status == 200 && !!this.responseText) {
  1295. self._handleStream(this);
  1296. }
  1297. };
  1298. this._http.send(null);
  1299. this._setHTTPTimeout();
  1300. } catch(e) {
  1301. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  1302. }
  1303. };
  1304. /** Handles onreadystatechange response as a stream. */
  1305. Socket.prototype._handleStream = function(http) {
  1306. var self = this;
  1307. // 3 and 4 are loading/done state. All others are not relevant.
  1308. var message = http.responseText.split('\n')[http._index];
  1309. if (!!message) {
  1310. http._index += 1;
  1311. try {
  1312. message = JSON.parse(message);
  1313. } catch(e) {
  1314. util.log('Invalid server message', message);
  1315. return;
  1316. }
  1317. self.emit('message', message);
  1318. }
  1319. };
  1320. Socket.prototype._setHTTPTimeout = function() {
  1321. var self = this;
  1322. this._timeout = setTimeout(function() {
  1323. var old = self._http;
  1324. if (!self._wsOpen()) {
  1325. self._startXhrStream(old._streamIndex + 1);
  1326. self._http.old = old;
  1327. } else {
  1328. old.abort();
  1329. }
  1330. }, 25000);
  1331. };
  1332. /** Exposed send for DC & Peer. */
  1333. Socket.prototype.send = function(data) {
  1334. if (!data.type) {
  1335. this.emit('error', 'Invalid message');
  1336. return;
  1337. }
  1338. message = JSON.stringify(data);
  1339. if (this._wsOpen()) {
  1340. this._socket.send(message);
  1341. } else {
  1342. var http = new XMLHttpRequest();
  1343. var url = this._httpUrl + '/' + data.type.toLowerCase();
  1344. http.open('post', url, true);
  1345. http.setRequestHeader('Content-Type', 'application/json');
  1346. http.send(message);
  1347. }
  1348. };
  1349. Socket.prototype.close = function() {
  1350. if (!!this._wsOpen()) {
  1351. this._socket.close();
  1352. }
  1353. };
  1354. Socket.prototype._wsOpen = function() {
  1355. return !!this._socket && this._socket.readyState == 1;
  1356. };
  1357. })(this);