peer.js 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420
  1. /*! peerjs.js build:0.2.8, 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. /**
  646. * Reliable transfer for Chrome Canary DataChannel impl.
  647. * Author: @michellebu
  648. */
  649. function Reliable(dc, debug) {
  650. if (!(this instanceof Reliable)) return new Reliable(dc);
  651. this._dc = dc;
  652. util.debug = debug;
  653. // Messages sent/received so far.
  654. // id: { ack: n, chunks: [...] }
  655. this._outgoing = {};
  656. // id: { ack: ['ack', id, n], chunks: [...] }
  657. this._incoming = {};
  658. this._received = {};
  659. // Window size.
  660. this._window = 1000;
  661. // MTU.
  662. this._mtu = 500;
  663. // Interval for setInterval. In ms.
  664. this._interval = 0;
  665. // Messages sent.
  666. this._count = 0;
  667. // Outgoing message queue.
  668. this._queue = [];
  669. this._setupDC();
  670. };
  671. // Send a message reliably.
  672. Reliable.prototype.send = function(msg) {
  673. // Determine if chunking is necessary.
  674. var bl = util.pack(msg);
  675. if (bl.size < this._mtu) {
  676. this._handleSend(['no', bl]);
  677. return;
  678. }
  679. this._outgoing[this._count] = {
  680. ack: 0,
  681. chunks: this._chunk(bl)
  682. };
  683. if (util.debug) {
  684. this._outgoing[this._count].timer = new Date();
  685. }
  686. // Send prelim window.
  687. this._sendWindowedChunks(this._count);
  688. this._count += 1;
  689. };
  690. // Set up interval for processing queue.
  691. Reliable.prototype._setupInterval = function() {
  692. // TODO: fail gracefully.
  693. var self = this;
  694. this._timeout = setInterval(function() {
  695. // FIXME: String stuff makes things terribly async.
  696. var msg = self._queue.shift();
  697. if (msg._multiple) {
  698. for (var i = 0, ii = msg.length; i < ii; i += 1) {
  699. self._intervalSend(msg[i]);
  700. }
  701. } else {
  702. self._intervalSend(msg);
  703. }
  704. }, this._interval);
  705. };
  706. Reliable.prototype._intervalSend = function(msg) {
  707. var self = this;
  708. msg = util.pack(msg);
  709. util.blobToBinaryString(msg, function(str) {
  710. self._dc.send(str);
  711. });
  712. if (self._queue.length === 0) {
  713. clearTimeout(self._timeout);
  714. self._timeout = null;
  715. //self._processAcks();
  716. }
  717. };
  718. // Go through ACKs to send missing pieces.
  719. Reliable.prototype._processAcks = function() {
  720. for (var id in this._outgoing) {
  721. if (this._outgoing.hasOwnProperty(id)) {
  722. this._sendWindowedChunks(id);
  723. }
  724. }
  725. };
  726. // Handle sending a message.
  727. // FIXME: Don't wait for interval time for all messages...
  728. Reliable.prototype._handleSend = function(msg) {
  729. var push = true;
  730. for (var i = 0, ii = this._queue.length; i < ii; i += 1) {
  731. var item = this._queue[i];
  732. if (item === msg) {
  733. push = false;
  734. } else if (item._multiple && item.indexOf(msg) !== -1) {
  735. push = false;
  736. }
  737. }
  738. if (push) {
  739. this._queue.push(msg);
  740. if (!this._timeout) {
  741. this._setupInterval();
  742. }
  743. }
  744. };
  745. // Set up DataChannel handlers.
  746. Reliable.prototype._setupDC = function() {
  747. // Handle various message types.
  748. var self = this;
  749. this._dc.onmessage = function(e) {
  750. var msg = e.data;
  751. var datatype = msg.constructor;
  752. // FIXME: msg is String until binary is supported.
  753. // Once that happens, this will have to be smarter.
  754. if (datatype === String) {
  755. var ab = util.binaryStringToArrayBuffer(msg);
  756. msg = util.unpack(ab);
  757. self._handleMessage(msg);
  758. }
  759. };
  760. };
  761. // Handles an incoming message.
  762. Reliable.prototype._handleMessage = function(msg) {
  763. var id = msg[1];
  764. var idata = this._incoming[id];
  765. var odata = this._outgoing[id];
  766. var data;
  767. switch (msg[0]) {
  768. // No chunking was done.
  769. case 'no':
  770. var message = id;
  771. if (!!message) {
  772. this.onmessage(util.unpack(message));
  773. }
  774. break;
  775. // Reached the end of the message.
  776. case 'end':
  777. data = idata;
  778. // In case end comes first.
  779. this._received[id] = msg[2];
  780. if (!data) {
  781. break;
  782. }
  783. this._ack(id);
  784. break;
  785. case 'ack':
  786. data = odata;
  787. if (!!data) {
  788. var ack = msg[2];
  789. // Take the larger ACK, for out of order messages.
  790. data.ack = Math.max(ack, data.ack);
  791. // Clean up when all chunks are ACKed.
  792. if (data.ack >= data.chunks.length) {
  793. util.log('Time: ', new Date() - data.timer);
  794. delete this._outgoing[id];
  795. } else {
  796. this._processAcks();
  797. }
  798. }
  799. // If !data, just ignore.
  800. break;
  801. // Received a chunk of data.
  802. case 'chunk':
  803. // Create a new entry if none exists.
  804. data = idata;
  805. if (!data) {
  806. var end = this._received[id];
  807. if (end === true) {
  808. break;
  809. }
  810. data = {
  811. ack: ['ack', id, 0],
  812. chunks: []
  813. };
  814. this._incoming[id] = data;
  815. }
  816. var n = msg[2];
  817. var chunk = msg[3];
  818. data.chunks[n] = new Uint8Array(chunk);
  819. // If we get the chunk we're looking for, ACK for next missing.
  820. // Otherwise, ACK the same N again.
  821. if (n === data.ack[2]) {
  822. this._calculateNextAck(id);
  823. }
  824. this._ack(id);
  825. break;
  826. default:
  827. // Shouldn't happen, but would make sense for message to just go
  828. // through as is.
  829. this._handleSend(msg);
  830. break;
  831. }
  832. };
  833. // Chunks BL into smaller messages.
  834. Reliable.prototype._chunk = function(bl) {
  835. var chunks = [];
  836. var size = bl.size;
  837. var start = 0;
  838. while (start < size) {
  839. var end = Math.min(size, start + this._mtu);
  840. var b = bl.slice(start, end);
  841. var chunk = {
  842. payload: b
  843. }
  844. chunks.push(chunk);
  845. start = end;
  846. }
  847. util.log('Created', chunks.length, 'chunks.');
  848. return chunks;
  849. };
  850. // Sends ACK N, expecting Nth blob chunk for message ID.
  851. Reliable.prototype._ack = function(id) {
  852. var ack = this._incoming[id].ack;
  853. // if ack is the end value, then call _complete.
  854. if (this._received[id] === ack[2]) {
  855. this._complete(id);
  856. this._received[id] = true;
  857. }
  858. this._handleSend(ack);
  859. };
  860. // Calculates the next ACK number, given chunks.
  861. Reliable.prototype._calculateNextAck = function(id) {
  862. var data = this._incoming[id];
  863. var chunks = data.chunks;
  864. for (var i = 0, ii = chunks.length; i < ii; i += 1) {
  865. // This chunk is missing!!! Better ACK for it.
  866. if (chunks[i] === undefined) {
  867. data.ack[2] = i;
  868. return;
  869. }
  870. }
  871. data.ack[2] = chunks.length;
  872. };
  873. // Sends the next window of chunks.
  874. Reliable.prototype._sendWindowedChunks = function(id) {
  875. util.log('sendWindowedChunks for: ', id);
  876. var data = this._outgoing[id];
  877. var ch = data.chunks;
  878. var chunks = [];
  879. var limit = Math.min(data.ack + this._window, ch.length);
  880. for (var i = data.ack; i < limit; i += 1) {
  881. if (!ch[i].sent || i === data.ack) {
  882. ch[i].sent = true;
  883. chunks.push(['chunk', id, i, ch[i].payload]);
  884. }
  885. }
  886. if (data.ack + this._window >= ch.length) {
  887. chunks.push(['end', id, ch.length])
  888. }
  889. chunks._multiple = true;
  890. this._handleSend(chunks);
  891. };
  892. // Puts together a message from chunks.
  893. Reliable.prototype._complete = function(id) {
  894. util.log('Completed called for', id);
  895. var self = this;
  896. var chunks = this._incoming[id].chunks;
  897. var bl = new Blob(chunks);
  898. util.blobToArrayBuffer(bl, function(ab) {
  899. self.onmessage(util.unpack(ab));
  900. });
  901. delete this._incoming[id];
  902. };
  903. // Ups bandwidth limit on SDP. Meant to be called during offer/answer.
  904. Reliable.higherBandwidthSDP = function(sdp) {
  905. // AS stands for Application-Specific Maximum.
  906. // Bandwidth number is in kilobits / sec.
  907. // See RFC for more info: http://www.ietf.org/rfc/rfc2327.txt
  908. var parts = sdp.split('b=AS:30');
  909. var replace = 'b=AS:102400'; // 100 Mbps
  910. return parts[0] + replace + parts[1];
  911. };
  912. // Overwritten, typically.
  913. Reliable.prototype.onmessage = function(msg) {};
  914. exports.Reliable = Reliable;
  915. exports.RTCSessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription;
  916. exports.RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection || window.RTCPeerConnection;
  917. var defaultConfig = {'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }]};
  918. var util = {
  919. noop: function() {},
  920. CLOUD_HOST: '0.peerjs.com',
  921. CLOUD_PORT: 9000,
  922. // Logging logic
  923. logLevel: 0,
  924. setLogLevel: function(level) {
  925. var debugLevel = parseInt(level, 10);
  926. if (!isNaN(parseInt(level, 10))) {
  927. util.logLevel = debugLevel;
  928. } else {
  929. // If they are using truthy/falsy values for debug
  930. util.logLevel = level ? 3 : 0;
  931. }
  932. util.log = util.warn = util.error = util.noop;
  933. if (util.logLevel > 0) {
  934. util.error = util._printWith('ERROR');
  935. }
  936. if (util.logLevel > 1) {
  937. util.warn = util._printWith('WARNING');
  938. }
  939. if (util.logLevel > 2) {
  940. util.log = util._print;
  941. }
  942. },
  943. setLogFunction: function(fn) {
  944. if (fn.constructor !== Function) {
  945. util.warn('The log function you passed in is not a function. Defaulting to regular logs.');
  946. } else {
  947. util._print = fn;
  948. }
  949. },
  950. _printWith: function(prefix) {
  951. return function() {
  952. var copy = Array.prototype.slice.call(arguments);
  953. copy.unshift(prefix);
  954. util._print.apply(util, copy);
  955. };
  956. },
  957. _print: function () {
  958. var err = false;
  959. var copy = Array.prototype.slice.call(arguments);
  960. copy.unshift('PeerJS: ');
  961. for (var i = 0, l = copy.length; i < l; i++){
  962. if (copy[i] instanceof Error) {
  963. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  964. err = true;
  965. }
  966. }
  967. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  968. },
  969. //
  970. // Returns browser-agnostic default config
  971. defaultConfig: defaultConfig,
  972. //
  973. // Returns the current browser.
  974. browser: (function() {
  975. if (window.mozRTCPeerConnection) {
  976. return 'Firefox';
  977. } else if (window.webkitRTCPeerConnection) {
  978. return 'Chrome';
  979. } else if (window.RTCPeerConnection) {
  980. return 'Supported';
  981. } else {
  982. return 'Unsupported';
  983. }
  984. })(),
  985. //
  986. // Lists which features are supported
  987. supports: (function() {
  988. var data = true;
  989. var audioVideo = true;
  990. var pc, dc;
  991. try {
  992. pc = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  993. } catch (e) {
  994. data = false;
  995. audioVideo = false;
  996. }
  997. if (data) {
  998. try {
  999. dc = pc.createDataChannel('_PEERJSDATATEST');
  1000. } catch (e) {
  1001. data = false;
  1002. }
  1003. }
  1004. // FIXME: not really the best check...
  1005. if (audioVideo) {
  1006. audioVideo = !!pc.addStream;
  1007. }
  1008. pc.close();
  1009. dc.close();
  1010. return {
  1011. audioVideo: audioVideo,
  1012. data: data,
  1013. binary: data && (function() {
  1014. var pc = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  1015. var dc = pc.createDataChannel('_PEERJSBINARYTEST');
  1016. try {
  1017. dc.binaryType = 'blob';
  1018. } catch (e) {
  1019. pc.close();
  1020. if (e.name === 'NotSupportedError') {
  1021. return false
  1022. }
  1023. }
  1024. pc.close();
  1025. dc.close();
  1026. return true;
  1027. })(),
  1028. reliable: data && (function() {
  1029. // Reliable (not RTP).
  1030. var pc = new RTCPeerConnection(defaultConfig, {});
  1031. var dc;
  1032. try {
  1033. dc = pc.createDataChannel('_PEERJSRELIABLETEST', {reliable: true});
  1034. } catch (e) {
  1035. pc.close();
  1036. if (e.name === 'NotSupportedError') {
  1037. return false
  1038. }
  1039. }
  1040. pc.close();
  1041. dc.close();
  1042. return true;
  1043. })(),
  1044. onnegotiationneeded: (data || audioVideo) && (function() {
  1045. var pc = new RTCPeerConnection(defaultConfig, {});
  1046. // sync default check.
  1047. var called = false;
  1048. var pc = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  1049. pc.onnegotiationneeded = function() {
  1050. called = true;
  1051. // async check.
  1052. if (util && util.supports) {
  1053. util.supports.onnegotiationneeded = true;
  1054. }
  1055. };
  1056. // FIXME: this is not great because in theory it doesn't work for
  1057. // av-only browsers (?).
  1058. var dc = pc.createDataChannel('_PEERJSRELIABLETEST');
  1059. pc.close();
  1060. dc.close();
  1061. return called;
  1062. })(),
  1063. // TODO(michelle): whether this browser can interop with a different
  1064. // browser. But the two browsers both have to support interop.
  1065. interop: false
  1066. };
  1067. }()),
  1068. //
  1069. // Ensure alphanumeric ids
  1070. validateId: function(id) {
  1071. // Allow empty ids
  1072. return !id || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id);
  1073. },
  1074. validateKey: function(key) {
  1075. // Allow empty keys
  1076. return !key || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(key);
  1077. },
  1078. debug: false,
  1079. inherits: function(ctor, superCtor) {
  1080. ctor.super_ = superCtor;
  1081. ctor.prototype = Object.create(superCtor.prototype, {
  1082. constructor: {
  1083. value: ctor,
  1084. enumerable: false,
  1085. writable: true,
  1086. configurable: true
  1087. }
  1088. });
  1089. },
  1090. extend: function(dest, source) {
  1091. for(var key in source) {
  1092. if(source.hasOwnProperty(key)) {
  1093. dest[key] = source[key];
  1094. }
  1095. }
  1096. return dest;
  1097. },
  1098. pack: BinaryPack.pack,
  1099. unpack: BinaryPack.unpack,
  1100. log: function () {
  1101. if (util.debug) {
  1102. var err = false;
  1103. var copy = Array.prototype.slice.call(arguments);
  1104. copy.unshift('PeerJS: ');
  1105. for (var i = 0, l = copy.length; i < l; i++){
  1106. if (copy[i] instanceof Error) {
  1107. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  1108. err = true;
  1109. }
  1110. }
  1111. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  1112. }
  1113. },
  1114. setZeroTimeout: (function(global) {
  1115. var timeouts = [];
  1116. var messageName = 'zero-timeout-message';
  1117. // Like setTimeout, but only takes a function argument. There's
  1118. // no time argument (always zero) and no arguments (you have to
  1119. // use a closure).
  1120. function setZeroTimeoutPostMessage(fn) {
  1121. timeouts.push(fn);
  1122. global.postMessage(messageName, '*');
  1123. }
  1124. function handleMessage(event) {
  1125. if (event.source == global && event.data == messageName) {
  1126. if (event.stopPropagation) {
  1127. event.stopPropagation();
  1128. }
  1129. if (timeouts.length) {
  1130. timeouts.shift()();
  1131. }
  1132. }
  1133. }
  1134. if (global.addEventListener) {
  1135. global.addEventListener('message', handleMessage, true);
  1136. } else if (global.attachEvent) {
  1137. global.attachEvent('onmessage', handleMessage);
  1138. }
  1139. return setZeroTimeoutPostMessage;
  1140. }(this)),
  1141. // Binary stuff
  1142. blobToArrayBuffer: function(blob, cb){
  1143. var fr = new FileReader();
  1144. fr.onload = function(evt) {
  1145. cb(evt.target.result);
  1146. };
  1147. fr.readAsArrayBuffer(blob);
  1148. },
  1149. blobToBinaryString: function(blob, cb){
  1150. var fr = new FileReader();
  1151. fr.onload = function(evt) {
  1152. cb(evt.target.result);
  1153. };
  1154. fr.readAsBinaryString(blob);
  1155. },
  1156. binaryStringToArrayBuffer: function(binary) {
  1157. var byteArray = new Uint8Array(binary.length);
  1158. for (var i = 0; i < binary.length; i++) {
  1159. byteArray[i] = binary.charCodeAt(i) & 0xff;
  1160. }
  1161. return byteArray.buffer;
  1162. },
  1163. randomToken: function () {
  1164. return Math.random().toString(36).substr(2);
  1165. },
  1166. //
  1167. isSecure: function() {
  1168. return location.protocol === 'https:';
  1169. }
  1170. };
  1171. exports.util = util;
  1172. /**
  1173. * A peer who can initiate connections with other peers.
  1174. */
  1175. function Peer(id, options) {
  1176. if (!(this instanceof Peer)) return new Peer(id, options);
  1177. EventEmitter.call(this);
  1178. // Deal with overloading
  1179. if (id && id.constructor == Object) {
  1180. options = id;
  1181. id = undefined;
  1182. } else if (id) {
  1183. // Ensure id is a string
  1184. id = id.toString();
  1185. }
  1186. //
  1187. // Configurize options
  1188. options = util.extend({
  1189. debug: 0, // 1: Errors, 2: Warnings, 3: All logs
  1190. host: util.CLOUD_HOST,
  1191. port: util.CLOUD_PORT,
  1192. key: 'peerjs',
  1193. config: util.defaultConfig
  1194. }, options);
  1195. this.options = options;
  1196. // Detect relative URL host.
  1197. if (options.host === '/') {
  1198. options.host = window.location.hostname;
  1199. }
  1200. // Set whether we use SSL to same as current host
  1201. if (options.secure === undefined && options.host !== util.CLOUD_HOST) {
  1202. options.secure = util.isSecure();
  1203. }
  1204. // Set a custom log function if present
  1205. if (options.logFunction) {
  1206. util.setLogFunction(options.logFunction);
  1207. }
  1208. util.setLogLevel(options.debug);
  1209. //
  1210. // Sanity checks
  1211. // Ensure WebRTC supported
  1212. if (!util.supports.audioVideo && !util.supports.data ) {
  1213. this._delayedAbort('browser-incompatible', 'The current browser does not support WebRTC');
  1214. return;
  1215. }
  1216. // Ensure alphanumeric id
  1217. if (!util.validateId(id)) {
  1218. this._delayedAbort('invalid-id', 'ID "' + id + '" is invalid');
  1219. return;
  1220. }
  1221. // Ensure valid key
  1222. if (!util.validateKey(options.key)) {
  1223. this._delayedAbort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  1224. return;
  1225. }
  1226. // Ensure not using unsecure cloud server on SSL page
  1227. if (options.secure && options.host === '0.peerjs.com') {
  1228. this._delayedAbort('ssl-unavailable',
  1229. 'The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS.');
  1230. return;
  1231. }
  1232. //
  1233. // States.
  1234. this.destroyed = false; // Connections have been killed
  1235. this.disconnected = false; // Connection to PeerServer killed manually but P2P connections still active
  1236. this.open = false; // Sockets and such are not yet open.
  1237. //
  1238. // References
  1239. this.connections = {}; // DataConnections for this peer.
  1240. this._lostMessages = {}; // src => [list of messages]
  1241. //
  1242. // Initialize the 'socket' (which is actually a mix of XHR streaming and
  1243. // websockets.)
  1244. var self = this;
  1245. this.socket = new Socket(this.options.secure, this.options.host, this.options.port, this.options.key);
  1246. this.socket.on('message', function(data) {
  1247. self._handleMessage(data);
  1248. });
  1249. this.socket.on('error', function(error) {
  1250. self._abort('socket-error', error);
  1251. });
  1252. this.socket.on('close', function() {
  1253. if (!self.disconnected) { // If we haven't explicitly disconnected, emit error.
  1254. self._abort('socket-closed', 'Underlying socket is already closed.');
  1255. }
  1256. });
  1257. //
  1258. // Start the connections
  1259. if (id) {
  1260. this._initialize(id);
  1261. } else {
  1262. this._retrieveId();
  1263. }
  1264. //
  1265. };
  1266. util.inherits(Peer, EventEmitter);
  1267. /** Get a unique ID from the server via XHR. */
  1268. Peer.prototype._retrieveId = function(cb) {
  1269. var self = this;
  1270. var http = new XMLHttpRequest();
  1271. var protocol = this.options.secure ? 'https://' : 'http://';
  1272. var url = protocol + this.options.host + ':' + this.options.port + '/' + this.options.key + '/id';
  1273. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  1274. url += queryString;
  1275. // If there's no ID we need to wait for one before trying to init socket.
  1276. http.open('get', url, true);
  1277. http.onerror = function(e) {
  1278. util.error('Error retrieving ID', e);
  1279. self._abort('server-error', 'Could not get an ID from the server');
  1280. }
  1281. http.onreadystatechange = function() {
  1282. if (http.readyState !== 4) {
  1283. return;
  1284. }
  1285. if (http.status !== 200) {
  1286. http.onerror();
  1287. return;
  1288. }
  1289. self._initialize(http.responseText);
  1290. };
  1291. http.send(null);
  1292. };
  1293. /** Initialize a connection with the server. */
  1294. Peer.prototype._initialize = function(id) {
  1295. var self = this;
  1296. this.id = id;
  1297. this.socket.start(this.id);
  1298. }
  1299. /** Handles messages from the server. */
  1300. Peer.prototype._handleMessage = function(message) {
  1301. var type = message.type;
  1302. var payload = message.payload;
  1303. var peer = message.src;
  1304. switch (type) {
  1305. case 'OPEN': // The connection to the server is open.
  1306. this.emit('open', this.id);
  1307. this.open = true;
  1308. break;
  1309. case 'ERROR': // Server error.
  1310. this._abort('server-error', payload.msg);
  1311. break;
  1312. case 'ID-TAKEN': // The selected ID is taken.
  1313. this._abort('unavailable-id', 'ID `' + this.id + '` is taken');
  1314. break;
  1315. case 'INVALID-KEY': // The given API key cannot be found.
  1316. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  1317. break;
  1318. //
  1319. case 'LEAVE': // Another peer has closed its connection to this peer.
  1320. util.log('Received leave message from', peer);
  1321. this._cleanupPeer(peer);
  1322. break;
  1323. case 'EXPIRE': // The offer sent to a peer has expired without response.
  1324. this.emit('error', new Error('Could not connect to peer ' + peer));
  1325. break;
  1326. case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  1327. var connectionId = payload.connectionId;
  1328. var connection = this.getConnection(peer, connectionId);
  1329. if (connection) {
  1330. util.warn('Offer received for existing Connection ID:', connectionId);
  1331. //connection.handleMessage(message);
  1332. } else {
  1333. // Create a new connection.
  1334. if (payload.type === 'media') {
  1335. var connection = new MediaConnection(peer, this, {
  1336. connectionId: connectionId,
  1337. _payload: payload,
  1338. metadata: payload.metadata,
  1339. });
  1340. this._addConnection(peer, connection);
  1341. this.emit('call', connection);
  1342. } else if (payload.type === 'data') {
  1343. connection = new DataConnection(peer, this, {
  1344. connectionId: connectionId,
  1345. _payload: payload,
  1346. metadata: payload.metadata,
  1347. label: payload.label,
  1348. serialization: payload.serialization,
  1349. reliable: payload.reliable
  1350. });
  1351. this._addConnection(peer, connection);
  1352. this.emit('connection', connection);
  1353. } else {
  1354. util.warn('Received malformed connection type:', payload.type);
  1355. return;
  1356. }
  1357. // Find messages.
  1358. var messages = this._getMessages(connectionId);
  1359. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  1360. connection.handleMessage(messages[i]);
  1361. }
  1362. }
  1363. break;
  1364. default:
  1365. if (!payload) {
  1366. util.warn('You received a malformed message from ' + peer + ' of type ' + type);
  1367. return;
  1368. }
  1369. var id = payload.connectionId;
  1370. var connection = this.getConnection(peer, id);
  1371. if (connection && connection.pc) {
  1372. // Pass it on.
  1373. connection.handleMessage(message);
  1374. } else if (id) {
  1375. // Store for possible later use
  1376. this._storeMessage(id, message);
  1377. } else {
  1378. util.warn('You received an unrecognized message:', message);
  1379. }
  1380. break;
  1381. }
  1382. }
  1383. /** Stores messages without a set up connection, to be claimed later. */
  1384. Peer.prototype._storeMessage = function(connectionId, message) {
  1385. if (!this._lostMessages[connectionId]) {
  1386. this._lostMessages[connectionId] = [];
  1387. }
  1388. this._lostMessages[connectionId].push(message);
  1389. }
  1390. /** Retrieve messages from lost message store */
  1391. Peer.prototype._getMessages = function(connectionId) {
  1392. var messages = this._lostMessages[connectionId];
  1393. if (messages) {
  1394. delete this._lostMessages[connectionId];
  1395. return messages;
  1396. } else {
  1397. return [];
  1398. }
  1399. }
  1400. /**
  1401. * Returns a DataConnection to the specified peer. See documentation for a
  1402. * complete list of options.
  1403. */
  1404. Peer.prototype.connect = function(peer, options) {
  1405. if (this.disconnected) {
  1406. util.warn('You cannot connect to a new Peer because you called '
  1407. + '.disconnect() on this Peer and ended your connection with the'
  1408. + ' server. You can create a new Peer to reconnect.');
  1409. this.emit('error', new Error('Cannot connect to new Peer after disconnecting from server.'));
  1410. return;
  1411. }
  1412. var connection = new DataConnection(peer, this, options);
  1413. this._addConnection(peer, connection);
  1414. return connection;
  1415. }
  1416. /**
  1417. * Returns a MediaConnection to the specified peer. See documentation for a
  1418. * complete list of options.
  1419. */
  1420. Peer.prototype.call = function(peer, stream, options) {
  1421. if (this.disconnected) {
  1422. util.warn('You cannot connect to a new Peer because you called '
  1423. + '.disconnect() on this Peer and ended your connection with the'
  1424. + ' server. You can create a new Peer to reconnect.');
  1425. this.emit('error', new Error('Cannot connect to new Peer after disconnecting from server.'));
  1426. return;
  1427. }
  1428. if (!stream) {
  1429. util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.');
  1430. return;
  1431. }
  1432. options = options || {};
  1433. options._stream = stream;
  1434. var call = new MediaConnection(peer, this, options);
  1435. this._addConnection(peer, call);
  1436. return call;
  1437. }
  1438. /** Add a data/media connection to this peer. */
  1439. Peer.prototype._addConnection = function(peer, connection) {
  1440. if (!this.connections[peer]) {
  1441. this.connections[peer] = [];
  1442. }
  1443. this.connections[peer].push(connection);
  1444. }
  1445. /** Retrieve a data/media connection for this peer. */
  1446. Peer.prototype.getConnection = function(peer, id) {
  1447. var connections = this.connections[peer];
  1448. if (!connections) {
  1449. return null;
  1450. }
  1451. for (var i = 0, ii = connections.length; i < ii; i++) {
  1452. if (connections[i].id === id) {
  1453. return connections[i];
  1454. }
  1455. }
  1456. return null;
  1457. }
  1458. Peer.prototype._delayedAbort = function(type, message) {
  1459. var self = this;
  1460. util.setZeroTimeout(function(){
  1461. self._abort(type, message);
  1462. });
  1463. }
  1464. /** Destroys the Peer and emits an error message. */
  1465. Peer.prototype._abort = function(type, message) {
  1466. util.error('Aborting. Error:', message);
  1467. var err = new Error(message);
  1468. err.type = type;
  1469. this.destroy();
  1470. this.emit('error', err);
  1471. };
  1472. /**
  1473. * Destroys the Peer: closes all active connections as well as the connection
  1474. * to the server.
  1475. * Warning: The peer can no longer create or accept connections after being
  1476. * destroyed.
  1477. */
  1478. Peer.prototype.destroy = function() {
  1479. if (!this.destroyed) {
  1480. this._cleanup();
  1481. this.disconnect();
  1482. this.destroyed = true;
  1483. }
  1484. }
  1485. /** Disconnects every connection on this peer. */
  1486. Peer.prototype._cleanup = function() {
  1487. var peers = Object.keys(this.connections);
  1488. for (var i = 0, ii = peers.length; i < ii; i++) {
  1489. this._cleanupPeer(peers[i]);
  1490. }
  1491. this.emit('close');
  1492. }
  1493. /** Closes all connections to this peer. */
  1494. Peer.prototype._cleanupPeer = function(peer) {
  1495. var connections = this.connections[peer];
  1496. for (var j = 0, jj = connections.length; j < jj; j += 1) {
  1497. connections[j].close();
  1498. }
  1499. }
  1500. /**
  1501. * Disconnects the Peer's connection to the PeerServer. Does not close any
  1502. * active connections.
  1503. * Warning: The peer can no longer create or accept connections after being
  1504. * disconnected. It also cannot reconnect to the server.
  1505. */
  1506. Peer.prototype.disconnect = function() {
  1507. var self = this;
  1508. util.setZeroTimeout(function(){
  1509. if (!self.disconnected) {
  1510. self.disconnected = true;
  1511. self.open = false;
  1512. if (self.socket) {
  1513. self.socket.close();
  1514. }
  1515. self.id = null;
  1516. }
  1517. });
  1518. }
  1519. exports.Peer = Peer;
  1520. /**
  1521. * Wraps a DataChannel between two Peers.
  1522. */
  1523. function DataConnection(peer, provider, options) {
  1524. if (!(this instanceof DataConnection)) return new DataConnection(peer, provider, options);
  1525. EventEmitter.call(this);
  1526. // TODO: perhaps default serialization should be binary-utf8?
  1527. this.options = util.extend({
  1528. serialization: 'binary'
  1529. }, options);
  1530. // Connection is not open yet.
  1531. this.open = false;
  1532. this.type = 'data';
  1533. this.peer = peer;
  1534. this.provider = provider;
  1535. this.id = this.options.connectionId || DataConnection._idPrefix + util.randomToken();
  1536. this.label = this.options.label || this.id;
  1537. this.metadata = this.options.metadata;
  1538. this.serialization = this.options.serialization;
  1539. this.reliable = this.options.reliable;
  1540. Negotiator.startConnection(
  1541. this,
  1542. this.options._payload || {
  1543. originator: true
  1544. }
  1545. );
  1546. }
  1547. util.inherits(DataConnection, EventEmitter);
  1548. DataConnection._idPrefix = 'dc_';
  1549. /** Called by the Negotiator when the DataChannel is ready. */
  1550. DataConnection.prototype.initialize = function(dc) {
  1551. this._dc = dc;
  1552. this._configureDataChannel();
  1553. }
  1554. DataConnection.prototype._configureDataChannel = function() {
  1555. var self = this;
  1556. if (util.supports.binary) {
  1557. // Webkit doesn't support binary yet
  1558. this._dc.binaryType = 'arraybuffer';
  1559. }
  1560. this._dc.onopen = function() {
  1561. util.log('Data channel connection success');
  1562. self.open = true;
  1563. self.emit('open');
  1564. }
  1565. // Use the Reliable shim for non Firefox browsers
  1566. if (!util.supports.reliable) {
  1567. this._reliable = new Reliable(this._dc, util.debug);
  1568. }
  1569. if (this._reliable) {
  1570. this._reliable.onmessage = function(msg) {
  1571. self.emit('data', msg);
  1572. };
  1573. } else {
  1574. this._dc.onmessage = function(e) {
  1575. self._handleDataMessage(e);
  1576. };
  1577. }
  1578. this._dc.onclose = function(e) {
  1579. util.log('DataChannel closed for:', self.peer);
  1580. self.close();
  1581. };
  1582. }
  1583. // Handles a DataChannel message.
  1584. DataConnection.prototype._handleDataMessage = function(e) {
  1585. var self = this;
  1586. var data = e.data;
  1587. var datatype = data.constructor;
  1588. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  1589. if (datatype === Blob) {
  1590. // Datatype should never be blob
  1591. util.blobToArrayBuffer(data, function(ab) {
  1592. data = util.unpack(ab);
  1593. self.emit('data', data);
  1594. });
  1595. return;
  1596. } else if (datatype === ArrayBuffer) {
  1597. data = util.unpack(data);
  1598. } else if (datatype === String) {
  1599. // String fallback for binary data for browsers that don't support binary yet
  1600. var ab = util.binaryStringToArrayBuffer(data);
  1601. data = util.unpack(ab);
  1602. }
  1603. } else if (this.serialization === 'json') {
  1604. data = JSON.parse(data);
  1605. }
  1606. this.emit('data', data);
  1607. }
  1608. /**
  1609. * Exposed functionality for users.
  1610. */
  1611. /** Allows user to close connection. */
  1612. DataConnection.prototype.close = function() {
  1613. if (!this.open) {
  1614. return;
  1615. }
  1616. this.open = false;
  1617. Negotiator.cleanup(this);
  1618. this.emit('close');
  1619. }
  1620. /** Allows user to send data. */
  1621. DataConnection.prototype.send = function(data) {
  1622. if (!this.open) {
  1623. this.emit('error', new Error('Connection is not open. You should listen for the `open` event before sending messages.'));
  1624. }
  1625. if (this._reliable) {
  1626. // Note: reliable shim sending will make it so that you cannot customize
  1627. // serialization.
  1628. this._reliable.send(data);
  1629. return;
  1630. }
  1631. var self = this;
  1632. if (this.serialization === 'json') {
  1633. this._dc.send(JSON.stringify(data));
  1634. } else if ('binary-utf8'.indexOf(this.serialization) !== -1) {
  1635. var utf8 = (this.serialization === 'binary-utf8');
  1636. var blob = util.pack(data, utf8);
  1637. // DataChannel currently only supports strings.
  1638. if (!util.supports.binary) {
  1639. util.blobToBinaryString(blob, function(str){
  1640. self._dc.send(str);
  1641. });
  1642. } else {
  1643. this._dc.send(blob);
  1644. }
  1645. } else {
  1646. this._dc.send(data);
  1647. }
  1648. }
  1649. DataConnection.prototype.handleMessage = function(message) {
  1650. var payload = message.payload;
  1651. switch (message.type) {
  1652. case 'ANSWER':
  1653. // Forward to negotiator
  1654. Negotiator.handleSDP(message.type, this, payload.sdp);
  1655. break;
  1656. case 'CANDIDATE':
  1657. Negotiator.handleCandidate(this, payload.candidate);
  1658. break;
  1659. default:
  1660. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  1661. break;
  1662. }
  1663. }
  1664. /**
  1665. * Wraps the streaming interface between two Peers.
  1666. */
  1667. function MediaConnection(peer, provider, options) {
  1668. if (!(this instanceof MediaConnection)) return new MediaConnection(peer, provider, options);
  1669. EventEmitter.call(this);
  1670. this.options = util.extend({}, options);
  1671. this.open = false;
  1672. this.type = 'media';
  1673. this.peer = peer;
  1674. this.provider = provider;
  1675. this.metadata = this.options.metadata;
  1676. this.localStream = this.options._stream;
  1677. this.id = this.options.connectionId || MediaConnection._idPrefix + util.randomToken();
  1678. if (this.localStream) {
  1679. Negotiator.startConnection(
  1680. this,
  1681. {_stream: this.localStream, originator: true}
  1682. );
  1683. }
  1684. };
  1685. util.inherits(MediaConnection, EventEmitter);
  1686. MediaConnection._idPrefix = 'mc_';
  1687. MediaConnection.prototype.addStream = function(remoteStream) {
  1688. util.log('Receiving stream', remoteStream);
  1689. this.remoteStream = remoteStream;
  1690. this.emit('stream', remoteStream); // Should we call this `open`?
  1691. };
  1692. MediaConnection.prototype.handleMessage = function(message) {
  1693. var payload = message.payload;
  1694. switch (message.type) {
  1695. case 'ANSWER':
  1696. // Forward to negotiator
  1697. Negotiator.handleSDP(message.type, this, payload.sdp);
  1698. this.open = true;
  1699. break;
  1700. case 'CANDIDATE':
  1701. Negotiator.handleCandidate(this, payload.candidate);
  1702. break;
  1703. default:
  1704. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  1705. break;
  1706. }
  1707. }
  1708. MediaConnection.prototype.answer = function(stream) {
  1709. if (this.localStream) {
  1710. util.warn('Local stream already exists on this MediaConnection. Are you answering a call twice?');
  1711. return;
  1712. }
  1713. this.options._payload._stream = stream;
  1714. this.localStream = stream;
  1715. Negotiator.startConnection(
  1716. this,
  1717. this.options._payload
  1718. )
  1719. // Retrieve lost messages stored because PeerConnection not set up.
  1720. var messages = this.provider._getMessages(this.id);
  1721. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  1722. this.handleMessage(messages[i]);
  1723. }
  1724. this.open = true;
  1725. };
  1726. /**
  1727. * Exposed functionality for users.
  1728. */
  1729. /** Allows user to close connection. */
  1730. MediaConnection.prototype.close = function() {
  1731. if (!this.open) {
  1732. return;
  1733. }
  1734. this.open = false;
  1735. Negotiator.cleanup(this);
  1736. this.emit('close')
  1737. };
  1738. /**
  1739. * Manages all negotiations between Peers.
  1740. */
  1741. var Negotiator = {
  1742. pcs: {
  1743. data: {},
  1744. media: {}
  1745. }, // type => {peerId: {pc_id: pc}}.
  1746. //providers: {}, // provider's id => providers (there may be multiple providers/client.
  1747. queue: [] // connections that are delayed due to a PC being in use.
  1748. }
  1749. Negotiator._idPrefix = 'pc_';
  1750. /** Returns a PeerConnection object set up correctly (for data, media). */
  1751. Negotiator.startConnection = function(connection, options) {
  1752. var pc = Negotiator._getPeerConnection(connection, options);
  1753. if (connection.type === 'media' && options._stream) {
  1754. // Add the stream.
  1755. pc.addStream(options._stream);
  1756. }
  1757. // Set the connection's PC.
  1758. connection.pc = pc;
  1759. // What do we need to do now?
  1760. if (options.originator) {
  1761. if (connection.type === 'data') {
  1762. // Create the datachannel.
  1763. var dc = pc.createDataChannel(connection.label, {reliable: options.reliable});
  1764. connection.initialize(dc);
  1765. }
  1766. if (!util.supports.onnegotiationneeded) {
  1767. Negotiator._makeOffer(connection);
  1768. }
  1769. } else {
  1770. Negotiator.handleSDP('OFFER', connection, options.sdp);
  1771. }
  1772. }
  1773. Negotiator._getPeerConnection = function(connection, options) {
  1774. if (!Negotiator.pcs[connection.type]) {
  1775. util.error(connection.type + ' is not a valid connection type. Maybe you overrode the `type` property somewhere.');
  1776. }
  1777. if (!Negotiator.pcs[connection.type][connection.peer]) {
  1778. Negotiator.pcs[connection.type][connection.peer] = {};
  1779. }
  1780. var peerConnections = Negotiator.pcs[connection.type][connection.peer];
  1781. var pc;
  1782. // Not multiplexing while FF and Chrome have not-great support for it.
  1783. /*if (options.multiplex) {
  1784. ids = Object.keys(peerConnections);
  1785. for (var i = 0, ii = ids.length; i < ii; i += 1) {
  1786. pc = peerConnections[ids[i]];
  1787. if (pc.signalingState === 'stable') {
  1788. break; // We can go ahead and use this PC.
  1789. }
  1790. }
  1791. } else */
  1792. if (options.pc) { // Simplest case: PC id already provided for us.
  1793. pc = Negotiator.pcs[connection.type][connection.peer][options.pc];
  1794. }
  1795. if (!pc || pc.signalingState !== 'stable') {
  1796. pc = Negotiator._startPeerConnection(connection);
  1797. }
  1798. return pc;
  1799. }
  1800. /*
  1801. Negotiator._addProvider = function(provider) {
  1802. if ((!provider.id && !provider.disconnected) || !provider.socket.open) {
  1803. // Wait for provider to obtain an ID.
  1804. provider.on('open', function(id) {
  1805. Negotiator._addProvider(provider);
  1806. });
  1807. } else {
  1808. Negotiator.providers[provider.id] = provider;
  1809. }
  1810. }*/
  1811. /** Start a PC. */
  1812. Negotiator._startPeerConnection = function(connection) {
  1813. util.log('Creating RTCPeerConnection.');
  1814. var id = Negotiator._idPrefix + util.randomToken();
  1815. var optional = {};
  1816. if (connection.type === 'data' && !util.supports.reliable) {
  1817. optional = {optional: [{RtpDataChannels: true}]};
  1818. } else if (connection.type === 'media') {
  1819. // Interop req for chrome.
  1820. optional = {optional: [{DtlsSrtpKeyAgreement: true}]};
  1821. }
  1822. pc = new RTCPeerConnection(connection.provider.options.config, optional);
  1823. Negotiator.pcs[connection.type][connection.peer][id] = pc;
  1824. Negotiator._setupListeners(connection, pc, id);
  1825. return pc;
  1826. }
  1827. /** Set up various WebRTC listeners. */
  1828. Negotiator._setupListeners = function(connection, pc, pc_id) {
  1829. var peerId = connection.peer;
  1830. var connectionId = connection.id;
  1831. var provider = connection.provider;
  1832. // ICE CANDIDATES.
  1833. util.log('Listening for ICE candidates.');
  1834. pc.onicecandidate = function(evt) {
  1835. if (evt.candidate) {
  1836. util.log('Received ICE candidates for:', connection.peer);
  1837. provider.socket.send({
  1838. type: 'CANDIDATE',
  1839. payload: {
  1840. candidate: evt.candidate,
  1841. type: connection.type,
  1842. connectionId: connection.id
  1843. },
  1844. dst: peerId,
  1845. });
  1846. }
  1847. };
  1848. pc.oniceconnectionstatechange = function() {
  1849. switch (pc.iceConnectionState) {
  1850. case 'disconnected':
  1851. case 'failed':
  1852. util.log('iceConnectionState is disconnected, closing connections to ' + peerId);
  1853. connection.close();
  1854. break;
  1855. case 'completed':
  1856. pc.onicecandidate = util.noop;
  1857. break;
  1858. }
  1859. };
  1860. // Fallback for older Chrome impls.
  1861. pc.onicechange = pc.oniceconnectionstatechange;
  1862. // ONNEGOTIATIONNEEDED (Chrome)
  1863. util.log('Listening for `negotiationneeded`');
  1864. pc.onnegotiationneeded = function() {
  1865. util.log('`negotiationneeded` triggered');
  1866. if (pc.signalingState == 'stable') {
  1867. Negotiator._makeOffer(connection);
  1868. } else {
  1869. util.log('onnegotiationneeded triggered when not stable. Is another connection being established?');
  1870. }
  1871. };
  1872. // DATACONNECTION.
  1873. util.log('Listening for data channel');
  1874. // Fired between offer and answer, so options should already be saved
  1875. // in the options hash.
  1876. pc.ondatachannel = function(evt) {
  1877. util.log('Received data channel');
  1878. var dc = evt.channel;
  1879. var connection = provider.getConnection(peerId, connectionId);
  1880. connection.initialize(dc);
  1881. };
  1882. // MEDIACONNECTION.
  1883. util.log('Listening for remote stream');
  1884. pc.onaddstream = function(evt) {
  1885. util.log('Received remote stream');
  1886. var stream = evt.stream;
  1887. provider.getConnection(peerId, connectionId).addStream(stream);
  1888. };
  1889. }
  1890. Negotiator.cleanup = function(connection) {
  1891. util.log('Cleaning up PeerConnection to ' + connection.peer);
  1892. var pc = connection.pc;
  1893. if (!!pc && (pc.readyState !== 'closed' || pc.signalingState !== 'closed')) {
  1894. pc.close();
  1895. connection.pc = null;
  1896. }
  1897. }
  1898. Negotiator._makeOffer = function(connection) {
  1899. var pc = connection.pc;
  1900. pc.createOffer(function(offer) {
  1901. util.log('Created offer.');
  1902. if (!util.supports.reliable && connection.type === 'data') {
  1903. offer.sdp = Reliable.higherBandwidthSDP(offer.sdp);
  1904. }
  1905. pc.setLocalDescription(offer, function() {
  1906. util.log('Set localDescription: offer', 'for:', connection.peer);
  1907. connection.provider.socket.send({
  1908. type: 'OFFER',
  1909. payload: {
  1910. sdp: offer,
  1911. type: connection.type,
  1912. label: connection.label,
  1913. reliable: connection.reliable,
  1914. serialization: connection.serialization,
  1915. metadata: connection.metadata,
  1916. connectionId: connection.id
  1917. },
  1918. dst: connection.peer,
  1919. });
  1920. }, function(err) {
  1921. connection.provider.emit('error', err);
  1922. util.log('Failed to setLocalDescription, ', err);
  1923. });
  1924. }, function(err) {
  1925. connection.provider.emit('error', err);
  1926. util.log('Failed to createOffer, ', err);
  1927. }, connection.options.constraints);
  1928. }
  1929. Negotiator._makeAnswer = function(connection) {
  1930. var pc = connection.pc;
  1931. pc.createAnswer(function(answer) {
  1932. util.log('Created answer.');
  1933. if (!util.supports.reliable && connection.type === 'data') {
  1934. answer.sdp = Reliable.higherBandwidthSDP(answer.sdp);
  1935. }
  1936. pc.setLocalDescription(answer, function() {
  1937. util.log('Set localDescription: answer', 'for:', connection.peer);
  1938. connection.provider.socket.send({
  1939. type: 'ANSWER',
  1940. payload: {
  1941. sdp: answer,
  1942. type: connection.type,
  1943. connectionId: connection.id
  1944. },
  1945. dst: connection.peer
  1946. });
  1947. }, function(err) {
  1948. connection.provider.emit('error', err);
  1949. util.log('Failed to setLocalDescription, ', err);
  1950. });
  1951. }, function(err) {
  1952. connection.provider.emit('error', err);
  1953. util.log('Failed to create answer, ', err);
  1954. });
  1955. }
  1956. /** Handle an SDP. */
  1957. Negotiator.handleSDP = function(type, connection, sdp) {
  1958. sdp = new RTCSessionDescription(sdp);
  1959. var pc = connection.pc;
  1960. util.log('Setting remote description', sdp);
  1961. pc.setRemoteDescription(sdp, function() {
  1962. util.log('Set remoteDescription:', type, 'for:', connection.peer);
  1963. if (type === 'OFFER') {
  1964. Negotiator._makeAnswer(connection);
  1965. }
  1966. }, function(err) {
  1967. connection.provider.emit('error', err);
  1968. util.log('Failed to setRemoteDescription, ', err);
  1969. });
  1970. }
  1971. /** Handle a candidate. */
  1972. Negotiator.handleCandidate = function(connection, candidate) {
  1973. var candidate = new RTCIceCandidate(candidate);
  1974. connection.pc.addIceCandidate(candidate);
  1975. util.log('Added ICE candidate for:', connection.peer);
  1976. }
  1977. /**
  1978. * An abstraction on top of WebSockets and XHR streaming to provide fastest
  1979. * possible connection for peers.
  1980. */
  1981. function Socket(secure, host, port, key) {
  1982. if (!(this instanceof Socket)) return new Socket(secure, host, port, key);
  1983. EventEmitter.call(this);
  1984. // Disconnected manually.
  1985. this.disconnected = false;
  1986. this._queue = [];
  1987. var httpProtocol = secure ? 'https://' : 'http://';
  1988. var wsProtocol = secure ? 'wss://' : 'ws://';
  1989. this._httpUrl = httpProtocol + host + ':' + port + '/' + key;
  1990. this._wsUrl = wsProtocol + host + ':' + port + '/peerjs?key=' + key;
  1991. }
  1992. util.inherits(Socket, EventEmitter);
  1993. /** Check in with ID or get one from server. */
  1994. Socket.prototype.start = function(id) {
  1995. this.id = id;
  1996. var token = util.randomToken();
  1997. this._httpUrl += '/' + id + '/' + token;
  1998. this._wsUrl += '&id='+id+'&token='+token;
  1999. this._startXhrStream();
  2000. this._startWebSocket();
  2001. }
  2002. /** Start up websocket communications. */
  2003. Socket.prototype._startWebSocket = function(id) {
  2004. var self = this;
  2005. if (this._socket) {
  2006. return;
  2007. }
  2008. this._socket = new WebSocket(this._wsUrl);
  2009. this._socket.onmessage = function(event) {
  2010. var data;
  2011. try {
  2012. data = JSON.parse(event.data);
  2013. } catch(e) {
  2014. util.log('Invalid server message', event.data);
  2015. return;
  2016. }
  2017. self.emit('message', data);
  2018. };
  2019. // Take care of the queue of connections if necessary and make sure Peer knows
  2020. // socket is open.
  2021. this._socket.onopen = function() {
  2022. if (self._timeout) {
  2023. clearTimeout(self._timeout);
  2024. setTimeout(function(){
  2025. self._http.abort();
  2026. self._http = null;
  2027. }, 5000);
  2028. }
  2029. self._sendQueuedMessages();
  2030. util.log('Socket open');
  2031. };
  2032. }
  2033. /** Start XHR streaming. */
  2034. Socket.prototype._startXhrStream = function(n) {
  2035. try {
  2036. var self = this;
  2037. this._http = new XMLHttpRequest();
  2038. this._http._index = 1;
  2039. this._http._streamIndex = n || 0;
  2040. this._http.open('post', this._httpUrl + '/id?i=' + this._http._streamIndex, true);
  2041. this._http.onreadystatechange = function() {
  2042. if (this.readyState == 2 && this.old) {
  2043. this.old.abort();
  2044. delete this.old;
  2045. }
  2046. if (this.readyState > 2 && this.status == 200 && this.responseText) {
  2047. self._handleStream(this);
  2048. }
  2049. };
  2050. this._http.send(null);
  2051. this._setHTTPTimeout();
  2052. } catch(e) {
  2053. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  2054. }
  2055. }
  2056. /** Handles onreadystatechange response as a stream. */
  2057. Socket.prototype._handleStream = function(http) {
  2058. // 3 and 4 are loading/done state. All others are not relevant.
  2059. var messages = http.responseText.split('\n');
  2060. // Check to see if anything needs to be processed on buffer.
  2061. if (http._buffer) {
  2062. while (http._buffer.length > 0) {
  2063. var index = http._buffer.shift();
  2064. var bufferedMessage = messages[index];
  2065. try {
  2066. bufferedMessage = JSON.parse(bufferedMessage);
  2067. } catch(e) {
  2068. http._buffer.shift(index);
  2069. break;
  2070. }
  2071. this.emit('message', bufferedMessage);
  2072. }
  2073. }
  2074. var message = messages[http._index];
  2075. if (message) {
  2076. http._index += 1;
  2077. // Buffering--this message is incomplete and we'll get to it next time.
  2078. // This checks if the httpResponse ended in a `\n`, in which case the last
  2079. // element of messages should be the empty string.
  2080. if (http._index === messages.length) {
  2081. if (!http._buffer) {
  2082. http._buffer = [];
  2083. }
  2084. http._buffer.push(http._index - 1);
  2085. } else {
  2086. try {
  2087. message = JSON.parse(message);
  2088. } catch(e) {
  2089. util.log('Invalid server message', message);
  2090. return;
  2091. }
  2092. this.emit('message', message);
  2093. }
  2094. }
  2095. }
  2096. Socket.prototype._setHTTPTimeout = function() {
  2097. var self = this;
  2098. this._timeout = setTimeout(function() {
  2099. var old = self._http;
  2100. if (!self._wsOpen()) {
  2101. self._startXhrStream(old._streamIndex + 1);
  2102. self._http.old = old;
  2103. } else {
  2104. old.abort();
  2105. }
  2106. }, 25000);
  2107. }
  2108. /** Is the websocket currently open? */
  2109. Socket.prototype._wsOpen = function() {
  2110. return this._socket && this._socket.readyState == 1;
  2111. }
  2112. /** Send queued messages. */
  2113. Socket.prototype._sendQueuedMessages = function() {
  2114. for (var i = 0, ii = this._queue.length; i < ii; i += 1) {
  2115. this.send(this._queue[i]);
  2116. }
  2117. }
  2118. /** Exposed send for DC & Peer. */
  2119. Socket.prototype.send = function(data) {
  2120. if (this.disconnected) {
  2121. return;
  2122. }
  2123. // If we didn't get an ID yet, we can't yet send anything so we should queue
  2124. // up these messages.
  2125. if (!this.id) {
  2126. this._queue.push(data);
  2127. return;
  2128. }
  2129. if (!data.type) {
  2130. this.emit('error', 'Invalid message');
  2131. return;
  2132. }
  2133. var message = JSON.stringify(data);
  2134. if (this._wsOpen()) {
  2135. this._socket.send(message);
  2136. } else {
  2137. var http = new XMLHttpRequest();
  2138. var url = this._httpUrl + '/' + data.type.toLowerCase();
  2139. http.open('post', url, true);
  2140. http.setRequestHeader('Content-Type', 'application/json');
  2141. http.send(message);
  2142. }
  2143. }
  2144. Socket.prototype.close = function() {
  2145. if (!this.disconnected && this._wsOpen()) {
  2146. this._socket.close();
  2147. this.disconnected = true;
  2148. }
  2149. }
  2150. })(this);