peer.js 40 KB

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