peer.js 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150
  1. /*! peerjs.js build:0.2.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, 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: false,
  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. randomPort: function() {
  674. return Math.round(Math.random() * 60535) + 5000;
  675. },
  676. log: function () {
  677. if (util.debug) {
  678. var err = false;
  679. var copy = Array.prototype.slice.call(arguments);
  680. copy.unshift('PeerJS: ');
  681. for (var i = 0, l = copy.length; i < l; i++){
  682. if (copy[i] instanceof Error) {
  683. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  684. err = true;
  685. }
  686. }
  687. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  688. }
  689. },
  690. setZeroTimeout: (function(global) {
  691. var timeouts = [];
  692. var messageName = 'zero-timeout-message';
  693. // Like setTimeout, but only takes a function argument. There's
  694. // no time argument (always zero) and no arguments (you have to
  695. // use a closure).
  696. function setZeroTimeoutPostMessage(fn) {
  697. timeouts.push(fn);
  698. global.postMessage(messageName, '*');
  699. }
  700. function handleMessage(event) {
  701. if (event.source == global && event.data == messageName) {
  702. if (event.stopPropagation) {
  703. event.stopPropagation();
  704. }
  705. if (timeouts.length) {
  706. timeouts.shift()();
  707. }
  708. }
  709. }
  710. if (global.addEventListener) {
  711. global.addEventListener('message', handleMessage, true);
  712. } else if (global.attachEvent) {
  713. global.attachEvent('onmessage', handleMessage);
  714. }
  715. return setZeroTimeoutPostMessage;
  716. }(this)),
  717. blobToArrayBuffer: function(blob, cb){
  718. var fr = new FileReader();
  719. fr.onload = function(evt) {
  720. cb(evt.target.result);
  721. };
  722. fr.readAsArrayBuffer(blob);
  723. },
  724. blobToBinaryString: function(blob, cb){
  725. var fr = new FileReader();
  726. fr.onload = function(evt) {
  727. cb(evt.target.result);
  728. };
  729. fr.readAsBinaryString(blob);
  730. },
  731. binaryStringToArrayBuffer: function(binary) {
  732. var byteArray = new Uint8Array(binary.length);
  733. for (var i = 0; i < binary.length; i++) {
  734. byteArray[i] = binary.charCodeAt(i) & 0xff;
  735. }
  736. return byteArray.buffer;
  737. },
  738. randomToken: function () {
  739. return Math.random().toString(36).substr(2);
  740. },
  741. isBrowserCompatible: function() {
  742. var c, f;
  743. if (this.chromeCompatible) {
  744. if ((c = navigator.userAgent.split('Chrome/')) && c.length > 1) {
  745. // Get version #.
  746. var v = c[1].split('.')[0];
  747. return parseInt(v) >= this.chromeVersion;
  748. }
  749. }
  750. if (this.firefoxCompatible) {
  751. if ((f = navigator.userAgent.split('Firefox/')) && f.length > 1) {
  752. // Get version #.
  753. var v = f[1].split('.')[0];
  754. return parseInt(v) >= this.firefoxVersion;
  755. }
  756. }
  757. return false;
  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 = 10;
  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. // Overwritten, typically.
  806. Reliable.prototype.onmessage = function(msg) {};
  807. // Set up interval for processing queue.
  808. Reliable.prototype._setupInterval = function() {
  809. var self = this;
  810. this._timeout = setInterval(function() {
  811. // FIXME: String stuff makes things terribly async.
  812. var msg = self._queue.shift();
  813. if (msg._multiple) {
  814. for (var i = 0, ii = msg.length; i < ii; i += 1) {
  815. self._intervalSend(msg[i]);
  816. }
  817. } else {
  818. self._intervalSend(msg);
  819. }
  820. }, this._interval);
  821. };
  822. Reliable.prototype._intervalSend = function(msg) {
  823. var self = this;
  824. util.log('Sending...', msg);
  825. msg = util.pack(msg);
  826. util.blobToBinaryString(msg, function(str) {
  827. self._dc.send(str);
  828. });
  829. if (self._queue.length === 0) {
  830. clearTimeout(self._timeout);
  831. self._timeout = null;
  832. self._processAcks();
  833. }
  834. };
  835. // Go through ACKs to send missing pieces.
  836. Reliable.prototype._processAcks = function() {
  837. // processAcks
  838. for (var id in this._outgoing) {
  839. if (this._outgoing.hasOwnProperty(id)) {
  840. this._sendWindowedChunks(id);
  841. }
  842. }
  843. };
  844. // Handle sending a message.
  845. // FIXME: Don't wait for interval time for all messages...
  846. Reliable.prototype._handleSend = function(msg) {
  847. var push = true;
  848. for (var i = 0, ii = this._queue.length; i < ii; i += 1) {
  849. var item = this._queue[i];
  850. if (item === msg) {
  851. push = false;
  852. } else if (item._multiple && item.indexOf(msg) !== -1) {
  853. push = false;
  854. }
  855. }
  856. if (push) {
  857. this._queue.push(msg);
  858. if (!this._timeout) {
  859. this._setupInterval();
  860. }
  861. }
  862. };
  863. // Set up DataChannel handlers.
  864. Reliable.prototype._setupDC = function() {
  865. // Handle various message types.
  866. var self = this;
  867. this._dc.onmessage = function(e) {
  868. var msg = e.data;
  869. var datatype = msg.constructor;
  870. // FIXME: msg is String until binary is supported.
  871. // Once that happens, this will have to be smarter.
  872. if (datatype === String) {
  873. var ab = util.binaryStringToArrayBuffer(msg);
  874. msg = util.unpack(ab);
  875. self._handleMessage(msg);
  876. }
  877. };
  878. };
  879. // Handles an incoming message.
  880. Reliable.prototype._handleMessage = function(msg) {
  881. util.log('handleMessage: ', msg);
  882. var id = msg[1];
  883. var idata = this._incoming[id];
  884. var odata = this._outgoing[id];
  885. var data;
  886. switch (msg[0]) {
  887. // No chunking was done.
  888. case 'no':
  889. var message = id;
  890. if (!!message) {
  891. // TODO: What fancy timeout stuff to do with ACK?
  892. this.onmessage(util.unpack(message));
  893. }
  894. break;
  895. // Reached the end of the message.
  896. case 'end':
  897. // What if 'end' is sent out of order? Eventually we will ACK for
  898. // and receive it, so shouldn't be a problem.
  899. data = idata;
  900. if (!!data && data.ack[2] === msg[2]) {
  901. this._complete(id);
  902. this._received[id] = true;
  903. } else if (!!data) {
  904. this._ack(id, data.ack);
  905. }
  906. break;
  907. case 'ack':
  908. data = odata;
  909. if (!!data) {
  910. // TODO: more optimization for window size & data sent.
  911. // TODO: possibly process ACKs only after queue cleared to avoid dups?
  912. var ack = msg[2];
  913. // Take the larger ACK, for out of order messages.
  914. data.ack = Math.max(ack, data.ack);
  915. // Clean up when all chunks are ACKed.
  916. if (data.ack >= data.chunks.length) {
  917. util.log('Time: ', new Date() - data.timer);
  918. delete this._outgoing[id];
  919. } else {
  920. this._processAcks();
  921. }
  922. }
  923. // If !data, just ignore.
  924. break;
  925. // Received a chunk of data.
  926. case 'chunk':
  927. // Create a new entry if none exists.
  928. data = idata;
  929. if (!data) {
  930. if (this._received[id] !== undefined) {
  931. break;
  932. }
  933. data = {
  934. ack: ['ack', id, 0],
  935. chunks: []
  936. };
  937. this._incoming[id] = data;
  938. }
  939. var n = msg[2];
  940. var chunk = msg[3];
  941. data.chunks[n] = new Uint8Array(chunk);
  942. // If we get the chunk we're looking for, ACK for next missing.
  943. // Otherwise, ACK the same N again.
  944. if (n === data.ack[2]) {
  945. this._calculateNextAck(id);
  946. }
  947. this._ack(id);
  948. break;
  949. default:
  950. // Shouldn't happen, but would make sense for message to just go
  951. // through as is.
  952. this._handleSend(msg);
  953. break;
  954. }
  955. };
  956. // Chunks BL into smaller messages.
  957. Reliable.prototype._chunk = function(bl) {
  958. var chunks = [];
  959. var size = bl.size;
  960. var start = 0;
  961. while (start < size) {
  962. var end = Math.min(size, start + this._mtu);
  963. var b = bl.slice(start, end);
  964. var chunk = {
  965. payload: b
  966. }
  967. chunks.push(chunk);
  968. start = end;
  969. }
  970. return chunks;
  971. };
  972. // Sends ACK N, expecting Nth blob chunk for message ID.
  973. Reliable.prototype._ack = function(id, n) {
  974. var ack = this._incoming[id].ack;
  975. this._handleSend(ack);
  976. };
  977. // Calculates the next ACK number, given chunks.
  978. Reliable.prototype._calculateNextAck = function(id) {
  979. var data = this._incoming[id];
  980. var chunks = data.chunks;
  981. for (var i = 0, ii = chunks.length; i < ii; i += 1) {
  982. // This chunk is missing!!! Better ACK for it.
  983. if (chunks[i] === undefined) {
  984. data.ack[2] = i;
  985. return;
  986. }
  987. }
  988. data.ack[2] = chunks.length;
  989. };
  990. // Sends the next window of chunks.
  991. Reliable.prototype._sendWindowedChunks = function(id) {
  992. util.log('sendWindowedChunks for: ', id);
  993. var data = this._outgoing[id];
  994. var ch = data.chunks;
  995. var chunks = [];
  996. var limit = Math.min(data.ack + this._window, ch.length);
  997. for (var i = data.ack; i < limit; i += 1) {
  998. if (!ch[i].sent || i === data.ack) {
  999. // Sliding window.
  1000. if (i === data.ack && ch[i].sent) {
  1001. this._window = Math.max(1, Math.round(this._window / 10));
  1002. limit = Math.min(data.ack + this._window, ch.length);
  1003. } else if (i === data.ack) {
  1004. this._window = Math.min(1000, Math.round(this._window * 10));
  1005. limit = Math.min(data.ack + this._window, ch.length);
  1006. }
  1007. ch[i].sent = true;
  1008. chunks.push(['chunk', id, i, ch[i].payload]);
  1009. }
  1010. }
  1011. if (data.ack + this._window >= ch.length - 1) {
  1012. chunks.push(['end', id, ch.length])
  1013. }
  1014. chunks._multiple = true;
  1015. this._handleSend(chunks);
  1016. // TODO: set retry timer.
  1017. };
  1018. // Puts together a message from chunks.
  1019. Reliable.prototype._complete = function(id) {
  1020. // FIXME: handle errors.
  1021. util.log('Complete', id);
  1022. var self = this;
  1023. var chunks = this._incoming[id].chunks;
  1024. var bl = new Blob(chunks);
  1025. util.blobToArrayBuffer(bl, function(ab) {
  1026. util.log('Calling onmessage with complete message');
  1027. self.onmessage(util.unpack(ab));
  1028. });
  1029. delete this._incoming[id];
  1030. };
  1031. // Ups bandwidth limit on SDP. Meant to be called during offer/answer.
  1032. Reliable.higherBandwidthSDP = function(sdp) {
  1033. // AS stands for Application-Specific Maximum.
  1034. // Bandwidth number is in kilobits / sec.
  1035. // See RFC for more info: http://www.ietf.org/rfc/rfc2327.txt
  1036. var parts = sdp.split('b=AS:30');
  1037. var replace = 'b=AS:102400'; // 100 Mbps
  1038. return parts[0] + replace + parts[1];
  1039. };
  1040. exports.Reliable = Reliable;
  1041. var RTCPeerConnection = null;
  1042. var getUserMedia = null;
  1043. var attachMediaStream = null;
  1044. if (navigator.mozGetUserMedia) {
  1045. util.browserisms = 'Firefox';
  1046. RTCSessionDescription = window.mozRTCSessionDescription;
  1047. RTCPeerConnection = window.mozRTCPeerConnection;
  1048. getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1049. } else if (navigator.webkitGetUserMedia) {
  1050. util.browserisms = 'Webkit';
  1051. RTCPeerConnection = window.webkitRTCPeerConnection;
  1052. getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1053. }
  1054. exports.RTCSessionDescription = RTCSessionDescription;
  1055. exports.RTCPeerConnection = RTCPeerConnection;
  1056. exports.getUserMedia = getUserMedia;
  1057. /**
  1058. * A peer who can initiate connections with other peers.
  1059. */
  1060. function Peer(id, options) {
  1061. if (id && id.constructor == Object) {
  1062. options = id;
  1063. id = undefined;
  1064. }
  1065. if (!(this instanceof Peer)) return new Peer(id, options);
  1066. EventEmitter.call(this);
  1067. // First check if browser can use PeerConnection/DataChannels.
  1068. // TODO: when media is supported, lower browser version limit and move DC
  1069. // check to where`connect` is called.
  1070. if (!util.isBrowserCompatible()) {
  1071. this._abort('browser-incompatible', 'The current browser does not support WebRTC DataChannels');
  1072. return;
  1073. }
  1074. // Detect relative URL host.
  1075. if (options.host === '/') {
  1076. options.host = window.location.hostname;
  1077. }
  1078. options = util.extend({
  1079. debug: false,
  1080. host: '0.peerjs.com',
  1081. port: 9000,
  1082. key: 'peerjs',
  1083. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  1084. }, options);
  1085. this._options = options;
  1086. util.debug = options.debug;
  1087. // Ensure alphanumeric_-
  1088. var self = this;
  1089. if (id && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id)) {
  1090. util.setZeroTimeout(function() {
  1091. self._abort('invalid-id', 'ID "' + id + '" is invalid');
  1092. });
  1093. return
  1094. }
  1095. if (options.key && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(options.key)) {
  1096. util.setZeroTimeout(function() {
  1097. self._abort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  1098. });
  1099. return
  1100. }
  1101. // States.
  1102. this.destroyed = false;
  1103. this.disconnected = false;
  1104. // Connections for this peer.
  1105. this.connections = {};
  1106. // Connection managers.
  1107. this.managers = {};
  1108. // Queued connections to make.
  1109. this._queued = [];
  1110. // Init immediately if ID is given, otherwise ask server for ID
  1111. if (id) {
  1112. this.id = id;
  1113. this._init();
  1114. } else {
  1115. this.id = null;
  1116. this._retrieveId();
  1117. }
  1118. };
  1119. util.inherits(Peer, EventEmitter);
  1120. Peer.prototype._retrieveId = function(cb) {
  1121. var self = this;
  1122. try {
  1123. var http = new XMLHttpRequest();
  1124. var url = 'http://' + this._options.host + ':' + this._options.port + '/' + this._options.key + '/id';
  1125. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  1126. url += queryString;
  1127. // If there's no ID we need to wait for one before trying to init socket.
  1128. http.open('get', url, true);
  1129. http.onreadystatechange = function() {
  1130. if (http.readyState === 4) {
  1131. if (http.status !== 200) {
  1132. throw 'Retrieve id response not 200';
  1133. return;
  1134. }
  1135. self.id = http.responseText;
  1136. self._init();
  1137. }
  1138. };
  1139. http.send(null);
  1140. } catch(e) {
  1141. this._abort('server-error', 'Could not get an ID from the server');
  1142. }
  1143. };
  1144. Peer.prototype._init = function() {
  1145. var self = this;
  1146. this._socket = new Socket(this._options.host, this._options.port, this._options.key, this.id);
  1147. this._socket.on('message', function(data) {
  1148. self._handleServerJSONMessage(data);
  1149. });
  1150. this._socket.on('error', function(error) {
  1151. util.log(error);
  1152. self._abort('socket-error', error);
  1153. });
  1154. this._socket.on('close', function() {
  1155. var msg = 'Underlying socket has closed';
  1156. util.log('error', msg);
  1157. self._abort('socket-closed', msg);
  1158. });
  1159. this._socket.start();
  1160. }
  1161. Peer.prototype._handleServerJSONMessage = function(message) {
  1162. var peer = message.src;
  1163. var manager = this.managers[peer];
  1164. var payload = message.payload;
  1165. switch (message.type) {
  1166. case 'OPEN':
  1167. this._processQueue();
  1168. this.emit('open', this.id);
  1169. break;
  1170. case 'ERROR':
  1171. util.log(payload.msg);
  1172. this._abort('server-error', payload.msg);
  1173. break;
  1174. case 'ID-TAKEN':
  1175. this._abort('unavailable-id', 'ID `'+this.id+'` is taken');
  1176. break;
  1177. case 'OFFER':
  1178. var options = {
  1179. sdp: payload.sdp,
  1180. labels: payload.labels,
  1181. config: this._options.config
  1182. };
  1183. var manager = this.managers[peer];
  1184. if (!manager) {
  1185. manager = new ConnectionManager(this.id, peer, this._socket, options);
  1186. this._attachManagerListeners(manager);
  1187. this.managers[peer] = manager;
  1188. this.connections[peer] = manager.connections;
  1189. }
  1190. manager.update(options.labels);
  1191. manager.handleSDP(payload.sdp, message.type);
  1192. break;
  1193. case 'EXPIRE':
  1194. if (manager) {
  1195. manager.close();
  1196. manager.emit('error', new Error('Could not connect to peer ' + manager.peer));
  1197. }
  1198. break;
  1199. case 'ANSWER':
  1200. if (manager) {
  1201. manager.handleSDP(payload.sdp, message.type);
  1202. }
  1203. break;
  1204. case 'CANDIDATE':
  1205. if (manager) {
  1206. manager.handleCandidate(payload);
  1207. }
  1208. break;
  1209. case 'LEAVE':
  1210. if (manager) {
  1211. manager.handleLeave();
  1212. }
  1213. break;
  1214. case 'INVALID-KEY':
  1215. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  1216. break;
  1217. case 'PORT':
  1218. //if (util.browserisms === 'Firefox') {
  1219. // connection.handlePort(payload);
  1220. // break;
  1221. //}
  1222. default:
  1223. util.log('Unrecognized message type:', message.type);
  1224. break;
  1225. }
  1226. };
  1227. /** Process queued calls to connect. */
  1228. Peer.prototype._processQueue = function() {
  1229. while (this._queued.length > 0) {
  1230. var manager = this._queued.pop();
  1231. manager.initialize(this.id, this._socket);
  1232. }
  1233. };
  1234. /** Listeners for manager. */
  1235. Peer.prototype._attachManagerListeners = function(manager) {
  1236. var self = this;
  1237. // Handle receiving a connection.
  1238. manager.on('connection', function(connection) {
  1239. self.emit('connection', connection);
  1240. });
  1241. // Handle a connection closing.
  1242. manager.on('close', function() {
  1243. if (!!self.managers[manager.peer]) {
  1244. delete self.managers[manager.peer];
  1245. delete self.connections[manager.peer];
  1246. }
  1247. });
  1248. manager.on('error', function(err) {
  1249. self.emit('error', err);
  1250. });
  1251. };
  1252. /** Destroys the Peer and emits an error message. */
  1253. Peer.prototype._abort = function(type, message) {
  1254. var err = new Error(message);
  1255. err.type = type;
  1256. this.destroy();
  1257. this.emit('error', err);
  1258. };
  1259. Peer.prototype._cleanup = function() {
  1260. var self = this;
  1261. var peers = Object.keys(this.managers);
  1262. for (var i = 0, ii = peers.length; i < ii; i++) {
  1263. this.managers[peers[i]].close();
  1264. }
  1265. util.setZeroTimeout(function(){
  1266. self.disconnect();
  1267. });
  1268. this.emit('close');
  1269. };
  1270. /** Exposed connect function for users. Will try to connect later if user
  1271. * is waiting for an ID. */
  1272. Peer.prototype.connect = function(peer, options) {
  1273. if (this.disconnected) {
  1274. var err = new Error('This Peer has been disconnected from the server and can no longer make connections.');
  1275. err.type = 'server-disconnected';
  1276. this.emit('error', err);
  1277. return;
  1278. }
  1279. options = util.extend({
  1280. config: this._options.config
  1281. }, options);
  1282. var manager = this.managers[peer];
  1283. if (!manager) {
  1284. manager = new ConnectionManager(this.id, peer, this._socket, options);
  1285. this._attachManagerListeners(manager);
  1286. this.managers[peer] = manager;
  1287. this.connections[peer] = {};
  1288. }
  1289. var connection = manager.connect(options);
  1290. if (!this.id) {
  1291. this._queued.push(manager);
  1292. }
  1293. return connection;
  1294. };
  1295. /**
  1296. * Return the peer id or null, if there's no id at the moment.
  1297. * Reasons for no id could be 'connect in progress' or 'disconnected'
  1298. */
  1299. Peer.prototype.getId = function() {
  1300. return this.id;
  1301. };
  1302. /**
  1303. * Destroys the Peer: closes all active connections as well as the connection
  1304. * to the server.
  1305. * Warning: The peer can no longer create or accept connections after being
  1306. * destroyed.
  1307. */
  1308. Peer.prototype.destroy = function() {
  1309. if (!this.destroyed) {
  1310. this._cleanup();
  1311. this.destroyed = true;
  1312. }
  1313. };
  1314. /**
  1315. * Disconnects the Peer's connection to the PeerServer. Does not close any
  1316. * active connections.
  1317. * Warning: The peer can no longer create or accept connections after being
  1318. * disconnected. It also cannot reconnect to the server.
  1319. */
  1320. Peer.prototype.disconnect = function() {
  1321. if (!this.disconnected) {
  1322. this._socket.close();
  1323. this.id = null;
  1324. this.disconnected = true;
  1325. }
  1326. };
  1327. /**
  1328. * Provides a clean method for checking if there's an active connection to the
  1329. * peer server.
  1330. */
  1331. Peer.prototype.isConnected = function() {
  1332. return !this.disconnected;
  1333. };
  1334. /**
  1335. * Returns true if this peer is destroyed and can no longer be used.
  1336. */
  1337. Peer.prototype.isDestroyed = function() {
  1338. return this.destroyed;
  1339. };
  1340. exports.Peer = Peer;
  1341. /**
  1342. * Wraps a DataChannel between two Peers.
  1343. */
  1344. function DataConnection(peer, dc, options) {
  1345. if (!(this instanceof DataConnection)) return new DataConnection(peer, dc, options);
  1346. EventEmitter.call(this);
  1347. options = util.extend({
  1348. reliable: false,
  1349. serialization: 'binary'
  1350. }, options);
  1351. // Connection is not open yet.
  1352. this.open = false;
  1353. this.label = options.label;
  1354. this.metadata = options.metadata;
  1355. this.serialization = options.serialization;
  1356. this.peer = peer;
  1357. this._isReliable = options.reliable;
  1358. this._dc = dc;
  1359. if (!!this._dc) {
  1360. this._configureDataChannel();
  1361. }
  1362. };
  1363. util.inherits(DataConnection, EventEmitter);
  1364. DataConnection.prototype._configureDataChannel = function() {
  1365. var self = this;
  1366. if (util.browserisms !== 'Webkit') {
  1367. this._dc.binaryType = 'arraybuffer';
  1368. }
  1369. this._dc.onopen = function() {
  1370. util.log('Data channel connection success');
  1371. self.open = true;
  1372. self.emit('open');
  1373. };
  1374. // Reliable.
  1375. if (this._isReliable) {
  1376. this._reliable = new Reliable(this._dc, util.debug);
  1377. }
  1378. if (this._reliable) {
  1379. this._reliable.onmessage = function(msg) {
  1380. self.emit('data', msg);
  1381. };
  1382. } else {
  1383. this._dc.onmessage = function(e) {
  1384. self._handleDataMessage(e);
  1385. };
  1386. }
  1387. this._dc.onclose = function(e) {
  1388. util.log('DataChannel closed.');
  1389. self.close();
  1390. };
  1391. };
  1392. DataConnection.prototype._cleanup = function() {
  1393. if (!!this._dc && this._dc.readyState !== 'closed') {
  1394. this._dc.close();
  1395. this._dc = null;
  1396. }
  1397. this.open = false;
  1398. this.emit('close');
  1399. };
  1400. // Handles a DataChannel message.
  1401. DataConnection.prototype._handleDataMessage = function(e) {
  1402. var self = this;
  1403. var data = e.data;
  1404. var datatype = data.constructor;
  1405. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  1406. if (datatype === Blob) {
  1407. util.blobToArrayBuffer(data, function(ab) {
  1408. data = util.unpack(ab);
  1409. self.emit('data', data);
  1410. });
  1411. return;
  1412. } else if (datatype === ArrayBuffer) {
  1413. data = util.unpack(data);
  1414. } else if (datatype === String) {
  1415. var ab = util.binaryStringToArrayBuffer(data);
  1416. data = util.unpack(ab);
  1417. }
  1418. } else if (this.serialization === 'json') {
  1419. data = JSON.parse(data);
  1420. }
  1421. this.emit('data', data);
  1422. };
  1423. DataConnection.prototype.addDC = function(dc) {
  1424. this._dc = dc;
  1425. this._configureDataChannel();
  1426. };
  1427. /**
  1428. * Exposed functionality for users.
  1429. */
  1430. /** Allows user to close connection. */
  1431. DataConnection.prototype.close = function() {
  1432. if (!this.open) {
  1433. return;
  1434. }
  1435. this._cleanup();
  1436. };
  1437. /** Allows user to send data. */
  1438. DataConnection.prototype.send = function(data) {
  1439. if (!this.open) {
  1440. this.emit('error', new Error('Connection no longer open.'));
  1441. }
  1442. if (this._reliable) {
  1443. // Note: reliable sending will make it so that you cannot customize
  1444. // serialization.
  1445. this._reliable.send(data);
  1446. return;
  1447. }
  1448. var self = this;
  1449. if (this.serialization === 'none') {
  1450. this._dc.send(data);
  1451. } else if (this.serialization === 'json') {
  1452. this._dc.send(JSON.stringify(data));
  1453. } else {
  1454. var utf8 = (this.serialization === 'binary-utf8');
  1455. var blob = util.pack(data, utf8);
  1456. // DataChannel currently only supports strings.
  1457. if (util.browserisms === 'Webkit') {
  1458. util.blobToBinaryString(blob, function(str){
  1459. self._dc.send(str);
  1460. });
  1461. } else {
  1462. this._dc.send(blob);
  1463. }
  1464. }
  1465. };
  1466. /**
  1467. * Returns true if the DataConnection is open and able to send messages.
  1468. */
  1469. DataConnection.prototype.isOpen = function() {
  1470. return this.open;
  1471. };
  1472. /**
  1473. * Gets the metadata associated with this DataConnection.
  1474. */
  1475. DataConnection.prototype.getMetadata = function() {
  1476. return this.metadata;
  1477. };
  1478. /**
  1479. * Gets the label associated with this DataConnection.
  1480. */
  1481. DataConnection.prototype.getLabel = function() {
  1482. return this.label;
  1483. };
  1484. /**
  1485. * Gets the brokering ID of the peer that you are connected with.
  1486. * Note that this ID may be out of date if the peer has disconnected from the
  1487. * server, so it's not recommended that you use this ID to identify this
  1488. * connection.
  1489. */
  1490. DataConnection.prototype.getPeer = function() {
  1491. return this.peer;
  1492. };
  1493. /**
  1494. * Manages DataConnections between its peer and one other peer.
  1495. * Internally, manages PeerConnection.
  1496. */
  1497. function ConnectionManager(id, peer, socket, options) {
  1498. if (!(this instanceof ConnectionManager)) return new ConnectionManager(id, peer, socket, options);
  1499. EventEmitter.call(this);
  1500. options = util.extend({
  1501. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  1502. }, options);
  1503. this._options = options;
  1504. // PeerConnection is not yet dead.
  1505. this.open = true;
  1506. this.id = id;
  1507. this.peer = peer;
  1508. this.pc = null;
  1509. // Mapping labels to metadata and serialization.
  1510. // label => { metadata: ..., serialization: ..., reliable: ...}
  1511. this.labels = {};
  1512. // A default label in the event that none are passed in.
  1513. this._default = 0;
  1514. // DataConnections on this PC.
  1515. this.connections = {};
  1516. this._queued = [];
  1517. this._socket = socket;
  1518. if (!!this.id) {
  1519. this.initialize();
  1520. }
  1521. };
  1522. util.inherits(ConnectionManager, EventEmitter);
  1523. ConnectionManager.prototype.initialize = function(id, socket) {
  1524. if (!!id) {
  1525. this.id = id;
  1526. }
  1527. if (!!socket) {
  1528. this._socket = socket;
  1529. }
  1530. // Set up PeerConnection.
  1531. this._startPeerConnection();
  1532. // Process queued DCs.
  1533. this._processQueue();
  1534. // Listen for ICE candidates.
  1535. this._setupIce();
  1536. // Listen for negotiation needed.
  1537. // Chrome only **
  1538. this._setupNegotiationHandler();
  1539. // Listen for data channel.
  1540. this._setupDataChannel();
  1541. this.initialize = function() { };
  1542. };
  1543. /** Start a PC. */
  1544. ConnectionManager.prototype._startPeerConnection = function() {
  1545. util.log('Creating RTCPeerConnection');
  1546. this.pc = new RTCPeerConnection(this._options.config, { optional: [ { RtpDataChannels: true } ]});
  1547. };
  1548. /** Add DataChannels to all queued DataConnections. */
  1549. ConnectionManager.prototype._processQueue = function() {
  1550. var conn = this._queued.pop();
  1551. if (!!conn) {
  1552. conn.addDC(this.pc.createDataChannel(conn.label, { reliable: false }));
  1553. }
  1554. };
  1555. /** Set up ICE candidate handlers. */
  1556. ConnectionManager.prototype._setupIce = function() {
  1557. util.log('Listening for ICE candidates.');
  1558. var self = this;
  1559. this.pc.onicecandidate = function(evt) {
  1560. if (evt.candidate) {
  1561. util.log('Received ICE candidates.');
  1562. self._socket.send({
  1563. type: 'CANDIDATE',
  1564. payload: {
  1565. candidate: evt.candidate
  1566. },
  1567. dst: self.peer
  1568. });
  1569. }
  1570. };
  1571. this.pc.oniceconnectionstatechange = function() {
  1572. if (!!self.pc && self.pc.iceConnectionState === 'disconnected') {
  1573. util.log('iceConnectionState is disconnected, closing connections to ' + this.peer);
  1574. self.close();
  1575. }
  1576. };
  1577. // Fallback for older Chrome impls.
  1578. this.pc.onicechange = function() {
  1579. if (!!self.pc && self.pc.iceConnectionState === 'disconnected') {
  1580. util.log('iceConnectionState is disconnected, closing connections to ' + this.peer);
  1581. self.close();
  1582. }
  1583. };
  1584. };
  1585. /** Set up onnegotiationneeded. */
  1586. ConnectionManager.prototype._setupNegotiationHandler = function() {
  1587. var self = this;
  1588. util.log('Listening for `negotiationneeded`');
  1589. this.pc.onnegotiationneeded = function() {
  1590. util.log('`negotiationneeded` triggered');
  1591. self._makeOffer();
  1592. };
  1593. };
  1594. /** Set up Data Channel listener. */
  1595. ConnectionManager.prototype._setupDataChannel = function() {
  1596. var self = this;
  1597. util.log('Listening for data channel');
  1598. this.pc.ondatachannel = function(evt) {
  1599. util.log('Received data channel');
  1600. var dc = evt.channel;
  1601. var label = dc.label;
  1602. // This should not be empty.
  1603. var options = self.labels[label] || {};
  1604. var connection = new DataConnection(self.peer, dc, options);
  1605. self._attachConnectionListeners(connection);
  1606. self.connections[label] = connection;
  1607. self.emit('connection', connection);
  1608. };
  1609. };
  1610. /** Send an offer. */
  1611. ConnectionManager.prototype._makeOffer = function() {
  1612. var self = this;
  1613. this.pc.createOffer(function(offer) {
  1614. util.log('Created offer.');
  1615. self.pc.setLocalDescription(offer, function() {
  1616. util.log('Set localDescription to offer');
  1617. self._socket.send({
  1618. type: 'OFFER',
  1619. payload: {
  1620. sdp: offer,
  1621. config: self._options.config,
  1622. labels: self.labels
  1623. },
  1624. dst: self.peer
  1625. });
  1626. // We can now reset labels because all info has been communicated.
  1627. self.labels = {};
  1628. }, function(err) {
  1629. self.emit('error', err);
  1630. util.log('Failed to setLocalDescription, ', err);
  1631. });
  1632. });
  1633. };
  1634. /** Create an answer for PC. */
  1635. ConnectionManager.prototype._makeAnswer = function() {
  1636. var self = this;
  1637. this.pc.createAnswer(function(answer) {
  1638. util.log('Created answer.');
  1639. self.pc.setLocalDescription(answer, function() {
  1640. util.log('Set localDescription to answer.');
  1641. self._socket.send({
  1642. type: 'ANSWER',
  1643. payload: {
  1644. sdp: answer
  1645. },
  1646. dst: self.peer
  1647. });
  1648. }, function(err) {
  1649. self.emit('error', err);
  1650. util.log('Failed to setLocalDescription, ', err);
  1651. });
  1652. }, function(err) {
  1653. self.emit('error', err);
  1654. util.log('Failed to create answer, ', err);
  1655. });
  1656. };
  1657. /** Clean up PC, close related DCs. */
  1658. ConnectionManager.prototype._cleanup = function() {
  1659. util.log('Cleanup ConnectionManager for ' + this.peer);
  1660. if (!!this.pc && (this.pc.readyState !== 'closed' || this.pc.signalingState !== 'closed')) {
  1661. this.pc.close();
  1662. this.pc = null;
  1663. }
  1664. var self = this;
  1665. this._socket.send({
  1666. type: 'LEAVE',
  1667. dst: self.peer
  1668. });
  1669. this.open = false;
  1670. this.emit('close');
  1671. };
  1672. /** Attach connection listeners. */
  1673. ConnectionManager.prototype._attachConnectionListeners = function(connection) {
  1674. var self = this;
  1675. connection.on('close', function() {
  1676. if (!!self.connections[connection.label]) {
  1677. delete self.connections[connection.label];
  1678. }
  1679. if (!Object.keys(self.connections).length) {
  1680. self._cleanup();
  1681. }
  1682. });
  1683. connection.on('open', function() {
  1684. self._lock = false;
  1685. self._processQueue();
  1686. });
  1687. };
  1688. /** Handle an SDP. */
  1689. ConnectionManager.prototype.handleSDP = function(sdp, type) {
  1690. sdp = new RTCSessionDescription(sdp);
  1691. var self = this;
  1692. this.pc.setRemoteDescription(sdp, function() {
  1693. util.log('Set remoteDescription: ' + type);
  1694. if (type === 'OFFER') {
  1695. self._makeAnswer();
  1696. }
  1697. }, function(err) {
  1698. self.emit('error', err);
  1699. util.log('Failed to setRemoteDescription, ', err);
  1700. });
  1701. };
  1702. /** Handle a candidate. */
  1703. ConnectionManager.prototype.handleCandidate = function(message) {
  1704. var candidate = new RTCIceCandidate(message.candidate);
  1705. this.pc.addIceCandidate(candidate);
  1706. util.log('Added ICE candidate.');
  1707. };
  1708. /** Handle peer leaving. */
  1709. ConnectionManager.prototype.handleLeave = function() {
  1710. util.log('Peer ' + this.peer + ' disconnected.');
  1711. this.close();
  1712. };
  1713. /** Closes manager and all related connections. */
  1714. ConnectionManager.prototype.close = function() {
  1715. if (!this.open) {
  1716. this.emit('error', new Error('Connections to ' + this.peer + 'are already closed.'));
  1717. return;
  1718. }
  1719. var labels = Object.keys(this.connections);
  1720. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  1721. var label = labels[i];
  1722. var connection = this.connections[label];
  1723. connection.close();
  1724. }
  1725. this.connections = null;
  1726. this._cleanup();
  1727. };
  1728. /** Create and returns a DataConnection with the peer with the given label. */
  1729. ConnectionManager.prototype.connect = function(options) {
  1730. if (!this.open) {
  1731. return;
  1732. }
  1733. options = util.extend({
  1734. label: 'peerjs'
  1735. }, options);
  1736. // Check if label is taken...if so, generate a new label randomly.
  1737. while (!!this.connections[options.label]) {
  1738. options.label = 'peerjs' + this._default;
  1739. this._default += 1;
  1740. }
  1741. this.labels[options.label] = options;
  1742. var dc;
  1743. if (!!this.pc && !this._lock) {
  1744. dc = this.pc.createDataChannel(options.label, { reliable: false });
  1745. }
  1746. var connection = new DataConnection(this.peer, dc, options);
  1747. this._attachConnectionListeners(connection);
  1748. this.connections[options.label] = connection;
  1749. if (!this.pc || this._lock) {
  1750. this._queued.push(connection);
  1751. }
  1752. this._lock = true
  1753. return connection;
  1754. };
  1755. /** Updates label:[serialization, reliable, metadata] pairs from offer. */
  1756. ConnectionManager.prototype.update = function(updates) {
  1757. var labels = Object.keys(updates);
  1758. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  1759. var label = labels[i];
  1760. this.labels[label] = updates[label];
  1761. }
  1762. };
  1763. /**
  1764. * An abstraction on top of WebSockets and XHR streaming to provide fastest
  1765. * possible connection for peers.
  1766. */
  1767. function Socket(host, port, key, id) {
  1768. if (!(this instanceof Socket)) return new Socket(host, port, key, id);
  1769. EventEmitter.call(this);
  1770. this._id = id;
  1771. var token = util.randomToken();
  1772. this.disconnected = false;
  1773. this._httpUrl = 'http://' + host + ':' + port + '/' + key + '/' + id + '/' + token;
  1774. this._wsUrl = 'ws://' + host + ':' + port + '/peerjs?key='+key+'&id='+id+'&token='+token;
  1775. };
  1776. util.inherits(Socket, EventEmitter);
  1777. /** Check in with ID or get one from server. */
  1778. Socket.prototype.start = function() {
  1779. this._startXhrStream();
  1780. this._startWebSocket();
  1781. };
  1782. /** Start up websocket communications. */
  1783. Socket.prototype._startWebSocket = function() {
  1784. var self = this;
  1785. if (!!this._socket) {
  1786. return;
  1787. }
  1788. this._socket = new WebSocket(this._wsUrl);
  1789. this._socket.onmessage = function(event) {
  1790. var data;
  1791. try {
  1792. data = JSON.parse(event.data);
  1793. } catch(e) {
  1794. util.log('Invalid server message', event.data);
  1795. return;
  1796. }
  1797. self.emit('message', data);
  1798. };
  1799. // Take care of the queue of connections if necessary and make sure Peer knows
  1800. // socket is open.
  1801. this._socket.onopen = function() {
  1802. if (!!self._timeout) {
  1803. clearTimeout(self._timeout);
  1804. setTimeout(function(){
  1805. self._http.abort();
  1806. self._http = null;
  1807. }, 5000);
  1808. }
  1809. util.log('Socket open');
  1810. };
  1811. };
  1812. /** Start XHR streaming. */
  1813. Socket.prototype._startXhrStream = function(n) {
  1814. try {
  1815. var self = this;
  1816. this._http = new XMLHttpRequest();
  1817. this._http._index = 1;
  1818. this._http._streamIndex = n || 0;
  1819. this._http.open('post', this._httpUrl + '/id?i=' + this._http._streamIndex, true);
  1820. this._http.onreadystatechange = function() {
  1821. if (this.readyState == 2 && !!this.old) {
  1822. this.old.abort();
  1823. delete this.old;
  1824. }
  1825. if (this.readyState > 2 && this.status == 200 && !!this.responseText) {
  1826. self._handleStream(this);
  1827. }
  1828. };
  1829. this._http.send(null);
  1830. this._setHTTPTimeout();
  1831. } catch(e) {
  1832. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  1833. }
  1834. };
  1835. /** Handles onreadystatechange response as a stream. */
  1836. Socket.prototype._handleStream = function(http) {
  1837. // 3 and 4 are loading/done state. All others are not relevant.
  1838. var messages = http.responseText.split('\n');
  1839. // Check to see if anything needs to be processed on buffer.
  1840. if (!!http._buffer) {
  1841. while (http._buffer.length > 0) {
  1842. var index = http._buffer.shift();
  1843. var bufferedMessage = messages[index];
  1844. try {
  1845. bufferedMessage = JSON.parse(bufferedMessage);
  1846. } catch(e) {
  1847. http._buffer.shift(index);
  1848. break;
  1849. }
  1850. this.emit('message', bufferedMessage);
  1851. }
  1852. }
  1853. var message = messages[http._index];
  1854. if (!!message) {
  1855. http._index += 1;
  1856. // Buffering--this message is incomplete and we'll get to it next time.
  1857. // This checks if the httpResponse ended in a `\n`, in which case the last
  1858. // element of messages should be the empty string.
  1859. if (http._index === messages.length) {
  1860. if (!http._buffer) {
  1861. http._buffer = [];
  1862. }
  1863. http._buffer.push(http._index - 1);
  1864. } else {
  1865. try {
  1866. message = JSON.parse(message);
  1867. } catch(e) {
  1868. util.log('Invalid server message', message);
  1869. return;
  1870. }
  1871. this.emit('message', message);
  1872. }
  1873. }
  1874. };
  1875. Socket.prototype._setHTTPTimeout = function() {
  1876. var self = this;
  1877. this._timeout = setTimeout(function() {
  1878. var old = self._http;
  1879. if (!self._wsOpen()) {
  1880. self._startXhrStream(old._streamIndex + 1);
  1881. self._http.old = old;
  1882. } else {
  1883. old.abort();
  1884. }
  1885. }, 25000);
  1886. };
  1887. Socket.prototype._wsOpen = function() {
  1888. return !!this._socket && this._socket.readyState == 1;
  1889. };
  1890. /** Exposed send for DC & Peer. */
  1891. Socket.prototype.send = function(data) {
  1892. if (this.disconnected) {
  1893. return;
  1894. }
  1895. if (!data.type) {
  1896. this.emit('error', 'Invalid message');
  1897. return;
  1898. }
  1899. var message = JSON.stringify(data);
  1900. if (this._wsOpen()) {
  1901. this._socket.send(message);
  1902. } else {
  1903. var http = new XMLHttpRequest();
  1904. var url = this._httpUrl + '/' + data.type.toLowerCase();
  1905. http.open('post', url, true);
  1906. http.setRequestHeader('Content-Type', 'application/json');
  1907. http.send(message);
  1908. }
  1909. };
  1910. Socket.prototype.close = function() {
  1911. if (!this.disconnected && this._wsOpen()) {
  1912. this._socket.close();
  1913. this.disconnected = true;
  1914. }
  1915. };
  1916. })(this);