peer.js 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191
  1. /*! peerjs.js build:0.2.0, development. Copyright(c) 2013 Michelle Bu <michelle@michellebu.com> */
  2. (function(exports){
  3. var binaryFeatures = {};
  4. binaryFeatures.useBlobBuilder = (function(){
  5. try {
  6. new Blob([]);
  7. return false;
  8. } catch (e) {
  9. return true;
  10. }
  11. })();
  12. binaryFeatures.useArrayBufferView = !binaryFeatures.useBlobBuilder && (function(){
  13. try {
  14. return (new Blob([new Uint8Array([])])).size === 0;
  15. } catch (e) {
  16. return true;
  17. }
  18. })();
  19. exports.binaryFeatures = binaryFeatures;
  20. exports.BlobBuilder = window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder || window.BlobBuilder;
  21. function BufferBuilder(){
  22. this._pieces = [];
  23. this._parts = [];
  24. }
  25. BufferBuilder.prototype.append = function(data) {
  26. if(typeof data === 'number') {
  27. this._pieces.push(data);
  28. } else {
  29. this._flush();
  30. this._parts.push(data);
  31. }
  32. };
  33. BufferBuilder.prototype._flush = function() {
  34. if (this._pieces.length > 0) {
  35. var buf = new Uint8Array(this._pieces);
  36. if(!binaryFeatures.useArrayBufferView) {
  37. buf = buf.buffer;
  38. }
  39. this._parts.push(buf);
  40. this._pieces = [];
  41. }
  42. };
  43. BufferBuilder.prototype.getBuffer = function() {
  44. this._flush();
  45. if(binaryFeatures.useBlobBuilder) {
  46. var builder = new BlobBuilder();
  47. for(var i = 0, ii = this._parts.length; i < ii; i++) {
  48. builder.append(this._parts[i]);
  49. }
  50. return builder.getBlob();
  51. } else {
  52. return new Blob(this._parts);
  53. }
  54. };
  55. exports.BinaryPack = {
  56. unpack: function(data){
  57. var unpacker = new Unpacker(data);
  58. return unpacker.unpack();
  59. },
  60. pack: function(data, 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. 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._getId();
  1116. }
  1117. };
  1118. util.inherits(Peer, EventEmitter);
  1119. Peer.prototype._getId = function(cb) {
  1120. var self = this;
  1121. try {
  1122. var http = new XMLHttpRequest();
  1123. var url = 'http://' + this._options.host + ':' + this._options.port + '/' + this._options.key + '/id';
  1124. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  1125. url += queryString;
  1126. // If there's no ID we need to wait for one before trying to init socket.
  1127. http.open('get', url, true);
  1128. http.onreadystatechange = function() {
  1129. if (http.readyState === 4) {
  1130. self.id = http.responseText;
  1131. self._init();
  1132. }
  1133. };
  1134. http.send(null);
  1135. } catch(e) {
  1136. this._abort('server-error', 'Could not get an ID from the server');
  1137. }
  1138. };
  1139. Peer.prototype._init = function() {
  1140. var self = this;
  1141. this._socket = new Socket(this._options.host, this._options.port, this._options.key, this.id);
  1142. this._socket.on('message', function(data) {
  1143. self._handleServerJSONMessage(data);
  1144. });
  1145. this._socket.on('error', function(error) {
  1146. util.log(error);
  1147. self._abort('socket-error', error);
  1148. });
  1149. this._socket.on('close', function() {
  1150. var msg = 'Underlying socket has closed';
  1151. util.log('error', msg);
  1152. self._abort('socket-closed', msg);
  1153. });
  1154. this._socket.start();
  1155. }
  1156. Peer.prototype._handleServerJSONMessage = function(message) {
  1157. var peer = message.src;
  1158. var manager = this.managers[peer];
  1159. var payload = message.payload;
  1160. // Check that browsers match.
  1161. if (!!payload && !!payload.browserisms && payload.browserisms !== util.browserisms) {
  1162. this._warn('incompatible-peer', 'Peer ' + self.peer + ' is on an incompatible browser. Please clean up this peer.');
  1163. }
  1164. switch (message.type) {
  1165. case 'OPEN':
  1166. this._processQueue();
  1167. this.emit('open', this.id);
  1168. break;
  1169. case 'ERROR':
  1170. util.log(payload.msg);
  1171. this._abort('server-error', payload.msg);
  1172. break;
  1173. case 'ID-TAKEN':
  1174. this._abort('unavailable-id', 'ID `'+this.id+'` is taken');
  1175. break;
  1176. case 'OFFER':
  1177. var options = {
  1178. sdp: payload.sdp,
  1179. labels: payload.labels,
  1180. config: this._options.config
  1181. };
  1182. var manager = this.managers[peer];
  1183. if (!manager) {
  1184. manager = new ConnectionManager(this.id, peer, this._socket, options);
  1185. this._attachManagerListeners(manager);
  1186. this.managers[peer] = manager;
  1187. this.connections[peer] = {};
  1188. }
  1189. manager.update(options.labels);
  1190. manager.handleSDP(payload.sdp, message.type);
  1191. break;
  1192. case 'EXPIRE':
  1193. if (manager) {
  1194. manager.close();
  1195. manager.emit('error', new Error('Could not connect to peer ' + manager.peer));
  1196. }
  1197. break;
  1198. case 'ANSWER':
  1199. if (manager) {
  1200. manager.handleSDP(payload.sdp, message.type);
  1201. }
  1202. break;
  1203. case 'CANDIDATE':
  1204. if (manager) {
  1205. manager.handleCandidate(payload);
  1206. }
  1207. break;
  1208. case 'LEAVE':
  1209. if (manager) {
  1210. manager.handleLeave();
  1211. }
  1212. break;
  1213. case 'INVALID-KEY':
  1214. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  1215. break;
  1216. case 'PORT':
  1217. // Firefoxism: exchanging ports.
  1218. if (util.browserisms === 'Firefox' && manager) {
  1219. manager.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.connections[connection.peer][connection.label] = connection;
  1240. self.emit('connection', connection);
  1241. });
  1242. // Handle a connection closing.
  1243. manager.on('close', function() {
  1244. if (!!self.managers[manager.peer]) {
  1245. delete self.managers[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. /** Emits an error message that things may not work. */
  1260. Peer.prototype._warn = function(type, message) {
  1261. var err = new Error(message);
  1262. err.type = type;
  1263. this.emit('error', err);
  1264. };
  1265. Peer.prototype._cleanup = function() {
  1266. var self = this;
  1267. if (!!this.managers) {
  1268. var peers = Object.keys(this.managers);
  1269. for (var i = 0, ii = peers.length; i < ii; i++) {
  1270. this.managers[peers[i]].close();
  1271. }
  1272. util.setZeroTimeout(function(){
  1273. self.disconnect();
  1274. });
  1275. }
  1276. this.emit('close');
  1277. };
  1278. /** Exposed connect function for users. Will try to connect later if user
  1279. * is waiting for an ID. */
  1280. Peer.prototype.connect = function(peer, options) {
  1281. if (this.disconnected) {
  1282. this._warn('server-disconnected', 'This Peer has been disconnected from the server and can no longer make connections.');
  1283. return;
  1284. }
  1285. options = util.extend({
  1286. config: this._options.config
  1287. }, options);
  1288. options.originator = true;
  1289. var manager = this.managers[peer];
  1290. if (!manager) {
  1291. manager = new ConnectionManager(this.id, peer, this._socket, options);
  1292. this._attachManagerListeners(manager);
  1293. this.managers[peer] = manager;
  1294. this.connections[peer] = {};
  1295. }
  1296. var connectionInfo = manager.connect(options);
  1297. if (!!connectionInfo) {
  1298. this.connections[peer][connectionInfo[0]] = connectionInfo[1];
  1299. }
  1300. if (!this.id) {
  1301. this._queued.push(manager);
  1302. }
  1303. return connectionInfo[1];
  1304. };
  1305. /**
  1306. * Destroys the Peer: closes all active connections as well as the connection
  1307. * to the server.
  1308. * Warning: The peer can no longer create or accept connections after being
  1309. * destroyed.
  1310. */
  1311. Peer.prototype.destroy = function() {
  1312. if (!this.destroyed) {
  1313. this._cleanup();
  1314. this.destroyed = true;
  1315. }
  1316. };
  1317. /**
  1318. * Disconnects the Peer's connection to the PeerServer. Does not close any
  1319. * active connections.
  1320. * Warning: The peer can no longer create or accept connections after being
  1321. * disconnected. It also cannot reconnect to the server.
  1322. */
  1323. Peer.prototype.disconnect = function() {
  1324. if (!this.disconnected) {
  1325. this._socket.close();
  1326. this.disconnected = true;
  1327. }
  1328. };
  1329. exports.Peer = Peer;
  1330. /**
  1331. * Wraps a DataChannel between two Peers.
  1332. */
  1333. function DataConnection(peer, dc, options) {
  1334. if (!(this instanceof DataConnection)) return new DataConnection(peer, dc, options);
  1335. EventEmitter.call(this);
  1336. options = util.extend({
  1337. reliable: false,
  1338. serialization: 'binary'
  1339. }, options);
  1340. // Connection is not open yet.
  1341. this.open = false;
  1342. this.label = options.label;
  1343. // Firefox is not this finely configurable.
  1344. this.metadata = options.metadata;
  1345. this.serialization = util.browserisms !== 'Firefox' ? options.serialization : 'binary';
  1346. this._isReliable = util.browserisms !== 'Firefox' ? options.reliable : false;
  1347. this.peer = peer;
  1348. this._dc = dc;
  1349. if (!!this._dc) {
  1350. this._configureDataChannel();
  1351. }
  1352. };
  1353. util.inherits(DataConnection, EventEmitter);
  1354. DataConnection.prototype._configureDataChannel = function() {
  1355. util.log('Configuring DataChannel with peer ' + this.peer);
  1356. var self = this;
  1357. if (util.browserisms !== 'Webkit') {
  1358. this._dc.binaryType = 'arraybuffer';
  1359. }
  1360. this._dc.onopen = function() {
  1361. util.log('Data channel connection success');
  1362. self.open = true;
  1363. self.emit('open');
  1364. };
  1365. // Reliable.
  1366. if (this._isReliable) {
  1367. this._reliable = new Reliable(this._dc, util.debug);
  1368. }
  1369. if (this._reliable) {
  1370. this._reliable.onmessage = function(msg) {
  1371. self.emit('data', msg);
  1372. };
  1373. } else {
  1374. this._dc.onmessage = function(e) {
  1375. self._handleDataMessage(e);
  1376. };
  1377. }
  1378. this._dc.onclose = function(e) {
  1379. util.log('DataChannel closed.');
  1380. self.close();
  1381. };
  1382. };
  1383. DataConnection.prototype._cleanup = function() {
  1384. if (!!this._dc && this._dc.readyState !== 'closed') {
  1385. this._dc.close();
  1386. this._dc = null;
  1387. }
  1388. this.open = false;
  1389. this.emit('close');
  1390. };
  1391. // Handles a DataChannel message.
  1392. DataConnection.prototype._handleDataMessage = function(e) {
  1393. var self = this;
  1394. var data = e.data;
  1395. var datatype = data.constructor;
  1396. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  1397. if (datatype === Blob) {
  1398. util.blobToArrayBuffer(data, function(ab) {
  1399. data = util.unpack(ab);
  1400. self.emit('data', data);
  1401. });
  1402. return;
  1403. } else if (datatype === ArrayBuffer) {
  1404. data = util.unpack(data);
  1405. } else if (datatype === String) {
  1406. var ab = util.binaryStringToArrayBuffer(data);
  1407. data = util.unpack(ab);
  1408. }
  1409. } else if (this.serialization === 'json') {
  1410. data = JSON.parse(data);
  1411. }
  1412. this.emit('data', data);
  1413. };
  1414. DataConnection.prototype.addDC = function(dc) {
  1415. this._dc = dc;
  1416. this._configureDataChannel();
  1417. };
  1418. /**
  1419. * Exposed functionality for users.
  1420. */
  1421. /** Allows user to close connection. */
  1422. DataConnection.prototype.close = function() {
  1423. if (!this.open) {
  1424. return;
  1425. }
  1426. this._cleanup();
  1427. };
  1428. /** Allows user to send data. */
  1429. DataConnection.prototype.send = function(data) {
  1430. if (!this.open) {
  1431. this.emit('error', new Error('Connection no longer open.'));
  1432. }
  1433. if (this._reliable) {
  1434. // Note: reliable sending will make it so that you cannot customize
  1435. // serialization.
  1436. this._reliable.send(data);
  1437. return;
  1438. }
  1439. var self = this;
  1440. if (this.serialization === 'none') {
  1441. this._dc.send(data);
  1442. } else if (this.serialization === 'json') {
  1443. this._dc.send(JSON.stringify(data));
  1444. } else {
  1445. var utf8 = (this.serialization === 'binary-utf8');
  1446. var blob = util.pack(data, utf8);
  1447. // DataChannel currently only supports strings.
  1448. if (util.browserisms === 'Webkit') {
  1449. util.blobToBinaryString(blob, function(str){
  1450. self._dc.send(str);
  1451. });
  1452. } else {
  1453. this._dc.send(blob);
  1454. }
  1455. }
  1456. };
  1457. /**
  1458. * Manages DataConnections between its peer and one other peer.
  1459. * Internally, manages PeerConnection.
  1460. */
  1461. function ConnectionManager(id, peer, socket, options) {
  1462. if (!(this instanceof ConnectionManager)) return new ConnectionManager(id, peer, socket, options);
  1463. EventEmitter.call(this);
  1464. options = util.extend({
  1465. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  1466. }, options);
  1467. this._options = options;
  1468. // PeerConnection is not yet dead.
  1469. this.open = true;
  1470. this.id = id;
  1471. this.peer = peer;
  1472. this.pc = null;
  1473. // Mapping labels to metadata and serialization.
  1474. // label => { metadata: ..., serialization: ..., reliable: ...}
  1475. this.labels = {};
  1476. // A default label in the event that none are passed in.
  1477. this._default = 0;
  1478. // DataConnections on this PC.
  1479. this.connections = {};
  1480. this._queued = [];
  1481. this._socket = socket;
  1482. if (!!this.id) {
  1483. this.initialize();
  1484. }
  1485. };
  1486. util.inherits(ConnectionManager, EventEmitter);
  1487. ConnectionManager.prototype.initialize = function(id, socket) {
  1488. if (!!id) {
  1489. this.id = id;
  1490. }
  1491. if (!!socket) {
  1492. this._socket = socket;
  1493. }
  1494. // Firefoxism where ports need to be generated.
  1495. if (util.browserisms === 'Firefox') {
  1496. this._firefoxPortSetup();
  1497. }
  1498. // Set up PeerConnection.
  1499. this._startPeerConnection();
  1500. // Process queued DCs.
  1501. if (util.browserisms !== 'Firefox') {
  1502. this._processQueue();
  1503. }
  1504. // Listen for ICE candidates.
  1505. this._setupIce();
  1506. // Listen for data channel.
  1507. this._setupDataChannel();
  1508. // Listen for negotiation needed.
  1509. // Chrome only--Firefox instead has to manually makeOffer.
  1510. if (util.browserisms !== 'Firefox') {
  1511. this._setupNegotiationHandler();
  1512. } else if (this._options.originator) {
  1513. this._firefoxHandlerSetup()
  1514. this._firefoxAdditional()
  1515. }
  1516. this.initialize = function() { };
  1517. };
  1518. /** Firefoxism that requires a fake media stream. */
  1519. ConnectionManager.prototype._firefoxAdditional = function() {
  1520. util.log('Additional media stream for Firefox.');
  1521. var self = this;
  1522. getUserMedia({ audio: true, fake: true }, function(s) {
  1523. self.pc.addStream(s);
  1524. if (self._options.originator) {
  1525. self._makeOffer();
  1526. } else {
  1527. self._makeAnswer();
  1528. }
  1529. }, function(err) { util.log('Could not getUserMedia'); });
  1530. };
  1531. /** Firefoxism that requires ports to be set up. */
  1532. ConnectionManager.prototype._firefoxPortSetup = function() {
  1533. if (!ConnectionManager.usedPorts) {
  1534. ConnectionManager.usedPorts = [];
  1535. }
  1536. this._localPort = util.randomPort();
  1537. while (ConnectionManager.usedPorts.indexOf(this._localPort) != -1) {
  1538. this._localPort = util.randomPort();
  1539. }
  1540. this._remotePort = util.randomPort();
  1541. while (this._remotePort === this._localPort ||
  1542. ConnectionManager.usedPorts.indexOf(this._remotePort) != -1) {
  1543. this._remotePort = util.randomPort();
  1544. }
  1545. ConnectionManager.usedPorts.push(this._remotePort);
  1546. ConnectionManager.usedPorts.push(this._localPort);
  1547. };
  1548. /** Firefoxism that is `onconnection`. */
  1549. ConnectionManager.prototype._firefoxHandlerSetup = function() {
  1550. util.log('Setup Firefox `onconnection`.');
  1551. var self = this;
  1552. this.pc.onconnection = function() {
  1553. util.log('FIREFOX: onconnection triggered');
  1554. self._processQueue();
  1555. }
  1556. };
  1557. /** Start a PC. */
  1558. ConnectionManager.prototype._startPeerConnection = function() {
  1559. util.log('Creating RTCPeerConnection');
  1560. this.pc = new RTCPeerConnection(this._options.config, { optional: [ { RtpDataChannels: true } ]});
  1561. };
  1562. /** Add DataChannels to all queued DataConnections. */
  1563. ConnectionManager.prototype._processQueue = function() {
  1564. var conn = this._queued.pop();
  1565. if (!!conn) {
  1566. conn.addDC(this.pc.createDataChannel(conn.label, { reliable: false }));
  1567. }
  1568. };
  1569. /** Set up ICE candidate handlers. */
  1570. ConnectionManager.prototype._setupIce = function() {
  1571. util.log('Listening for ICE candidates.');
  1572. var self = this;
  1573. this.pc.onicecandidate = function(evt) {
  1574. if (evt.candidate) {
  1575. util.log('Received ICE candidates.');
  1576. self._socket.send({
  1577. type: 'CANDIDATE',
  1578. payload: {
  1579. candidate: evt.candidate
  1580. },
  1581. dst: self.peer
  1582. });
  1583. }
  1584. };
  1585. };
  1586. /** Set up onnegotiationneeded. */
  1587. ConnectionManager.prototype._setupNegotiationHandler = function() {
  1588. var self = this;
  1589. util.log('Listening for `negotiationneeded`');
  1590. this.pc.onnegotiationneeded = function() {
  1591. util.log('`negotiationneeded` triggered');
  1592. self._makeOffer();
  1593. };
  1594. };
  1595. /** Set up Data Channel listener. */
  1596. ConnectionManager.prototype._setupDataChannel = function() {
  1597. var self = this;
  1598. util.log('Listening for data channel');
  1599. this.pc.ondatachannel = function(evt) {
  1600. util.log('Received data channel');
  1601. // Firefoxism: ondatachannel receives channel directly. NOT TO SPEC.
  1602. var dc = util.browserisms === 'Firefox' ? evt : evt.channel;
  1603. var label = dc.label;
  1604. // This should not be empty.
  1605. // NOTE: Multiple DCs are currently not configurable in FF. Will have to
  1606. // come up with reasonable defaults.
  1607. var options = self.labels[label] || { label: label };
  1608. var connection = new DataConnection(self.peer, dc, options);
  1609. delete self.labels[label];
  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. self.pc.setLocalDescription(offer, function() {
  1621. util.log('Set localDescription to offer');
  1622. self._socket.send({
  1623. type: 'OFFER',
  1624. payload: {
  1625. browserisms: util.browserisms,
  1626. sdp: offer,
  1627. config: self._options.config,
  1628. labels: self.labels
  1629. },
  1630. dst: self.peer
  1631. });
  1632. // We can now reset labels because all info has been communicated.
  1633. self.labels = {};
  1634. }, function(err) {
  1635. self.emit('error', err);
  1636. util.log('Failed to setLocalDescription, ', err);
  1637. });
  1638. });
  1639. };
  1640. /** Create an answer for PC. */
  1641. ConnectionManager.prototype._makeAnswer = function() {
  1642. var self = this;
  1643. this.pc.createAnswer(function(answer) {
  1644. util.log('Created answer.');
  1645. self.pc.setLocalDescription(answer, function() {
  1646. util.log('Set localDescription to answer.');
  1647. self._socket.send({
  1648. type: 'ANSWER',
  1649. payload: {
  1650. browserisms: util.browserisms,
  1651. sdp: answer
  1652. },
  1653. dst: self.peer
  1654. });
  1655. }, function(err) {
  1656. self.emit('error', err);
  1657. util.log('Failed to setLocalDescription, ', err);
  1658. });
  1659. }, function(err) {
  1660. self.emit('error', err);
  1661. util.log('Failed to create answer, ', err);
  1662. });
  1663. };
  1664. /** Clean up PC, close related DCs. */
  1665. ConnectionManager.prototype._cleanup = function() {
  1666. util.log('Cleanup ConnectionManager for ' + this.peer);
  1667. if (!!this.pc && this.pc.readyState !== 'closed') {
  1668. this.pc.close();
  1669. this.pc = null;
  1670. }
  1671. var self = this;
  1672. this._socket.send({
  1673. type: 'LEAVE',
  1674. dst: self.peer
  1675. });
  1676. this.open = false;
  1677. this.emit('close');
  1678. };
  1679. /** Attach connection listeners. */
  1680. ConnectionManager.prototype._attachConnectionListeners = function(connection) {
  1681. var self = this;
  1682. connection.on('close', function() {
  1683. if (!!self.connections[connection.label]) {
  1684. delete self.connections[connection.label];
  1685. }
  1686. if (!Object.keys(self.connections).length) {
  1687. self._cleanup();
  1688. }
  1689. });
  1690. connection.on('open', function() {
  1691. self._lock = false;
  1692. self._processQueue();
  1693. });
  1694. };
  1695. /** Firefoxism: handle receiving a set of ports. */
  1696. ConnectionManager.prototype.handlePort = function(ports) {
  1697. util.log('Received ports, calling connectDataConnection.');
  1698. if (!ConnectionManager.usedPorts) {
  1699. ConnectionManager.usedPorts = [];
  1700. }
  1701. ConnectionManager.usedPorts.push(ports.local);
  1702. ConnectionManager.usedPorts.push(ports.remote);
  1703. this.pc.connectDataConnection(ports.local, ports.remote);
  1704. };
  1705. /** Handle an SDP. */
  1706. ConnectionManager.prototype.handleSDP = function(sdp, type) {
  1707. if (util.browserisms !== 'Firefox') {
  1708. // Doesn't need to happen for FF.
  1709. sdp = new RTCSessionDescription(sdp);
  1710. }
  1711. var self = this;
  1712. this.pc.setRemoteDescription(sdp, function() {
  1713. util.log('Set remoteDescription: ' + type);
  1714. if (type === 'OFFER') {
  1715. if (util.browserisms === 'Firefox') {
  1716. self._firefoxAdditional();
  1717. } else {
  1718. self._makeAnswer();
  1719. }
  1720. } else if (util.browserisms === 'Firefox') {
  1721. // Firefoxism.
  1722. util.log('Peer ANSWER received, connectDataConnection called.');
  1723. self.pc.connectDataConnection(self._localPort, self._remotePort);
  1724. self._socket.send({
  1725. type: 'PORT',
  1726. payload: {
  1727. remote: self._localPort,
  1728. local: self._remotePort
  1729. },
  1730. dst: self.peer
  1731. });
  1732. }
  1733. }, function(err) {
  1734. self.emit('error', err);
  1735. util.log('Failed to setRemoteDescription, ', err);
  1736. });
  1737. };
  1738. /** Handle a candidate. */
  1739. ConnectionManager.prototype.handleCandidate = function(message) {
  1740. var candidate = new RTCIceCandidate(message.candidate);
  1741. this.pc.addIceCandidate(candidate);
  1742. util.log('Added ICE candidate.');
  1743. };
  1744. /** Handle peer leaving. */
  1745. ConnectionManager.prototype.handleLeave = function() {
  1746. util.log('Peer ' + this.peer + ' disconnected.');
  1747. this.close();
  1748. };
  1749. /** Closes manager and all related connections. */
  1750. ConnectionManager.prototype.close = function() {
  1751. if (!this.open) {
  1752. this.emit('error', new Error('Connections to ' + this.peer + 'are already closed.'));
  1753. return;
  1754. }
  1755. var labels = Object.keys(this.connections);
  1756. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  1757. var label = labels[i];
  1758. var connection = this.connections[label];
  1759. connection.close();
  1760. }
  1761. this.connections = null;
  1762. this._cleanup();
  1763. };
  1764. /** Create and returns a DataConnection with the peer with the given label. */
  1765. ConnectionManager.prototype.connect = function(options) {
  1766. if (!this.open) {
  1767. return;
  1768. }
  1769. options = util.extend({
  1770. label: 'peerjs'
  1771. }, options);
  1772. // Check if label is taken...if so, generate a new label randomly.
  1773. while (!!this.connections[options.label]) {
  1774. options.label = 'peerjs' + this._default;
  1775. this._default += 1;
  1776. }
  1777. this.labels[options.label] = options;
  1778. var dc;
  1779. if (!!this.pc && !this._lock && (util.browserisms !== 'Firefox' || Object.keys(this.connections).length !== 0)) {
  1780. dc = this.pc.createDataChannel(options.label, { reliable: false });
  1781. }
  1782. var connection = new DataConnection(this.peer, dc, options);
  1783. this._attachConnectionListeners(connection);
  1784. this.connections[options.label] = connection;
  1785. if (!dc) {
  1786. this._queued.push(connection);
  1787. }
  1788. this._lock = true
  1789. return [options.label, connection];
  1790. };
  1791. /** Updates label:[serialization, reliable, metadata] pairs from offer. */
  1792. ConnectionManager.prototype.update = function(updates) {
  1793. var labels = Object.keys(updates);
  1794. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  1795. var label = labels[i];
  1796. this.labels[label] = updates[label];
  1797. }
  1798. };
  1799. /**
  1800. * An abstraction on top of WebSockets and XHR streaming to provide fastest
  1801. * possible connection for peers.
  1802. */
  1803. function Socket(host, port, key, id) {
  1804. if (!(this instanceof Socket)) return new Socket(host, port, key, id);
  1805. EventEmitter.call(this);
  1806. this._id = id;
  1807. var token = util.randomToken();
  1808. this.disconnected = false;
  1809. this._httpUrl = 'http://' + host + ':' + port + '/' + key + '/' + id + '/' + token;
  1810. this._wsUrl = 'ws://' + host + ':' + port + '/peerjs?key='+key+'&id='+id+'&token='+token;
  1811. };
  1812. util.inherits(Socket, EventEmitter);
  1813. /** Check in with ID or get one from server. */
  1814. Socket.prototype.start = function() {
  1815. this._startXhrStream();
  1816. this._startWebSocket();
  1817. };
  1818. /** Start up websocket communications. */
  1819. Socket.prototype._startWebSocket = function() {
  1820. var self = this;
  1821. if (!!this._socket) {
  1822. return;
  1823. }
  1824. this._socket = new WebSocket(this._wsUrl);
  1825. this._socket.onmessage = function(event) {
  1826. var data;
  1827. try {
  1828. data = JSON.parse(event.data);
  1829. } catch(e) {
  1830. util.log('Invalid server message', event.data);
  1831. return;
  1832. }
  1833. self.emit('message', data);
  1834. };
  1835. // Take care of the queue of connections if necessary and make sure Peer knows
  1836. // socket is open.
  1837. this._socket.onopen = function() {
  1838. if (!!self._timeout) {
  1839. clearTimeout(self._timeout);
  1840. setTimeout(function(){
  1841. self._http.abort();
  1842. self._http = null;
  1843. }, 5000);
  1844. }
  1845. util.log('Socket open');
  1846. };
  1847. };
  1848. /** Start XHR streaming. */
  1849. Socket.prototype._startXhrStream = function(n) {
  1850. try {
  1851. var self = this;
  1852. this._http = new XMLHttpRequest();
  1853. this._http._index = 1;
  1854. this._http._streamIndex = n || 0;
  1855. this._http.open('post', this._httpUrl + '/id?i=' + this._http._streamIndex, true);
  1856. this._http.onreadystatechange = function() {
  1857. if (this.readyState == 2 && !!this.old) {
  1858. this.old.abort();
  1859. delete this.old;
  1860. }
  1861. if (this.readyState > 2 && this.status == 200 && !!this.responseText) {
  1862. self._handleStream(this);
  1863. }
  1864. };
  1865. this._http.send(null);
  1866. this._setHTTPTimeout();
  1867. } catch(e) {
  1868. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  1869. }
  1870. };
  1871. /** Handles onreadystatechange response as a stream. */
  1872. Socket.prototype._handleStream = function(http) {
  1873. // 3 and 4 are loading/done state. All others are not relevant.
  1874. var messages = http.responseText.split('\n');
  1875. // Check to see if anything needs to be processed on buffer.
  1876. if (!!http._buffer) {
  1877. while (http._buffer.length > 0) {
  1878. var index = http._buffer.shift();
  1879. var bufferedMessage = messages[index];
  1880. try {
  1881. bufferedMessage = JSON.parse(bufferedMessage);
  1882. } catch(e) {
  1883. http._buffer.shift(index);
  1884. break;
  1885. }
  1886. this.emit('message', bufferedMessage);
  1887. }
  1888. }
  1889. var message = messages[http._index];
  1890. if (!!message) {
  1891. http._index += 1;
  1892. // Buffering--this message is incomplete and we'll get to it next time.
  1893. // This checks if the httpResponse ended in a `\n`, in which case the last
  1894. // element of messages should be the empty string.
  1895. if (http._index === messages.length) {
  1896. if (!http._buffer) {
  1897. http._buffer = [];
  1898. }
  1899. http._buffer.push(http._index - 1);
  1900. } else {
  1901. try {
  1902. message = JSON.parse(message);
  1903. } catch(e) {
  1904. util.log('Invalid server message', message);
  1905. return;
  1906. }
  1907. this.emit('message', message);
  1908. }
  1909. }
  1910. };
  1911. Socket.prototype._setHTTPTimeout = function() {
  1912. var self = this;
  1913. this._timeout = setTimeout(function() {
  1914. var old = self._http;
  1915. if (!self._wsOpen()) {
  1916. self._startXhrStream(old._streamIndex + 1);
  1917. self._http.old = old;
  1918. } else {
  1919. old.abort();
  1920. }
  1921. }, 25000);
  1922. };
  1923. Socket.prototype._wsOpen = function() {
  1924. return !!this._socket && this._socket.readyState == 1;
  1925. };
  1926. /** Exposed send for DC & Peer. */
  1927. Socket.prototype.send = function(data) {
  1928. if (this.disconnected) {
  1929. return;
  1930. }
  1931. if (!data.type) {
  1932. this.emit('error', 'Invalid message');
  1933. return;
  1934. }
  1935. var message = JSON.stringify(data);
  1936. if (this._wsOpen()) {
  1937. this._socket.send(message);
  1938. } else {
  1939. var http = new XMLHttpRequest();
  1940. var url = this._httpUrl + '/' + data.type.toLowerCase();
  1941. http.open('post', url, true);
  1942. http.setRequestHeader('Content-Type', 'application/json');
  1943. http.send(message);
  1944. }
  1945. };
  1946. Socket.prototype.close = function() {
  1947. if (!this.disconnected && this._wsOpen()) {
  1948. this._socket.close();
  1949. this.disconnected = true;
  1950. }
  1951. };
  1952. })(this);