peer.js 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181
  1. /*! peerjs.js build:0.2.7, 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, utf8){
  61. var packer = new Packer(utf8);
  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(utf8){
  284. this.utf8 = utf8;
  285. this.bufferBuilder = new BufferBuilder();
  286. }
  287. Packer.prototype.pack = function(value){
  288. var type = typeof(value);
  289. if (type == 'string'){
  290. this.pack_string(value);
  291. } else if (type == 'number'){
  292. if (Math.floor(value) === value){
  293. this.pack_integer(value);
  294. } else{
  295. this.pack_double(value);
  296. }
  297. } else if (type == 'boolean'){
  298. if (value === true){
  299. this.bufferBuilder.append(0xc3);
  300. } else if (value === false){
  301. this.bufferBuilder.append(0xc2);
  302. }
  303. } else if (type == 'undefined'){
  304. this.bufferBuilder.append(0xc0);
  305. } else if (type == 'object'){
  306. if (value === null){
  307. this.bufferBuilder.append(0xc0);
  308. } else {
  309. var constructor = value.constructor;
  310. if (constructor == Array){
  311. this.pack_array(value);
  312. } else if (constructor == Blob || constructor == File) {
  313. this.pack_bin(value);
  314. } else if (constructor == ArrayBuffer) {
  315. if(binaryFeatures.useArrayBufferView) {
  316. this.pack_bin(new Uint8Array(value));
  317. } else {
  318. this.pack_bin(value);
  319. }
  320. } else if ('BYTES_PER_ELEMENT' in value){
  321. if(binaryFeatures.useArrayBufferView) {
  322. this.pack_bin(value);
  323. } else {
  324. this.pack_bin(value.buffer);
  325. }
  326. } else if (constructor == Object){
  327. this.pack_object(value);
  328. } else if (constructor == Date){
  329. this.pack_string(value.toString());
  330. } else if (typeof value.toBinaryPack == 'function'){
  331. this.bufferBuilder.append(value.toBinaryPack());
  332. } else {
  333. throw new Error('Type "' + constructor.toString() + '" not yet supported');
  334. }
  335. }
  336. } else {
  337. throw new Error('Type "' + type + '" not yet supported');
  338. }
  339. return this.bufferBuilder.getBuffer();
  340. }
  341. Packer.prototype.pack_bin = function(blob){
  342. var length = blob.length || blob.byteLength || blob.size;
  343. if (length <= 0x0f){
  344. this.pack_uint8(0xa0 + length);
  345. } else if (length <= 0xffff){
  346. this.bufferBuilder.append(0xda) ;
  347. this.pack_uint16(length);
  348. } else if (length <= 0xffffffff){
  349. this.bufferBuilder.append(0xdb);
  350. this.pack_uint32(length);
  351. } else{
  352. throw new Error('Invalid length');
  353. return;
  354. }
  355. this.bufferBuilder.append(blob);
  356. }
  357. Packer.prototype.pack_string = function(str){
  358. var length;
  359. if (this.utf8) {
  360. var blob = new Blob([str]);
  361. length = blob.size;
  362. } else {
  363. length = str.length;
  364. }
  365. if (length <= 0x0f){
  366. this.pack_uint8(0xb0 + length);
  367. } else if (length <= 0xffff){
  368. this.bufferBuilder.append(0xd8) ;
  369. this.pack_uint16(length);
  370. } else if (length <= 0xffffffff){
  371. this.bufferBuilder.append(0xd9);
  372. this.pack_uint32(length);
  373. } else{
  374. throw new Error('Invalid length');
  375. return;
  376. }
  377. this.bufferBuilder.append(str);
  378. }
  379. Packer.prototype.pack_array = function(ary){
  380. var length = ary.length;
  381. if (length <= 0x0f){
  382. this.pack_uint8(0x90 + length);
  383. } else if (length <= 0xffff){
  384. this.bufferBuilder.append(0xdc)
  385. this.pack_uint16(length);
  386. } else if (length <= 0xffffffff){
  387. this.bufferBuilder.append(0xdd);
  388. this.pack_uint32(length);
  389. } else{
  390. throw new Error('Invalid length');
  391. }
  392. for(var i = 0; i < length ; i++){
  393. this.pack(ary[i]);
  394. }
  395. }
  396. Packer.prototype.pack_integer = function(num){
  397. if ( -0x20 <= num && num <= 0x7f){
  398. this.bufferBuilder.append(num & 0xff);
  399. } else if (0x00 <= num && num <= 0xff){
  400. this.bufferBuilder.append(0xcc);
  401. this.pack_uint8(num);
  402. } else if (-0x80 <= num && num <= 0x7f){
  403. this.bufferBuilder.append(0xd0);
  404. this.pack_int8(num);
  405. } else if ( 0x0000 <= num && num <= 0xffff){
  406. this.bufferBuilder.append(0xcd);
  407. this.pack_uint16(num);
  408. } else if (-0x8000 <= num && num <= 0x7fff){
  409. this.bufferBuilder.append(0xd1);
  410. this.pack_int16(num);
  411. } else if ( 0x00000000 <= num && num <= 0xffffffff){
  412. this.bufferBuilder.append(0xce);
  413. this.pack_uint32(num);
  414. } else if (-0x80000000 <= num && num <= 0x7fffffff){
  415. this.bufferBuilder.append(0xd2);
  416. this.pack_int32(num);
  417. } else if (-0x8000000000000000 <= num && num <= 0x7FFFFFFFFFFFFFFF){
  418. this.bufferBuilder.append(0xd3);
  419. this.pack_int64(num);
  420. } else if (0x0000000000000000 <= num && num <= 0xFFFFFFFFFFFFFFFF){
  421. this.bufferBuilder.append(0xcf);
  422. this.pack_uint64(num);
  423. } else{
  424. throw new Error('Invalid integer');
  425. }
  426. }
  427. Packer.prototype.pack_double = function(num){
  428. var sign = 0;
  429. if (num < 0){
  430. sign = 1;
  431. num = -num;
  432. }
  433. var exp = Math.floor(Math.log(num) / Math.LN2);
  434. var frac0 = num / Math.pow(2, exp) - 1;
  435. var frac1 = Math.floor(frac0 * Math.pow(2, 52));
  436. var b32 = Math.pow(2, 32);
  437. var h32 = (sign << 31) | ((exp+1023) << 20) |
  438. (frac1 / b32) & 0x0fffff;
  439. var l32 = frac1 % b32;
  440. this.bufferBuilder.append(0xcb);
  441. this.pack_int32(h32);
  442. this.pack_int32(l32);
  443. }
  444. Packer.prototype.pack_object = function(obj){
  445. var keys = Object.keys(obj);
  446. var length = keys.length;
  447. if (length <= 0x0f){
  448. this.pack_uint8(0x80 + length);
  449. } else if (length <= 0xffff){
  450. this.bufferBuilder.append(0xde);
  451. this.pack_uint16(length);
  452. } else if (length <= 0xffffffff){
  453. this.bufferBuilder.append(0xdf);
  454. this.pack_uint32(length);
  455. } else{
  456. throw new Error('Invalid length');
  457. }
  458. for(var prop in obj){
  459. if (obj.hasOwnProperty(prop)){
  460. this.pack(prop);
  461. this.pack(obj[prop]);
  462. }
  463. }
  464. }
  465. Packer.prototype.pack_uint8 = function(num){
  466. this.bufferBuilder.append(num);
  467. }
  468. Packer.prototype.pack_uint16 = function(num){
  469. this.bufferBuilder.append(num >> 8);
  470. this.bufferBuilder.append(num & 0xff);
  471. }
  472. Packer.prototype.pack_uint32 = function(num){
  473. var n = num & 0xffffffff;
  474. this.bufferBuilder.append((n & 0xff000000) >>> 24);
  475. this.bufferBuilder.append((n & 0x00ff0000) >>> 16);
  476. this.bufferBuilder.append((n & 0x0000ff00) >>> 8);
  477. this.bufferBuilder.append((n & 0x000000ff));
  478. }
  479. Packer.prototype.pack_uint64 = function(num){
  480. var high = num / Math.pow(2, 32);
  481. var low = num % Math.pow(2, 32);
  482. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  483. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  484. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  485. this.bufferBuilder.append((high & 0x000000ff));
  486. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  487. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  488. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  489. this.bufferBuilder.append((low & 0x000000ff));
  490. }
  491. Packer.prototype.pack_int8 = function(num){
  492. this.bufferBuilder.append(num & 0xff);
  493. }
  494. Packer.prototype.pack_int16 = function(num){
  495. this.bufferBuilder.append((num & 0xff00) >> 8);
  496. this.bufferBuilder.append(num & 0xff);
  497. }
  498. Packer.prototype.pack_int32 = function(num){
  499. this.bufferBuilder.append((num >>> 24) & 0xff);
  500. this.bufferBuilder.append((num & 0x00ff0000) >>> 16);
  501. this.bufferBuilder.append((num & 0x0000ff00) >>> 8);
  502. this.bufferBuilder.append((num & 0x000000ff));
  503. }
  504. Packer.prototype.pack_int64 = function(num){
  505. var high = Math.floor(num / Math.pow(2, 32));
  506. var low = num % Math.pow(2, 32);
  507. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  508. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  509. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  510. this.bufferBuilder.append((high & 0x000000ff));
  511. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  512. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  513. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  514. this.bufferBuilder.append((low & 0x000000ff));
  515. }
  516. /**
  517. * Light EventEmitter. Ported from Node.js/events.js
  518. * Eric Zhang
  519. */
  520. /**
  521. * EventEmitter class
  522. * Creates an object with event registering and firing methods
  523. */
  524. function EventEmitter() {
  525. // Initialise required storage variables
  526. this._events = {};
  527. }
  528. var isArray = Array.isArray;
  529. EventEmitter.prototype.addListener = function(type, listener, scope, once) {
  530. if ('function' !== typeof listener) {
  531. throw new Error('addListener only takes instances of Function');
  532. }
  533. // To avoid recursion in the case that type == "newListeners"! Before
  534. // adding it to the listeners, first emit "newListeners".
  535. this.emit('newListener', type, typeof listener.listener === 'function' ?
  536. listener.listener : listener);
  537. if (!this._events[type]) {
  538. // Optimize the case of one listener. Don't need the extra array object.
  539. this._events[type] = listener;
  540. } else if (isArray(this._events[type])) {
  541. // If we've already got an array, just append.
  542. this._events[type].push(listener);
  543. } else {
  544. // Adding the second element, need to change to array.
  545. this._events[type] = [this._events[type], listener];
  546. }
  547. return this;
  548. };
  549. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  550. EventEmitter.prototype.once = function(type, listener, scope) {
  551. if ('function' !== typeof listener) {
  552. throw new Error('.once only takes instances of Function');
  553. }
  554. var self = this;
  555. function g() {
  556. self.removeListener(type, g);
  557. listener.apply(this, arguments);
  558. };
  559. g.listener = listener;
  560. self.on(type, g);
  561. return this;
  562. };
  563. EventEmitter.prototype.removeListener = function(type, listener, scope) {
  564. if ('function' !== typeof listener) {
  565. throw new Error('removeListener only takes instances of Function');
  566. }
  567. // does not use listeners(), so no side effect of creating _events[type]
  568. if (!this._events[type]) return this;
  569. var list = this._events[type];
  570. if (isArray(list)) {
  571. var position = -1;
  572. for (var i = 0, length = list.length; i < length; i++) {
  573. if (list[i] === listener ||
  574. (list[i].listener && list[i].listener === listener))
  575. {
  576. position = i;
  577. break;
  578. }
  579. }
  580. if (position < 0) return this;
  581. list.splice(position, 1);
  582. if (list.length == 0)
  583. delete this._events[type];
  584. } else if (list === listener ||
  585. (list.listener && list.listener === listener))
  586. {
  587. delete this._events[type];
  588. }
  589. return this;
  590. };
  591. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  592. EventEmitter.prototype.removeAllListeners = function(type) {
  593. if (arguments.length === 0) {
  594. this._events = {};
  595. return this;
  596. }
  597. // does not use listeners(), so no side effect of creating _events[type]
  598. if (type && this._events && this._events[type]) this._events[type] = null;
  599. return this;
  600. };
  601. EventEmitter.prototype.listeners = function(type) {
  602. if (!this._events[type]) this._events[type] = [];
  603. if (!isArray(this._events[type])) {
  604. this._events[type] = [this._events[type]];
  605. }
  606. return this._events[type];
  607. };
  608. EventEmitter.prototype.emit = function(type) {
  609. var type = arguments[0];
  610. var handler = this._events[type];
  611. if (!handler) return false;
  612. if (typeof handler == 'function') {
  613. switch (arguments.length) {
  614. // fast cases
  615. case 1:
  616. handler.call(this);
  617. break;
  618. case 2:
  619. handler.call(this, arguments[1]);
  620. break;
  621. case 3:
  622. handler.call(this, arguments[1], arguments[2]);
  623. break;
  624. // slower
  625. default:
  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. handler.apply(this, args);
  630. }
  631. return true;
  632. } else if (isArray(handler)) {
  633. var l = arguments.length;
  634. var args = new Array(l - 1);
  635. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  636. var listeners = handler.slice();
  637. for (var i = 0, l = listeners.length; i < l; i++) {
  638. listeners[i].apply(this, args);
  639. }
  640. return true;
  641. } else {
  642. return false;
  643. }
  644. };
  645. var util = {
  646. chromeCompatible: true,
  647. firefoxCompatible: true,
  648. chromeVersion: 26,
  649. firefoxVersion: 22,
  650. debug: false,
  651. browserisms: '',
  652. inherits: function(ctor, superCtor) {
  653. ctor.super_ = superCtor;
  654. ctor.prototype = Object.create(superCtor.prototype, {
  655. constructor: {
  656. value: ctor,
  657. enumerable: false,
  658. writable: true,
  659. configurable: true
  660. }
  661. });
  662. },
  663. extend: function(dest, source) {
  664. for(var key in source) {
  665. if(source.hasOwnProperty(key)) {
  666. dest[key] = source[key];
  667. }
  668. }
  669. return dest;
  670. },
  671. pack: BinaryPack.pack,
  672. unpack: BinaryPack.unpack,
  673. log: function () {
  674. if (util.debug) {
  675. var err = false;
  676. var copy = Array.prototype.slice.call(arguments);
  677. copy.unshift('PeerJS: ');
  678. for (var i = 0, l = copy.length; i < l; i++){
  679. if (copy[i] instanceof Error) {
  680. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  681. err = true;
  682. }
  683. }
  684. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  685. }
  686. },
  687. setZeroTimeout: (function(global) {
  688. var timeouts = [];
  689. var messageName = 'zero-timeout-message';
  690. // Like setTimeout, but only takes a function argument. There's
  691. // no time argument (always zero) and no arguments (you have to
  692. // use a closure).
  693. function setZeroTimeoutPostMessage(fn) {
  694. timeouts.push(fn);
  695. global.postMessage(messageName, '*');
  696. }
  697. function handleMessage(event) {
  698. if (event.source == global && event.data == messageName) {
  699. if (event.stopPropagation) {
  700. event.stopPropagation();
  701. }
  702. if (timeouts.length) {
  703. timeouts.shift()();
  704. }
  705. }
  706. }
  707. if (global.addEventListener) {
  708. global.addEventListener('message', handleMessage, true);
  709. } else if (global.attachEvent) {
  710. global.attachEvent('onmessage', handleMessage);
  711. }
  712. return setZeroTimeoutPostMessage;
  713. }(this)),
  714. blobToArrayBuffer: function(blob, cb){
  715. var fr = new FileReader();
  716. fr.onload = function(evt) {
  717. cb(evt.target.result);
  718. };
  719. fr.readAsArrayBuffer(blob);
  720. },
  721. blobToBinaryString: function(blob, cb){
  722. var fr = new FileReader();
  723. fr.onload = function(evt) {
  724. cb(evt.target.result);
  725. };
  726. fr.readAsBinaryString(blob);
  727. },
  728. binaryStringToArrayBuffer: function(binary) {
  729. var byteArray = new Uint8Array(binary.length);
  730. for (var i = 0; i < binary.length; i++) {
  731. byteArray[i] = binary.charCodeAt(i) & 0xff;
  732. }
  733. return byteArray.buffer;
  734. },
  735. randomToken: function () {
  736. return Math.random().toString(36).substr(2);
  737. },
  738. isBrowserCompatible: function() {
  739. var c, f;
  740. if (this.chromeCompatible) {
  741. if ((c = navigator.userAgent.split('Chrome/')) && c.length > 1) {
  742. // Get version #.
  743. var v = c[1].split('.')[0];
  744. return parseInt(v) >= this.chromeVersion;
  745. }
  746. }
  747. if (this.firefoxCompatible) {
  748. if ((f = navigator.userAgent.split('Firefox/')) && f.length > 1) {
  749. // Get version #.
  750. var v = f[1].split('.')[0];
  751. return parseInt(v) >= this.firefoxVersion;
  752. }
  753. }
  754. return false;
  755. },
  756. isSecure: function() {
  757. return location.protocol === 'https:';
  758. }
  759. };
  760. /**
  761. * Reliable transfer for Chrome Canary DataChannel impl.
  762. * Author: @michellebu
  763. */
  764. function Reliable(dc, debug) {
  765. if (!(this instanceof Reliable)) return new Reliable(dc);
  766. this._dc = dc;
  767. util.debug = debug;
  768. // Messages sent/received so far.
  769. // id: { ack: n, chunks: [...] }
  770. this._outgoing = {};
  771. // id: { ack: ['ack', id, n], chunks: [...] }
  772. this._incoming = {};
  773. this._received = {};
  774. // Window size.
  775. this._window = 1000;
  776. // MTU.
  777. this._mtu = 500;
  778. // Interval for setInterval. In ms.
  779. this._interval = 0;
  780. // Messages sent.
  781. this._count = 0;
  782. // Outgoing message queue.
  783. this._queue = [];
  784. this._setupDC();
  785. };
  786. // Send a message reliably.
  787. Reliable.prototype.send = function(msg) {
  788. // Determine if chunking is necessary.
  789. var bl = util.pack(msg);
  790. if (bl.size < this._mtu) {
  791. this._handleSend(['no', bl]);
  792. return;
  793. }
  794. this._outgoing[this._count] = {
  795. ack: 0,
  796. chunks: this._chunk(bl)
  797. };
  798. if (util.debug) {
  799. this._outgoing[this._count].timer = new Date();
  800. }
  801. // Send prelim window.
  802. this._sendWindowedChunks(this._count);
  803. this._count += 1;
  804. };
  805. // Set up interval for processing queue.
  806. Reliable.prototype._setupInterval = function() {
  807. // TODO: fail gracefully.
  808. var self = this;
  809. this._timeout = setInterval(function() {
  810. // FIXME: String stuff makes things terribly async.
  811. var msg = self._queue.shift();
  812. if (msg._multiple) {
  813. for (var i = 0, ii = msg.length; i < ii; i += 1) {
  814. self._intervalSend(msg[i]);
  815. }
  816. } else {
  817. self._intervalSend(msg);
  818. }
  819. }, this._interval);
  820. };
  821. Reliable.prototype._intervalSend = function(msg) {
  822. var self = this;
  823. msg = util.pack(msg);
  824. util.blobToBinaryString(msg, function(str) {
  825. self._dc.send(str);
  826. });
  827. if (self._queue.length === 0) {
  828. clearTimeout(self._timeout);
  829. self._timeout = null;
  830. //self._processAcks();
  831. }
  832. };
  833. // Go through ACKs to send missing pieces.
  834. Reliable.prototype._processAcks = function() {
  835. for (var id in this._outgoing) {
  836. if (this._outgoing.hasOwnProperty(id)) {
  837. this._sendWindowedChunks(id);
  838. }
  839. }
  840. };
  841. // Handle sending a message.
  842. // FIXME: Don't wait for interval time for all messages...
  843. Reliable.prototype._handleSend = function(msg) {
  844. var push = true;
  845. for (var i = 0, ii = this._queue.length; i < ii; i += 1) {
  846. var item = this._queue[i];
  847. if (item === msg) {
  848. push = false;
  849. } else if (item._multiple && item.indexOf(msg) !== -1) {
  850. push = false;
  851. }
  852. }
  853. if (push) {
  854. this._queue.push(msg);
  855. if (!this._timeout) {
  856. this._setupInterval();
  857. }
  858. }
  859. };
  860. // Set up DataChannel handlers.
  861. Reliable.prototype._setupDC = function() {
  862. // Handle various message types.
  863. var self = this;
  864. this._dc.onmessage = function(e) {
  865. var msg = e.data;
  866. var datatype = msg.constructor;
  867. // FIXME: msg is String until binary is supported.
  868. // Once that happens, this will have to be smarter.
  869. if (datatype === String) {
  870. var ab = util.binaryStringToArrayBuffer(msg);
  871. msg = util.unpack(ab);
  872. self._handleMessage(msg);
  873. }
  874. };
  875. };
  876. // Handles an incoming message.
  877. Reliable.prototype._handleMessage = function(msg) {
  878. var id = msg[1];
  879. var idata = this._incoming[id];
  880. var odata = this._outgoing[id];
  881. var data;
  882. switch (msg[0]) {
  883. // No chunking was done.
  884. case 'no':
  885. var message = id;
  886. if (!!message) {
  887. this.onmessage(util.unpack(message));
  888. }
  889. break;
  890. // Reached the end of the message.
  891. case 'end':
  892. data = idata;
  893. // In case end comes first.
  894. this._received[id] = msg[2];
  895. if (!data) {
  896. break;
  897. }
  898. this._ack(id);
  899. break;
  900. case 'ack':
  901. data = odata;
  902. if (!!data) {
  903. var ack = msg[2];
  904. // Take the larger ACK, for out of order messages.
  905. data.ack = Math.max(ack, data.ack);
  906. // Clean up when all chunks are ACKed.
  907. if (data.ack >= data.chunks.length) {
  908. util.log('Time: ', new Date() - data.timer);
  909. delete this._outgoing[id];
  910. } else {
  911. this._processAcks();
  912. }
  913. }
  914. // If !data, just ignore.
  915. break;
  916. // Received a chunk of data.
  917. case 'chunk':
  918. // Create a new entry if none exists.
  919. data = idata;
  920. if (!data) {
  921. var end = this._received[id];
  922. if (end === true) {
  923. break;
  924. }
  925. data = {
  926. ack: ['ack', id, 0],
  927. chunks: []
  928. };
  929. this._incoming[id] = data;
  930. }
  931. var n = msg[2];
  932. var chunk = msg[3];
  933. data.chunks[n] = new Uint8Array(chunk);
  934. // If we get the chunk we're looking for, ACK for next missing.
  935. // Otherwise, ACK the same N again.
  936. if (n === data.ack[2]) {
  937. this._calculateNextAck(id);
  938. }
  939. this._ack(id);
  940. break;
  941. default:
  942. // Shouldn't happen, but would make sense for message to just go
  943. // through as is.
  944. this._handleSend(msg);
  945. break;
  946. }
  947. };
  948. // Chunks BL into smaller messages.
  949. Reliable.prototype._chunk = function(bl) {
  950. var chunks = [];
  951. var size = bl.size;
  952. var start = 0;
  953. while (start < size) {
  954. var end = Math.min(size, start + this._mtu);
  955. var b = bl.slice(start, end);
  956. var chunk = {
  957. payload: b
  958. }
  959. chunks.push(chunk);
  960. start = end;
  961. }
  962. util.log('Created', chunks.length, 'chunks.');
  963. return chunks;
  964. };
  965. // Sends ACK N, expecting Nth blob chunk for message ID.
  966. Reliable.prototype._ack = function(id) {
  967. var ack = this._incoming[id].ack;
  968. // if ack is the end value, then call _complete.
  969. if (this._received[id] === ack[2]) {
  970. this._complete(id);
  971. this._received[id] = true;
  972. }
  973. this._handleSend(ack);
  974. };
  975. // Calculates the next ACK number, given chunks.
  976. Reliable.prototype._calculateNextAck = function(id) {
  977. var data = this._incoming[id];
  978. var chunks = data.chunks;
  979. for (var i = 0, ii = chunks.length; i < ii; i += 1) {
  980. // This chunk is missing!!! Better ACK for it.
  981. if (chunks[i] === undefined) {
  982. data.ack[2] = i;
  983. return;
  984. }
  985. }
  986. data.ack[2] = chunks.length;
  987. };
  988. // Sends the next window of chunks.
  989. Reliable.prototype._sendWindowedChunks = function(id) {
  990. util.log('sendWindowedChunks for: ', id);
  991. var data = this._outgoing[id];
  992. var ch = data.chunks;
  993. var chunks = [];
  994. var limit = Math.min(data.ack + this._window, ch.length);
  995. for (var i = data.ack; i < limit; i += 1) {
  996. if (!ch[i].sent || i === data.ack) {
  997. ch[i].sent = true;
  998. chunks.push(['chunk', id, i, ch[i].payload]);
  999. }
  1000. }
  1001. if (data.ack + this._window >= ch.length) {
  1002. chunks.push(['end', id, ch.length])
  1003. }
  1004. chunks._multiple = true;
  1005. this._handleSend(chunks);
  1006. };
  1007. // Puts together a message from chunks.
  1008. Reliable.prototype._complete = function(id) {
  1009. util.log('Completed called for', id);
  1010. var self = this;
  1011. var chunks = this._incoming[id].chunks;
  1012. var bl = new Blob(chunks);
  1013. util.blobToArrayBuffer(bl, function(ab) {
  1014. self.onmessage(util.unpack(ab));
  1015. });
  1016. delete this._incoming[id];
  1017. };
  1018. // Ups bandwidth limit on SDP. Meant to be called during offer/answer.
  1019. Reliable.higherBandwidthSDP = function(sdp) {
  1020. // AS stands for Application-Specific Maximum.
  1021. // Bandwidth number is in kilobits / sec.
  1022. // See RFC for more info: http://www.ietf.org/rfc/rfc2327.txt
  1023. var parts = sdp.split('b=AS:30');
  1024. var replace = 'b=AS:102400'; // 100 Mbps
  1025. return parts[0] + replace + parts[1];
  1026. };
  1027. // Overwritten, typically.
  1028. Reliable.prototype.onmessage = function(msg) {};
  1029. exports.Reliable = Reliable;
  1030. if (window.mozRTCPeerConnection) {
  1031. util.browserisms = 'Firefox';
  1032. } else if (window.webkitRTCPeerConnection) {
  1033. util.browserisms = 'Webkit';
  1034. } else {
  1035. util.browserisms = 'Unknown';
  1036. }
  1037. exports.RTCSessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
  1038. exports.RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection || window.RTCPeerConnection;
  1039. /**
  1040. * A peer who can initiate connections with other peers.
  1041. */
  1042. function Peer(id, options) {
  1043. if (id && id.constructor == Object) {
  1044. options = id;
  1045. id = undefined;
  1046. }
  1047. if (!(this instanceof Peer)) return new Peer(id, options);
  1048. EventEmitter.call(this);
  1049. options = util.extend({
  1050. debug: false,
  1051. host: '0.peerjs.com',
  1052. port: 9000,
  1053. key: 'peerjs',
  1054. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  1055. }, options);
  1056. this._options = options;
  1057. util.debug = options.debug;
  1058. // First check if browser can use PeerConnection/DataChannels.
  1059. // TODO: when media is supported, lower browser version limit and move DC
  1060. // check to where`connect` is called.
  1061. var self = this;
  1062. if (!util.isBrowserCompatible()) {
  1063. util.setZeroTimeout(function() {
  1064. self._abort('browser-incompatible', 'The current browser does not support WebRTC DataChannels');
  1065. });
  1066. return;
  1067. }
  1068. // Detect relative URL host.
  1069. if (options.host === '/') {
  1070. options.host = window.location.hostname;
  1071. }
  1072. // Ensure alphanumeric_-
  1073. if (id && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id)) {
  1074. util.setZeroTimeout(function() {
  1075. self._abort('invalid-id', 'ID "' + id + '" is invalid');
  1076. });
  1077. return;
  1078. }
  1079. if (options.key && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(options.key)) {
  1080. util.setZeroTimeout(function() {
  1081. self._abort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  1082. });
  1083. return;
  1084. }
  1085. this._secure = util.isSecure();
  1086. // Errors for now because no support for SSL on cloud server.
  1087. if (this._secure && options.host === '0.peerjs.com') {
  1088. util.setZeroTimeout(function() {
  1089. self._abort('ssl-unavailable',
  1090. 'The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS.');
  1091. });
  1092. return;
  1093. }
  1094. // States.
  1095. this.destroyed = false;
  1096. this.disconnected = false;
  1097. // Connections for this peer.
  1098. this.connections = {};
  1099. // Connection managers.
  1100. this.managers = {};
  1101. // Queued connections to make.
  1102. this._queued = [];
  1103. // Init immediately if ID is given, otherwise ask server for ID
  1104. if (id) {
  1105. this.id = id;
  1106. this._init();
  1107. } else {
  1108. this.id = null;
  1109. this._retrieveId();
  1110. }
  1111. };
  1112. util.inherits(Peer, EventEmitter);
  1113. Peer.prototype._retrieveId = function(cb) {
  1114. var self = this;
  1115. try {
  1116. var http = new XMLHttpRequest();
  1117. var protocol = this._secure ? 'https://' : 'http://';
  1118. var url = protocol + this._options.host + ':' + this._options.port + '/' + this._options.key + '/id';
  1119. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  1120. url += queryString;
  1121. // If there's no ID we need to wait for one before trying to init socket.
  1122. http.open('get', url, true);
  1123. http.onreadystatechange = function() {
  1124. if (http.readyState === 4) {
  1125. if (http.status !== 200) {
  1126. throw 'Retrieve id response not 200';
  1127. return;
  1128. }
  1129. self.id = http.responseText;
  1130. self._init();
  1131. }
  1132. };
  1133. http.send(null);
  1134. } catch(e) {
  1135. this._abort('server-error', 'Could not get an ID from the server');
  1136. }
  1137. };
  1138. Peer.prototype._init = function() {
  1139. var self = this;
  1140. this._socket = new Socket(this._options.host, this._options.port, this._options.key, this.id);
  1141. this._socket.on('message', function(data) {
  1142. self._handleServerJSONMessage(data);
  1143. });
  1144. this._socket.on('error', function(error) {
  1145. util.log(error);
  1146. self._abort('socket-error', error);
  1147. });
  1148. this._socket.on('close', function() {
  1149. var msg = 'Underlying socket has closed';
  1150. util.log('error', msg);
  1151. self._abort('socket-closed', msg);
  1152. });
  1153. this._socket.start();
  1154. }
  1155. Peer.prototype._handleServerJSONMessage = function(message) {
  1156. var peer = message.src;
  1157. var manager = this.managers[peer];
  1158. var payload = message.payload;
  1159. switch (message.type) {
  1160. case 'OPEN':
  1161. this._processQueue();
  1162. this.emit('open', this.id);
  1163. break;
  1164. case 'ERROR':
  1165. this._abort('server-error', payload.msg);
  1166. break;
  1167. case 'ID-TAKEN':
  1168. this._abort('unavailable-id', 'ID `'+this.id+'` is taken');
  1169. break;
  1170. case 'OFFER':
  1171. var options = {
  1172. sdp: payload.sdp,
  1173. labels: payload.labels,
  1174. config: this._options.config
  1175. };
  1176. var manager = this.managers[peer];
  1177. if (!manager) {
  1178. manager = new ConnectionManager(this.id, peer, this._socket, options);
  1179. this._attachManagerListeners(manager);
  1180. this.managers[peer] = manager;
  1181. this.connections[peer] = manager.connections;
  1182. }
  1183. manager.update(options.labels);
  1184. manager.handleSDP(payload.sdp, message.type);
  1185. break;
  1186. case 'EXPIRE':
  1187. if (manager) {
  1188. manager.close();
  1189. manager.emit('error', new Error('Could not connect to peer ' + manager.peer));
  1190. }
  1191. break;
  1192. case 'ANSWER':
  1193. if (manager) {
  1194. manager.handleSDP(payload.sdp, message.type);
  1195. }
  1196. break;
  1197. case 'CANDIDATE':
  1198. if (manager) {
  1199. manager.handleCandidate(payload);
  1200. }
  1201. break;
  1202. case 'LEAVE':
  1203. if (manager) {
  1204. manager.handleLeave();
  1205. }
  1206. break;
  1207. case 'INVALID-KEY':
  1208. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  1209. break;
  1210. default:
  1211. util.log('Unrecognized message type:', message.type);
  1212. break;
  1213. }
  1214. };
  1215. /** Process queued calls to connect. */
  1216. Peer.prototype._processQueue = function() {
  1217. while (this._queued.length > 0) {
  1218. var manager = this._queued.pop();
  1219. manager.initialize(this.id, this._socket);
  1220. }
  1221. };
  1222. /** Listeners for manager. */
  1223. Peer.prototype._attachManagerListeners = function(manager) {
  1224. var self = this;
  1225. // Handle receiving a connection.
  1226. manager.on('connection', function(connection) {
  1227. self.emit('connection', connection);
  1228. });
  1229. // Handle a connection closing.
  1230. manager.on('close', function() {
  1231. if (!!self.managers[manager.peer]) {
  1232. delete self.managers[manager.peer];
  1233. delete self.connections[manager.peer];
  1234. }
  1235. });
  1236. manager.on('error', function(err) {
  1237. self.emit('error', err);
  1238. });
  1239. };
  1240. /** Destroys the Peer and emits an error message. */
  1241. Peer.prototype._abort = function(type, message) {
  1242. util.log('Aborting. Error:', message);
  1243. var err = new Error(message);
  1244. err.type = type;
  1245. this.destroy();
  1246. this.emit('error', err);
  1247. };
  1248. Peer.prototype._cleanup = function() {
  1249. var self = this;
  1250. if (!!this.managers) {
  1251. var peers = Object.keys(this.managers);
  1252. for (var i = 0, ii = peers.length; i < ii; i++) {
  1253. this.managers[peers[i]].close();
  1254. }
  1255. }
  1256. util.setZeroTimeout(function(){
  1257. self.disconnect();
  1258. });
  1259. this.emit('close');
  1260. };
  1261. /** Exposed connect function for users. Will try to connect later if user
  1262. * is waiting for an ID. */
  1263. Peer.prototype.connect = function(peer, options) {
  1264. if (this.disconnected) {
  1265. var err = new Error('This Peer has been disconnected from the server and can no longer make connections.');
  1266. err.type = 'server-disconnected';
  1267. this.emit('error', err);
  1268. return;
  1269. }
  1270. options = util.extend({
  1271. config: this._options.config
  1272. }, options);
  1273. var manager = this.managers[peer];
  1274. // Firefox currently does not support multiplexing once an offer is made.
  1275. if (util.browserisms === 'Firefox' && !!manager && manager.firefoxSingular) {
  1276. var err = new Error('Firefox currently does not support multiplexing after a DataChannel has already been established');
  1277. err.type = 'firefoxism';
  1278. this.emit('error', err);
  1279. return;
  1280. }
  1281. if (!manager) {
  1282. manager = new ConnectionManager(this.id, peer, this._socket, options);
  1283. this._attachManagerListeners(manager);
  1284. this.managers[peer] = manager;
  1285. this.connections[peer] = manager.connections;
  1286. }
  1287. var connection = manager.connect(options);
  1288. if (!this.id) {
  1289. this._queued.push(manager);
  1290. }
  1291. return connection;
  1292. };
  1293. /**
  1294. * Return the peer id or null, if there's no id at the moment.
  1295. * Reasons for no id could be 'connect in progress' or 'disconnected'
  1296. */
  1297. Peer.prototype.getId = function() {
  1298. return this.id;
  1299. };
  1300. /**
  1301. * Destroys the Peer: closes all active connections as well as the connection
  1302. * to the server.
  1303. * Warning: The peer can no longer create or accept connections after being
  1304. * destroyed.
  1305. */
  1306. Peer.prototype.destroy = function() {
  1307. if (!this.destroyed) {
  1308. this._cleanup();
  1309. this.destroyed = true;
  1310. }
  1311. };
  1312. /**
  1313. * Disconnects the Peer's connection to the PeerServer. Does not close any
  1314. * active connections.
  1315. * Warning: The peer can no longer create or accept connections after being
  1316. * disconnected. It also cannot reconnect to the server.
  1317. */
  1318. Peer.prototype.disconnect = function() {
  1319. if (!this.disconnected) {
  1320. if (!!this._socket) {
  1321. this._socket.close();
  1322. }
  1323. this.id = null;
  1324. this.disconnected = true;
  1325. }
  1326. };
  1327. /** The current browser. */
  1328. Peer.browser = util.browserisms;
  1329. /**
  1330. * Provides a clean method for checking if there's an active connection to the
  1331. * peer server.
  1332. */
  1333. Peer.prototype.isConnected = function() {
  1334. return !this.disconnected;
  1335. };
  1336. /**
  1337. * Returns true if this peer is destroyed and can no longer be used.
  1338. */
  1339. Peer.prototype.isDestroyed = function() {
  1340. return this.destroyed;
  1341. };
  1342. exports.Peer = Peer;
  1343. /**
  1344. * Wraps a DataChannel between two Peers.
  1345. */
  1346. function DataConnection(peer, dc, options) {
  1347. if (!(this instanceof DataConnection)) return new DataConnection(peer, dc, options);
  1348. EventEmitter.call(this);
  1349. options = util.extend({
  1350. serialization: 'binary'
  1351. }, options);
  1352. // Connection is not open yet.
  1353. this.open = false;
  1354. this.label = options.label;
  1355. this.metadata = options.metadata;
  1356. this.serialization = options.serialization;
  1357. this.peer = peer;
  1358. this.reliable = options.reliable;
  1359. this._dc = dc;
  1360. if (!!this._dc) {
  1361. this._configureDataChannel();
  1362. }
  1363. };
  1364. util.inherits(DataConnection, EventEmitter);
  1365. DataConnection.prototype._configureDataChannel = function() {
  1366. var self = this;
  1367. if (util.browserisms !== 'Webkit') {
  1368. // Webkit doesn't support binary yet
  1369. this._dc.binaryType = 'arraybuffer';
  1370. }
  1371. this._dc.onopen = function() {
  1372. util.log('Data channel connection success');
  1373. self.open = true;
  1374. self.emit('open');
  1375. };
  1376. // Use the Reliable shim for non Firefox browsers
  1377. if (this.reliable && util.browserisms !== 'Firefox') {
  1378. this._reliable = new Reliable(this._dc, util.debug);
  1379. }
  1380. if (this._reliable) {
  1381. this._reliable.onmessage = function(msg) {
  1382. self.emit('data', msg);
  1383. };
  1384. } else {
  1385. this._dc.onmessage = function(e) {
  1386. self._handleDataMessage(e);
  1387. };
  1388. }
  1389. this._dc.onclose = function(e) {
  1390. util.log('DataChannel closed.');
  1391. self.close();
  1392. };
  1393. };
  1394. DataConnection.prototype._cleanup = function() {
  1395. if (!!this._dc && this._dc.readyState !== 'closed') {
  1396. this._dc.close();
  1397. this._dc = null;
  1398. }
  1399. this.open = false;
  1400. this.emit('close');
  1401. };
  1402. // Handles a DataChannel message.
  1403. DataConnection.prototype._handleDataMessage = function(e) {
  1404. var self = this;
  1405. var data = e.data;
  1406. var datatype = data.constructor;
  1407. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  1408. if (datatype === Blob) {
  1409. // Datatype should never be blob
  1410. util.blobToArrayBuffer(data, function(ab) {
  1411. data = util.unpack(ab);
  1412. self.emit('data', data);
  1413. });
  1414. return;
  1415. } else if (datatype === ArrayBuffer) {
  1416. data = util.unpack(data);
  1417. } else if (datatype === String) {
  1418. // String fallback for binary data for browsers that don't support binary yet
  1419. var ab = util.binaryStringToArrayBuffer(data);
  1420. data = util.unpack(ab);
  1421. }
  1422. } else if (this.serialization === 'json') {
  1423. data = JSON.parse(data);
  1424. }
  1425. this.emit('data', data);
  1426. };
  1427. DataConnection.prototype.addDC = function(dc) {
  1428. this._dc = dc;
  1429. this._configureDataChannel();
  1430. };
  1431. /**
  1432. * Exposed functionality for users.
  1433. */
  1434. /** Allows user to close connection. */
  1435. DataConnection.prototype.close = function() {
  1436. if (!this.open) {
  1437. return;
  1438. }
  1439. this._cleanup();
  1440. };
  1441. /** Allows user to send data. */
  1442. DataConnection.prototype.send = function(data) {
  1443. if (!this.open) {
  1444. this.emit('error', new Error('Connection no longer open.'));
  1445. }
  1446. if (this._reliable) {
  1447. // Note: reliable sending will make it so that you cannot customize
  1448. // serialization.
  1449. this._reliable.send(data);
  1450. return;
  1451. }
  1452. var self = this;
  1453. if (this.serialization === 'none') {
  1454. this._dc.send(data);
  1455. } else if (this.serialization === 'json') {
  1456. this._dc.send(JSON.stringify(data));
  1457. } else {
  1458. var utf8 = (this.serialization === 'binary-utf8');
  1459. var blob = util.pack(data, utf8);
  1460. // DataChannel currently only supports strings.
  1461. if (util.browserisms === 'Webkit') {
  1462. util.blobToBinaryString(blob, function(str){
  1463. self._dc.send(str);
  1464. });
  1465. } else {
  1466. this._dc.send(blob);
  1467. }
  1468. }
  1469. };
  1470. /**
  1471. * Returns true if the DataConnection is open and able to send messages.
  1472. */
  1473. DataConnection.prototype.isOpen = function() {
  1474. return this.open;
  1475. };
  1476. /**
  1477. * Gets the metadata associated with this DataConnection.
  1478. */
  1479. DataConnection.prototype.getMetadata = function() {
  1480. return this.metadata;
  1481. };
  1482. /**
  1483. * Gets the label associated with this DataConnection.
  1484. */
  1485. DataConnection.prototype.getLabel = function() {
  1486. return this.label;
  1487. };
  1488. /**
  1489. * Gets the brokering ID of the peer that you are connected with.
  1490. * Note that this ID may be out of date if the peer has disconnected from the
  1491. * server, so it's not recommended that you use this ID to identify this
  1492. * connection.
  1493. */
  1494. DataConnection.prototype.getPeer = function() {
  1495. return this.peer;
  1496. };
  1497. /**
  1498. * Manages DataConnections between its peer and one other peer.
  1499. * Internally, manages PeerConnection.
  1500. */
  1501. function ConnectionManager(id, peer, socket, options) {
  1502. if (!(this instanceof ConnectionManager)) return new ConnectionManager(id, peer, socket, options);
  1503. EventEmitter.call(this);
  1504. options = util.extend({
  1505. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  1506. }, options);
  1507. this._options = options;
  1508. // PeerConnection is not yet dead.
  1509. this.open = true;
  1510. this.id = id;
  1511. this.peer = peer;
  1512. this.pc = null;
  1513. // Mapping labels to metadata and serialization.
  1514. // label => { metadata: ..., serialization: ..., reliable: ...}
  1515. this.labels = {};
  1516. // A default label in the event that none are passed in.
  1517. this._default = 0;
  1518. // DataConnections on this PC.
  1519. this.connections = {};
  1520. this._queued = [];
  1521. this._socket = socket;
  1522. if (!!this.id) {
  1523. this.initialize();
  1524. }
  1525. };
  1526. util.inherits(ConnectionManager, EventEmitter);
  1527. ConnectionManager.prototype.initialize = function(id, socket) {
  1528. if (!!id) {
  1529. this.id = id;
  1530. }
  1531. if (!!socket) {
  1532. this._socket = socket;
  1533. }
  1534. // Set up PeerConnection.
  1535. this._startPeerConnection();
  1536. // Process queued DCs.
  1537. this._processQueue();
  1538. // Listen for ICE candidates.
  1539. this._setupIce();
  1540. // Listen for negotiation needed.
  1541. // Chrome only **
  1542. this._setupNegotiationHandler();
  1543. // Listen for data channel.
  1544. this._setupDataChannel();
  1545. this.initialize = function() { };
  1546. };
  1547. /** Start a PC. */
  1548. ConnectionManager.prototype._startPeerConnection = function() {
  1549. util.log('Creating RTCPeerConnection');
  1550. this.pc = new RTCPeerConnection(this._options.config, { optional: [ { RtpDataChannels: true } ]});
  1551. };
  1552. /** Add DataChannels to all queued DataConnections. */
  1553. ConnectionManager.prototype._processQueue = function() {
  1554. var conn = this._queued.pop();
  1555. if (!!conn) {
  1556. var reliable = util.browserisms === 'Firefox' ? conn.reliable : false;
  1557. conn.addDC(this.pc.createDataChannel(conn.label, { reliable: reliable }));
  1558. }
  1559. };
  1560. /** Set up ICE candidate handlers. */
  1561. ConnectionManager.prototype._setupIce = function() {
  1562. util.log('Listening for ICE candidates.');
  1563. var self = this;
  1564. this.pc.onicecandidate = function(evt) {
  1565. if (evt.candidate) {
  1566. util.log('Received ICE candidates.');
  1567. self._socket.send({
  1568. type: 'CANDIDATE',
  1569. payload: {
  1570. candidate: evt.candidate
  1571. },
  1572. dst: self.peer
  1573. });
  1574. }
  1575. };
  1576. this.pc.oniceconnectionstatechange = function() {
  1577. if (!!self.pc && self.pc.iceConnectionState === 'disconnected') {
  1578. util.log('iceConnectionState is disconnected, closing connections to ' + this.peer);
  1579. self.close();
  1580. }
  1581. };
  1582. // Fallback for older Chrome impls.
  1583. this.pc.onicechange = function() {
  1584. if (!!self.pc && self.pc.iceConnectionState === 'disconnected') {
  1585. util.log('iceConnectionState is disconnected, closing connections to ' + this.peer);
  1586. self.close();
  1587. }
  1588. };
  1589. };
  1590. /** Set up onnegotiationneeded. */
  1591. ConnectionManager.prototype._setupNegotiationHandler = function() {
  1592. var self = this;
  1593. util.log('Listening for `negotiationneeded`');
  1594. this.pc.onnegotiationneeded = function() {
  1595. util.log('`negotiationneeded` triggered');
  1596. self._makeOffer();
  1597. };
  1598. };
  1599. /** Set up Data Channel listener. */
  1600. ConnectionManager.prototype._setupDataChannel = function() {
  1601. var self = this;
  1602. util.log('Listening for data channel');
  1603. this.pc.ondatachannel = function(evt) {
  1604. util.log('Received data channel');
  1605. var dc = evt.channel;
  1606. var label = dc.label;
  1607. // This should not be empty.
  1608. var options = self.labels[label] || {};
  1609. var connection = new DataConnection(self.peer, dc, options);
  1610. self._attachConnectionListeners(connection);
  1611. self.connections[label] = connection;
  1612. self.emit('connection', connection);
  1613. };
  1614. };
  1615. /** Send an offer. */
  1616. ConnectionManager.prototype._makeOffer = function() {
  1617. var self = this;
  1618. this.pc.createOffer(function(offer) {
  1619. util.log('Created offer.');
  1620. // Firefox currently does not support multiplexing once an offer is made.
  1621. self.firefoxSingular = true;
  1622. if (util.browserisms === 'Webkit') {
  1623. offer.sdp = Reliable.higherBandwidthSDP(offer.sdp);
  1624. }
  1625. self.pc.setLocalDescription(offer, function() {
  1626. util.log('Set localDescription to offer');
  1627. self._socket.send({
  1628. type: 'OFFER',
  1629. payload: {
  1630. sdp: offer,
  1631. config: self._options.config,
  1632. labels: self.labels
  1633. },
  1634. dst: self.peer
  1635. });
  1636. // We can now reset labels because all info has been communicated.
  1637. self.labels = {};
  1638. }, function(err) {
  1639. self.emit('error', err);
  1640. util.log('Failed to setLocalDescription, ', err);
  1641. });
  1642. });
  1643. };
  1644. /** Create an answer for PC. */
  1645. ConnectionManager.prototype._makeAnswer = function() {
  1646. var self = this;
  1647. this.pc.createAnswer(function(answer) {
  1648. util.log('Created answer.');
  1649. if (util.browserisms === 'Webkit') {
  1650. answer.sdp = Reliable.higherBandwidthSDP(answer.sdp);
  1651. }
  1652. self.pc.setLocalDescription(answer, function() {
  1653. util.log('Set localDescription to answer.');
  1654. self._socket.send({
  1655. type: 'ANSWER',
  1656. payload: {
  1657. sdp: answer
  1658. },
  1659. dst: self.peer
  1660. });
  1661. }, function(err) {
  1662. self.emit('error', err);
  1663. util.log('Failed to setLocalDescription, ', err);
  1664. });
  1665. }, function(err) {
  1666. self.emit('error', err);
  1667. util.log('Failed to create answer, ', err);
  1668. });
  1669. };
  1670. /** Clean up PC, close related DCs. */
  1671. ConnectionManager.prototype._cleanup = function() {
  1672. util.log('Cleanup ConnectionManager for ' + this.peer);
  1673. if (!!this.pc && (this.pc.readyState !== 'closed' || this.pc.signalingState !== 'closed')) {
  1674. this.pc.close();
  1675. this.pc = null;
  1676. }
  1677. var self = this;
  1678. this._socket.send({
  1679. type: 'LEAVE',
  1680. dst: self.peer
  1681. });
  1682. this.open = false;
  1683. this.emit('close');
  1684. };
  1685. /** Attach connection listeners. */
  1686. ConnectionManager.prototype._attachConnectionListeners = function(connection) {
  1687. var self = this;
  1688. connection.on('close', function() {
  1689. if (!!self.connections[connection.label]) {
  1690. delete self.connections[connection.label];
  1691. }
  1692. if (!Object.keys(self.connections).length) {
  1693. self._cleanup();
  1694. }
  1695. });
  1696. connection.on('open', function() {
  1697. self._lock = false;
  1698. self._processQueue();
  1699. });
  1700. };
  1701. /** Handle an SDP. */
  1702. ConnectionManager.prototype.handleSDP = function(sdp, type) {
  1703. sdp = new RTCSessionDescription(sdp);
  1704. var self = this;
  1705. this.pc.setRemoteDescription(sdp, function() {
  1706. util.log('Set remoteDescription: ' + type);
  1707. if (type === 'OFFER') {
  1708. self._makeAnswer();
  1709. }
  1710. }, function(err) {
  1711. self.emit('error', err);
  1712. util.log('Failed to setRemoteDescription, ', err);
  1713. });
  1714. };
  1715. /** Handle a candidate. */
  1716. ConnectionManager.prototype.handleCandidate = function(message) {
  1717. var candidate = new RTCIceCandidate(message.candidate);
  1718. this.pc.addIceCandidate(candidate);
  1719. util.log('Added ICE candidate.');
  1720. };
  1721. /** Handle peer leaving. */
  1722. ConnectionManager.prototype.handleLeave = function() {
  1723. util.log('Peer ' + this.peer + ' disconnected.');
  1724. this.close();
  1725. };
  1726. /** Closes manager and all related connections. */
  1727. ConnectionManager.prototype.close = function() {
  1728. if (!this.open) {
  1729. this.emit('error', new Error('Connections to ' + this.peer + 'are already closed.'));
  1730. return;
  1731. }
  1732. var labels = Object.keys(this.connections);
  1733. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  1734. var label = labels[i];
  1735. var connection = this.connections[label];
  1736. connection.close();
  1737. }
  1738. this.connections = null;
  1739. this._cleanup();
  1740. };
  1741. /** Create and returns a DataConnection with the peer with the given label. */
  1742. ConnectionManager.prototype.connect = function(options) {
  1743. if (!this.open) {
  1744. return;
  1745. }
  1746. options = util.extend({
  1747. label: 'peerjs',
  1748. reliable: (util.browserisms === 'Firefox')
  1749. }, options);
  1750. // Check if label is taken...if so, generate a new label randomly.
  1751. while (!!this.connections[options.label]) {
  1752. options.label = 'peerjs' + this._default;
  1753. this._default += 1;
  1754. }
  1755. this.labels[options.label] = options;
  1756. var dc;
  1757. if (!!this.pc && !this._lock) {
  1758. var reliable = util.browserisms === 'Firefox' ? options.reliable : false;
  1759. dc = this.pc.createDataChannel(options.label, { reliable: reliable });
  1760. if (util.browserisms === 'Firefox') {
  1761. this._makeOffer();
  1762. }
  1763. }
  1764. var connection = new DataConnection(this.peer, dc, options);
  1765. this._attachConnectionListeners(connection);
  1766. this.connections[options.label] = connection;
  1767. if (!this.pc || this._lock) {
  1768. this._queued.push(connection);
  1769. }
  1770. this._lock = true
  1771. return connection;
  1772. };
  1773. /** Updates label:[serialization, reliable, metadata] pairs from offer. */
  1774. ConnectionManager.prototype.update = function(updates) {
  1775. var labels = Object.keys(updates);
  1776. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  1777. var label = labels[i];
  1778. this.labels[label] = updates[label];
  1779. }
  1780. };
  1781. /**
  1782. * An abstraction on top of WebSockets and XHR streaming to provide fastest
  1783. * possible connection for peers.
  1784. */
  1785. function Socket(host, port, key, id) {
  1786. if (!(this instanceof Socket)) return new Socket(host, port, key, id);
  1787. EventEmitter.call(this);
  1788. this._id = id;
  1789. var token = util.randomToken();
  1790. this.disconnected = false;
  1791. var secure = util.isSecure();
  1792. var protocol = secure ? 'https://' : 'http://';
  1793. var wsProtocol = secure ? 'wss://' : 'ws://';
  1794. this._httpUrl = protocol + host + ':' + port + '/' + key + '/' + id + '/' + token;
  1795. this._wsUrl = wsProtocol + host + ':' + port + '/peerjs?key='+key+'&id='+id+'&token='+token;
  1796. };
  1797. util.inherits(Socket, EventEmitter);
  1798. /** Check in with ID or get one from server. */
  1799. Socket.prototype.start = function() {
  1800. this._startXhrStream();
  1801. this._startWebSocket();
  1802. };
  1803. /** Start up websocket communications. */
  1804. Socket.prototype._startWebSocket = function() {
  1805. var self = this;
  1806. if (!!this._socket) {
  1807. return;
  1808. }
  1809. this._socket = new WebSocket(this._wsUrl);
  1810. this._socket.onmessage = function(event) {
  1811. var data;
  1812. try {
  1813. data = JSON.parse(event.data);
  1814. } catch(e) {
  1815. util.log('Invalid server message', event.data);
  1816. return;
  1817. }
  1818. self.emit('message', data);
  1819. };
  1820. // Take care of the queue of connections if necessary and make sure Peer knows
  1821. // socket is open.
  1822. this._socket.onopen = function() {
  1823. if (!!self._timeout) {
  1824. clearTimeout(self._timeout);
  1825. setTimeout(function(){
  1826. self._http.abort();
  1827. self._http = null;
  1828. }, 5000);
  1829. }
  1830. util.log('Socket open');
  1831. };
  1832. };
  1833. /** Start XHR streaming. */
  1834. Socket.prototype._startXhrStream = function(n) {
  1835. try {
  1836. var self = this;
  1837. this._http = new XMLHttpRequest();
  1838. this._http._index = 1;
  1839. this._http._streamIndex = n || 0;
  1840. this._http.open('post', this._httpUrl + '/id?i=' + this._http._streamIndex, true);
  1841. this._http.onreadystatechange = function() {
  1842. if (this.readyState == 2 && !!this.old) {
  1843. this.old.abort();
  1844. delete this.old;
  1845. }
  1846. if (this.readyState > 2 && this.status == 200 && !!this.responseText) {
  1847. self._handleStream(this);
  1848. }
  1849. };
  1850. this._http.send(null);
  1851. this._setHTTPTimeout();
  1852. } catch(e) {
  1853. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  1854. }
  1855. };
  1856. /** Handles onreadystatechange response as a stream. */
  1857. Socket.prototype._handleStream = function(http) {
  1858. // 3 and 4 are loading/done state. All others are not relevant.
  1859. var messages = http.responseText.split('\n');
  1860. // Check to see if anything needs to be processed on buffer.
  1861. if (!!http._buffer) {
  1862. while (http._buffer.length > 0) {
  1863. var index = http._buffer.shift();
  1864. var bufferedMessage = messages[index];
  1865. try {
  1866. bufferedMessage = JSON.parse(bufferedMessage);
  1867. } catch(e) {
  1868. http._buffer.shift(index);
  1869. break;
  1870. }
  1871. this.emit('message', bufferedMessage);
  1872. }
  1873. }
  1874. var message = messages[http._index];
  1875. if (!!message) {
  1876. http._index += 1;
  1877. // Buffering--this message is incomplete and we'll get to it next time.
  1878. // This checks if the httpResponse ended in a `\n`, in which case the last
  1879. // element of messages should be the empty string.
  1880. if (http._index === messages.length) {
  1881. if (!http._buffer) {
  1882. http._buffer = [];
  1883. }
  1884. http._buffer.push(http._index - 1);
  1885. } else {
  1886. try {
  1887. message = JSON.parse(message);
  1888. } catch(e) {
  1889. util.log('Invalid server message', message);
  1890. return;
  1891. }
  1892. this.emit('message', message);
  1893. }
  1894. }
  1895. };
  1896. Socket.prototype._setHTTPTimeout = function() {
  1897. var self = this;
  1898. this._timeout = setTimeout(function() {
  1899. var old = self._http;
  1900. if (!self._wsOpen()) {
  1901. self._startXhrStream(old._streamIndex + 1);
  1902. self._http.old = old;
  1903. } else {
  1904. old.abort();
  1905. }
  1906. }, 25000);
  1907. };
  1908. Socket.prototype._wsOpen = function() {
  1909. return !!this._socket && this._socket.readyState == 1;
  1910. };
  1911. /** Exposed send for DC & Peer. */
  1912. Socket.prototype.send = function(data) {
  1913. if (this.disconnected) {
  1914. return;
  1915. }
  1916. if (!data.type) {
  1917. this.emit('error', 'Invalid message');
  1918. return;
  1919. }
  1920. var message = JSON.stringify(data);
  1921. if (this._wsOpen()) {
  1922. this._socket.send(message);
  1923. } else {
  1924. var http = new XMLHttpRequest();
  1925. var url = this._httpUrl + '/' + data.type.toLowerCase();
  1926. http.open('post', url, true);
  1927. http.setRequestHeader('Content-Type', 'application/json');
  1928. http.send(message);
  1929. }
  1930. };
  1931. Socket.prototype.close = function() {
  1932. if (!this.disconnected && this._wsOpen()) {
  1933. this._socket.close();
  1934. this.disconnected = true;
  1935. }
  1936. };
  1937. })(this);