peer.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518
  1. /*! peerjs.js build:0.0.1, 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. };
  541. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  542. EventEmitter.prototype.once = function(type, listener, scope) {
  543. if ('function' !== typeof listener) {
  544. throw new Error('.once only takes instances of Function');
  545. }
  546. var self = this;
  547. function g() {
  548. self.removeListener(type, g);
  549. listener.apply(this, arguments);
  550. };
  551. g.listener = listener;
  552. self.on(type, g);
  553. return this;
  554. };
  555. EventEmitter.prototype.removeListener = function(type, listener, scope) {
  556. if ('function' !== typeof listener) {
  557. throw new Error('removeListener only takes instances of Function');
  558. }
  559. // does not use listeners(), so no side effect of creating _events[type]
  560. if (!this._events[type]) return this;
  561. var list = this._events[type];
  562. if (isArray(list)) {
  563. var position = -1;
  564. for (var i = 0, length = list.length; i < length; i++) {
  565. if (list[i] === listener ||
  566. (list[i].listener && list[i].listener === listener))
  567. {
  568. position = i;
  569. break;
  570. }
  571. }
  572. if (position < 0) return this;
  573. list.splice(position, 1);
  574. if (list.length == 0)
  575. delete this._events[type];
  576. } else if (list === listener ||
  577. (list.listener && list.listener === listener))
  578. {
  579. delete this._events[type];
  580. }
  581. return this;
  582. };
  583. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  584. EventEmitter.prototype.removeAllListeners = function(type) {
  585. if (arguments.length === 0) {
  586. this._events = {};
  587. return this;
  588. }
  589. // does not use listeners(), so no side effect of creating _events[type]
  590. if (type && this._events && this._events[type]) this._events[type] = null;
  591. return this;
  592. };
  593. EventEmitter.prototype.listeners = function(type) {
  594. if (!this._events[type]) this._events[type] = [];
  595. if (!isArray(this._events[type])) {
  596. this._events[type] = [this._events[type]];
  597. }
  598. return this._events[type];
  599. };
  600. EventEmitter.prototype.emit = function(type) {
  601. var type = arguments[0];
  602. var handler = this._events[type];
  603. if (!handler) return false;
  604. if (typeof handler == 'function') {
  605. switch (arguments.length) {
  606. // fast cases
  607. case 1:
  608. handler.call(this);
  609. break;
  610. case 2:
  611. handler.call(this, arguments[1]);
  612. break;
  613. case 3:
  614. handler.call(this, arguments[1], arguments[2]);
  615. break;
  616. // slower
  617. default:
  618. var l = arguments.length;
  619. var args = new Array(l - 1);
  620. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  621. handler.apply(this, args);
  622. }
  623. return true;
  624. } else if (isArray(handler)) {
  625. var l = arguments.length;
  626. var args = new Array(l - 1);
  627. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  628. var listeners = handler.slice();
  629. for (var i = 0, l = listeners.length; i < l; i++) {
  630. listeners[i].apply(this, args);
  631. }
  632. return true;
  633. } else {
  634. return false;
  635. }
  636. };
  637. var util = {
  638. debug: false,
  639. browserisms: '',
  640. inherits: function(ctor, superCtor) {
  641. ctor.super_ = superCtor;
  642. ctor.prototype = Object.create(superCtor.prototype, {
  643. constructor: {
  644. value: ctor,
  645. enumerable: false,
  646. writable: true,
  647. configurable: true
  648. }
  649. });
  650. },
  651. extend: function(dest, source) {
  652. for(var key in source) {
  653. if(source.hasOwnProperty(key)) {
  654. dest[key] = source[key];
  655. }
  656. }
  657. return dest;
  658. },
  659. pack: BinaryPack.pack,
  660. unpack: BinaryPack.unpack,
  661. randomPort: function() {
  662. return Math.round(Math.random() * 60535) + 5000;
  663. },
  664. log: function () {
  665. if (util.debug) {
  666. var copy = [];
  667. for (var i = 0; i < arguments.length; i++) {
  668. copy[i] = arguments[i];
  669. }
  670. copy.unshift('PeerJS: ');
  671. console.log.apply(console, copy);
  672. }
  673. },
  674. setZeroTimeout: (function(global) {
  675. var timeouts = [];
  676. var messageName = 'zero-timeout-message';
  677. // Like setTimeout, but only takes a function argument. There's
  678. // no time argument (always zero) and no arguments (you have to
  679. // use a closure).
  680. function setZeroTimeoutPostMessage(fn) {
  681. timeouts.push(fn);
  682. global.postMessage(messageName, '*');
  683. }
  684. function handleMessage(event) {
  685. if (event.source == global && event.data == messageName) {
  686. if (event.stopPropagation) {
  687. event.stopPropagation();
  688. }
  689. if (timeouts.length) {
  690. timeouts.shift()();
  691. }
  692. }
  693. }
  694. if (global.addEventListener) {
  695. global.addEventListener('message', handleMessage, true);
  696. } else if (global.attachEvent) {
  697. global.attachEvent('onmessage', handleMessage);
  698. }
  699. return setZeroTimeoutPostMessage;
  700. }(this)),
  701. blobToArrayBuffer: function(blob, cb){
  702. var fr = new FileReader();
  703. fr.onload = function(evt) {
  704. cb(evt.target.result);
  705. };
  706. fr.readAsArrayBuffer(blob);
  707. },
  708. blobToBinaryString: function(blob, cb){
  709. var fr = new FileReader();
  710. fr.onload = function(evt) {
  711. cb(evt.target.result);
  712. };
  713. fr.readAsBinaryString(blob);
  714. },
  715. binaryStringToArrayBuffer: function(binary) {
  716. var byteArray = new Uint8Array(binary.length);
  717. for (var i = 0; i < binary.length; i++) {
  718. byteArray[i] = binary.charCodeAt(i) & 0xff;
  719. }
  720. return byteArray.buffer;
  721. },
  722. randomToken: function () {
  723. return Math.random().toString(36).substr(2);
  724. }
  725. };
  726. var RTCPeerConnection = null;
  727. var getUserMedia = null;
  728. var attachMediaStream = null;
  729. if (navigator.mozGetUserMedia) {
  730. util.browserisms = 'Firefox'
  731. RTCPeerConnection = mozRTCPeerConnection;
  732. getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  733. } else if (navigator.webkitGetUserMedia) {
  734. util.browserisms = 'Webkit'
  735. RTCPeerConnection = webkitRTCPeerConnection;
  736. getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  737. }
  738. exports.RTCPeerConnection = RTCPeerConnection;
  739. exports.getUserMedia = getUserMedia;
  740. /**
  741. * A peer who can initiate connections with other peers.
  742. */
  743. function Peer(id, options) {
  744. if (id.constructor == Object) {
  745. options = id;
  746. id = undefined;
  747. }
  748. if (!(this instanceof Peer)) return new Peer(options);
  749. EventEmitter.call(this);
  750. options = util.extend({
  751. debug: false,
  752. host: '0.peerjs.com',
  753. port: 9000,
  754. key: 'peerjs',
  755. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  756. }, options);
  757. this._options = options;
  758. util.debug = options.debug;
  759. // Ensure alphanumeric_-
  760. if (id && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id)) {
  761. throw new Error('Peer ID can only contain alphanumerics, "_", and "-".');
  762. }
  763. if (options.key && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(options.key)) {
  764. throw new Error('API key can only contain alphanumerics, "_", and "-".');
  765. }
  766. // Connections for this peer.
  767. this.connections = {};
  768. // Queued connections to make.
  769. this._queued = [];
  770. // Init immediately if ID is given, otherwise ask server for ID
  771. if (id) {
  772. this.id = id;
  773. this._init();
  774. } else {
  775. this._getId();
  776. }
  777. };
  778. util.inherits(Peer, EventEmitter);
  779. Peer.prototype._getId = function(cb) {
  780. var self;
  781. try {
  782. var http = new XMLHttpRequest();
  783. var url = 'http://' + this._options.host + ':' + this._options.port + '/' + this._options.key + '/id';
  784. // If there's no ID we need to wait for one before trying to init socket.
  785. http.open('get', url, true);
  786. http.onreadystatechange = function() {
  787. if (http.readyState === 4) {
  788. self.id = id;
  789. self._init();
  790. }
  791. };
  792. http.send(null);
  793. } catch(e) {
  794. this.emit('error', 'Could not get an ID from the server');
  795. }
  796. };
  797. Peer.prototype._init = function() {
  798. var self = this;
  799. this._socket = new Socket(this._options.host, this._options.port, this._options.key, this.id);
  800. this._socket.on('message', function(data) {
  801. self._handleServerJSONMessage(data);
  802. });
  803. this._socket.on('error', function(error) {
  804. util.log(error);
  805. self.emit('error', error);
  806. self.destroy();
  807. });
  808. this._socket.on('close', function() {
  809. var msg = 'Underlying socket has closed';
  810. util.log('error', msg);
  811. self.emit('error', msg);
  812. self.destroy();
  813. });
  814. this._socket.start();
  815. }
  816. Peer.prototype._handleServerJSONMessage = function(message) {
  817. var peer = message.src;
  818. var connection = this.connections[peer];
  819. payload = message.payload;
  820. switch (message.type) {
  821. case 'OPEN':
  822. if (!this.id) {
  823. // If we're just now getting an ID then we may have a queue.
  824. this.id = payload.id;
  825. }
  826. this.emit('open', this.id);
  827. this._processQueue();
  828. break;
  829. case 'ERROR':
  830. this.emit('error', payload.msg);
  831. util.log(payload.msg);
  832. break;
  833. case 'ID-TAKEN':
  834. this.emit('error', 'ID `'+this.id+'` is taken');
  835. this.destroy();
  836. break;
  837. case 'OFFER':
  838. var options = {
  839. metadata: payload.metadata,
  840. sdp: payload.sdp,
  841. config: this._options.config,
  842. };
  843. var connection = new DataConnection(this.id, peer, this._socket, options);
  844. this._attachConnectionListeners(connection);
  845. this.connections[peer] = connection;
  846. this.emit('connection', connection, payload.metadata);
  847. break;
  848. case 'EXPIRE':
  849. connection = this.connections[payload.expired];
  850. if (connection) {
  851. connection.close();
  852. connection.emit('Could not connect to peer ' + connection.peer);
  853. }
  854. break;
  855. case 'ANSWER':
  856. if (connection) {
  857. connection.handleSDP(payload.sdp, message.type);
  858. }
  859. break;
  860. case 'CANDIDATE':
  861. if (connection) {
  862. connection.handleCandidate(payload);
  863. }
  864. break;
  865. case 'LEAVE':
  866. if (connection) {
  867. connection.handleLeave();
  868. }
  869. break;
  870. case 'INVALID-KEY':
  871. this.emit('error', 'API KEY "' + this._key + '" is invalid');
  872. this.destroy();
  873. break;
  874. case 'PORT':
  875. //if (util.browserisms === 'Firefox') {
  876. // connection.handlePort(payload);
  877. // break;
  878. //}
  879. default:
  880. util.log('Unrecognized message type:', message.type);
  881. break;
  882. }
  883. };
  884. /** Process queued calls to connect. */
  885. Peer.prototype._processQueue = function() {
  886. while (this._queued.length > 0) {
  887. var conn = this._queued.pop();
  888. conn.initialize(this.id);
  889. }
  890. };
  891. Peer.prototype._cleanup = function() {
  892. var self = this;
  893. var peers = Object.keys(this.connections);
  894. for (var i = 0, ii = peers.length; i < ii; i++) {
  895. this.connections[peers[i]].close();
  896. }
  897. util.setZeroTimeout(function(){
  898. self._socket.close();
  899. });
  900. this.emit('close');
  901. };
  902. /** Listeners for DataConnection events. */
  903. Peer.prototype._attachConnectionListeners = function(connection) {
  904. var self = this;
  905. connection.on('close', function(peer) {
  906. if (self.connections[peer]) {
  907. delete self.connections[peer];
  908. }
  909. });
  910. };
  911. /** Exposed connect function for users. Will try to connect later if user
  912. * is waiting for an ID. */
  913. // TODO: pause XHR streaming when not in use and start again when this is
  914. // called.
  915. Peer.prototype.connect = function(peer, metadata, options) {
  916. options = util.extend({
  917. metadata: metadata,
  918. config: this._options.config,
  919. }, options);
  920. var connection = new DataConnection(this.id, peer, this._socket, options);
  921. this._attachConnectionListeners(connection);
  922. this.connections[peer] = connection;
  923. if (!this.id) {
  924. this._queued.push(connection);
  925. }
  926. return connection;
  927. };
  928. Peer.prototype.destroy = function() {
  929. this._cleanup();
  930. };
  931. exports.Peer = Peer;
  932. /**
  933. * A DataChannel|PeerConnection between two Peers.
  934. */
  935. function DataConnection(id, peer, socket, options) {
  936. if (!(this instanceof DataConnection)) return new DataConnection(options);
  937. EventEmitter.call(this);
  938. options = util.extend({
  939. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] },
  940. reliable: false
  941. }, options);
  942. this._options = options;
  943. // Connection is not open yet.
  944. this.open = false;
  945. this.id = id;
  946. this.peer = peer;
  947. this.metadata = options.metadata;
  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) {
  956. if (!!id) {
  957. this.id = id;
  958. }
  959. // Firefoxism: connectDataConnection ports.
  960. /*if (util.browserisms === 'Firefox') {
  961. this._firefoxPortSetup();
  962. }*/
  963. // Set up PeerConnection.
  964. this._startPeerConnection();
  965. // Listen for ICE candidates
  966. this._setupIce();
  967. // Listen for negotiation needed
  968. // ** Chrome only.
  969. if (util.browserisms !== 'Firefox' && !!this.id) {
  970. this._setupOffer();
  971. }
  972. // Listen for or create a data channel
  973. this._setupDataChannel();
  974. var self = this;
  975. if (!!this._sdp) {
  976. this.handleSDP(this._sdp, 'OFFER');
  977. }
  978. // Makes offer if Firefox
  979. /*if (util.browserisms === 'Firefox') {
  980. this._firefoxAdditional();
  981. }*/
  982. // No-op this.
  983. this.initialize = function() {};
  984. }
  985. DataConnection.prototype._setupOffer = function() {
  986. var self = this;
  987. util.log('Listening for `negotiationneeded`');
  988. this._pc.onnegotiationneeded = function() {
  989. util.log('`negotiationneeded` triggered');
  990. self._makeOffer();
  991. };
  992. }
  993. DataConnection.prototype._setupDataChannel = function() {
  994. var self = this;
  995. if (this._originator) {
  996. util.log('Creating data channel');
  997. this._dc = this._pc.createDataChannel(this.peer, { reliable: this._options.reliable });
  998. this._configureDataChannel();
  999. } else {
  1000. util.log('Listening for data channel');
  1001. this._pc.ondatachannel = function(evt) {
  1002. util.log('Received data channel');
  1003. self._dc = evt.channel;
  1004. self._configureDataChannel();
  1005. };
  1006. }
  1007. };
  1008. /** Starts a PeerConnection and sets up handlers. */
  1009. DataConnection.prototype._startPeerConnection = function() {
  1010. util.log('Creating RTCPeerConnection');
  1011. this._pc = new RTCPeerConnection(this._options.config, { optional:[ { RtpDataChannels: true } ]});
  1012. };
  1013. /** Takes care of ice handlers. */
  1014. DataConnection.prototype._setupIce = function() {
  1015. util.log('Listening for ICE candidates');
  1016. var self = this;
  1017. this._pc.onicecandidate = function(evt) {
  1018. if (evt.candidate) {
  1019. util.log('Received ICE candidates');
  1020. self._socket.send({
  1021. type: 'CANDIDATE',
  1022. payload: {
  1023. candidate: evt.candidate
  1024. },
  1025. dst: self.peer
  1026. });
  1027. }
  1028. };
  1029. };
  1030. /*DataConnection.prototype._firefoxPortSetup = function() {
  1031. if (!DataConnection.usedPorts) {
  1032. DataConnection.usedPorts = [];
  1033. }
  1034. this.localPort = util.randomPort();
  1035. while (DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  1036. this.localPort = util.randomPort();
  1037. }
  1038. this.remotePort = util.randomPort();
  1039. while (this.remotePort === this.localPort ||
  1040. DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  1041. this.remotePort = util.randomPort();
  1042. }
  1043. DataConnection.usedPorts.push(this.remotePort);
  1044. DataConnection.usedPorts.push(this.localPort);
  1045. }*/
  1046. DataConnection.prototype._configureDataChannel = function() {
  1047. var self = this;
  1048. if (util.browserisms !== 'Webkit') {
  1049. this._dc.binaryType = 'arraybuffer';
  1050. }
  1051. this._dc.onopen = function() {
  1052. util.log('Data channel connection success');
  1053. self.open = true;
  1054. self.emit('open');
  1055. };
  1056. this._dc.onmessage = function(e) {
  1057. self._handleDataMessage(e);
  1058. };
  1059. this._dc.onclose = function(e) {
  1060. self.emit('close');
  1061. };
  1062. };
  1063. /** Decide whether to handle Firefoxisms. */
  1064. /*DataConnection.prototype._firefoxAdditional = function() {
  1065. var self = this;
  1066. getUserMedia({ audio: true, fake: true }, function(s) {
  1067. self._pc.addStream(s);
  1068. if (self._originator) {
  1069. self._makeOffer();
  1070. }
  1071. }, function(err) { util.log('Could not getUserMedia'); });
  1072. };*/
  1073. DataConnection.prototype._makeOffer = function() {
  1074. var self = this;
  1075. this._pc.createOffer(function(offer) {
  1076. util.log('Created offer');
  1077. self._pc.setLocalDescription(offer, function() {
  1078. util.log('Set localDescription to offer');
  1079. self._socket.send({
  1080. type: 'OFFER',
  1081. payload: {
  1082. sdp: offer,
  1083. metadata: self.metadata
  1084. },
  1085. dst: self.peer
  1086. });
  1087. }, function(err) {
  1088. self.emit('error', 'Failed to setLocalDescription');
  1089. util.log('Failed to setLocalDescription, ', err);
  1090. });
  1091. });
  1092. };
  1093. /** Create an answer for PC. */
  1094. DataConnection.prototype._makeAnswer = function() {
  1095. var self = this;
  1096. this._pc.createAnswer(function(answer) {
  1097. util.log('Created answer');
  1098. self._pc.setLocalDescription(answer, function() {
  1099. util.log('Set localDescription to answer');
  1100. self._socket.send({
  1101. type: 'ANSWER',
  1102. payload: {
  1103. sdp: answer
  1104. },
  1105. dst: self.peer
  1106. });
  1107. }, function(err) {
  1108. self.emit('error', 'Failed to setLocalDescription');
  1109. util.log('Failed to setLocalDescription, ', err)
  1110. });
  1111. }, function(err) {
  1112. self.emit('error', 'Failed to create answer');
  1113. util.log('Failed to create answer, ', err)
  1114. });
  1115. };
  1116. DataConnection.prototype._cleanup = function() {
  1117. if (!!this._dc && this._dc.readyState != 'closed') {
  1118. this._dc.close();
  1119. this._dc = null;
  1120. }
  1121. if (!!this._pc && this._pc.readyState != 'closed') {
  1122. this._pc.close();
  1123. this._pc = null;
  1124. }
  1125. };
  1126. // Handles a DataChannel message.
  1127. DataConnection.prototype._handleDataMessage = function(e) {
  1128. var self = this;
  1129. if (e.data.constructor === Blob) {
  1130. util.blobToArrayBuffer(e.data, function(ab) {
  1131. var data = BinaryPack.unpack(ab);
  1132. self.emit('data', data);
  1133. });
  1134. } else if (e.data.constructor === ArrayBuffer) {
  1135. var data = BinaryPack.unpack(e.data);
  1136. self.emit('data', data);
  1137. } else if (e.data.constructor === String) {
  1138. var ab = util.binaryStringToArrayBuffer(e.data);
  1139. var data = BinaryPack.unpack(ab);
  1140. self.emit('data', data);
  1141. }
  1142. };
  1143. /**
  1144. * Exposed functionality for users.
  1145. */
  1146. /** Allows user to close connection. */
  1147. DataConnection.prototype.close = function() {
  1148. this._cleanup();
  1149. var self = this;
  1150. if (this.open) {
  1151. this._socket.send({
  1152. type: 'LEAVE',
  1153. dst: self.peer
  1154. });
  1155. }
  1156. this.open = false;
  1157. this.emit('close', this.peer);
  1158. };
  1159. /** Allows user to send data. */
  1160. DataConnection.prototype.send = function(data) {
  1161. var self = this;
  1162. var blob = BinaryPack.pack(data);
  1163. if (util.browserisms === 'Webkit') {
  1164. util.blobToBinaryString(blob, function(str){
  1165. self._dc.send(str);
  1166. });
  1167. } else {
  1168. this._dc.send(blob);
  1169. }
  1170. };
  1171. DataConnection.prototype.handleSDP = function(sdp, type) {
  1172. if (util.browserisms != 'Firefox') {
  1173. sdp = new RTCSessionDescription(sdp);
  1174. }
  1175. var self = this;
  1176. this._pc.setRemoteDescription(sdp, function() {
  1177. util.log('Set remoteDescription: ' + type);
  1178. // Firefoxism
  1179. /**if (type === 'ANSWER' && util.browserisms === 'Firefox') {
  1180. self._pc.connectDataConnection(self.localPort, self.remotePort);
  1181. self._socket.send({
  1182. type: 'PORT',
  1183. dst: self.peer,
  1184. payload: {
  1185. remote: self.localPort,
  1186. local: self.remotePort
  1187. }
  1188. });
  1189. } else*/ if (type === 'OFFER') {
  1190. self._makeAnswer();
  1191. }
  1192. }, function(err) {
  1193. self.emit('error', 'Failed to setRemoteDescription');
  1194. util.log('Failed to setRemoteDescription, ', err);
  1195. });
  1196. };
  1197. DataConnection.prototype.handleCandidate = function(message) {
  1198. var candidate = new RTCIceCandidate(message.candidate);
  1199. this._pc.addIceCandidate(candidate);
  1200. util.log('Added ice candidate');
  1201. };
  1202. DataConnection.prototype.handleLeave = function() {
  1203. util.log('Peer ' + this.peer + ' disconnected');
  1204. this.close();
  1205. };
  1206. /*
  1207. DataConnection.prototype.handlePort = function(message) {
  1208. if (!DataConnection.usedPorts) {
  1209. DataConnection.usedPorts = [];
  1210. }
  1211. DataConnection.usedPorts.push(message.local);
  1212. DataConnection.usedPorts.push(message.remote);
  1213. this._pc.connectDataConnection(message.local, message.remote);
  1214. };
  1215. */
  1216. /**
  1217. * An abstraction on top of WebSockets and XHR streaming to provide fastest
  1218. * possible connection for peers.
  1219. */
  1220. function Socket(host, port, key, id) {
  1221. if (!(this instanceof Socket)) return new Socket(server, id, key);
  1222. EventEmitter.call(this);
  1223. this._id = id;
  1224. var token = util.randomToken();
  1225. this._httpUrl = 'http://' + host + ':' + port + '/' + key + '/' + id + '/' + token;
  1226. this._wsUrl = 'ws://' + this._server + '/ws?key='+key+'id='+id+'token='+token;
  1227. this._index = 1;
  1228. };
  1229. util.inherits(Socket, EventEmitter);
  1230. /** Check in with ID or get one from server. */
  1231. Socket.prototype.start = function() {
  1232. this._startXhrStream();
  1233. this._startWebSocket();
  1234. };
  1235. /** Start up websocket communications. */
  1236. Socket.prototype._startWebSocket = function() {
  1237. var self = this;
  1238. if (!!this._socket) {
  1239. return;
  1240. }
  1241. this._socket = new WebSocket(wsurl);
  1242. this._socket.onmessage = function(event) {
  1243. var data;
  1244. try {
  1245. data = JSON.parse(event.data);
  1246. } catch(e) {
  1247. util.log('Invalid server message', event.data);
  1248. return;
  1249. }
  1250. self.emit('message', data);
  1251. };
  1252. // Take care of the queue of connections if necessary and make sure Peer knows
  1253. // socket is open.
  1254. this._socket.onopen = function() {
  1255. if (!!self._timeout) {
  1256. clearTimeout(self._timeout);
  1257. self._http.abort();
  1258. self._http = null;
  1259. }
  1260. util.log('Socket open');
  1261. };
  1262. };
  1263. /** Start XHR streaming. */
  1264. Socket.prototype._startXhrStream = function() {
  1265. try {
  1266. var self = this;
  1267. this._http = new XMLHttpRequest();
  1268. this._http.open('post', this._httpUrl + '/id', true);
  1269. this._http.onreadystatechange = function() {
  1270. if (!!self._http.old) {
  1271. self._http.old.abort();
  1272. delete self._http.old;
  1273. }
  1274. if (self._http.readyState > 2 && self._http.status == 200 && !!self._http.responseText) {
  1275. self._handleStream();
  1276. }
  1277. };
  1278. this._http.send(null);
  1279. this._setHTTPTimeout();
  1280. } catch(e) {
  1281. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  1282. }
  1283. };
  1284. /** Handles onreadystatechange response as a stream. */
  1285. Socket.prototype._handleStream = function() {
  1286. var self = this;
  1287. // 3 and 4 are loading/done state. All others are not relevant.
  1288. var message = this._http.responseText.split('\n')[this._index];
  1289. if (!!message) {
  1290. this._index += 1;
  1291. try {
  1292. message = JSON.parse(message);
  1293. } catch(e) {
  1294. util.log('Invalid server message', message);
  1295. return;
  1296. }
  1297. self.emit('message', message);
  1298. }
  1299. };
  1300. Socket.prototype._setHTTPTimeout = function() {
  1301. var self = this;
  1302. this._timeout = setTimeout(function() {
  1303. var old = self._http;
  1304. if (!self._wsOpen()) {
  1305. self._index = 1;
  1306. self._startXhrStream();
  1307. self._http.old = old;
  1308. } else {
  1309. old.abort();
  1310. }
  1311. }, 30000);
  1312. };
  1313. /** Exposed send for DC & Peer. */
  1314. Socket.prototype.send = function(data) {
  1315. if (!data.type) {
  1316. this.emit('error', 'Invalid message');
  1317. }
  1318. message = JSON.stringify(data);
  1319. if (this._wsOpen()) {
  1320. this._socket.send(message);
  1321. } else {
  1322. var http = new XMLHttpRequest();
  1323. var url = this._httpUrl + '/' + type.toLowerCase();
  1324. http.open('post', url, true);
  1325. http.setRequestHeader('Content-Type', 'application/json');
  1326. http.send(message);
  1327. }
  1328. };
  1329. Socket.prototype.close = function() {
  1330. if (!!this._wsOpen()) {
  1331. this._socket.close();
  1332. }
  1333. };
  1334. Socket.prototype._wsOpen = function() {
  1335. return !!this._socket && this._socket.readyState == 1;
  1336. };
  1337. })(this);