peer.js 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423
  1. /*! peerjs.js build:0.3.1, development. Copyright(c) 2013 Michelle Bu <michelle@michellebu.com> */
  2. (function(exports){
  3. var binaryFeatures = {};
  4. binaryFeatures.useBlobBuilder = (function(){
  5. try {
  6. new Blob([]);
  7. return false;
  8. } catch (e) {
  9. return true;
  10. }
  11. })();
  12. binaryFeatures.useArrayBufferView = !binaryFeatures.useBlobBuilder && (function(){
  13. try {
  14. return (new Blob([new Uint8Array([])])).size === 0;
  15. } catch (e) {
  16. return true;
  17. }
  18. })();
  19. exports.binaryFeatures = binaryFeatures;
  20. exports.BlobBuilder = window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder || window.BlobBuilder;
  21. function BufferBuilder(){
  22. this._pieces = [];
  23. this._parts = [];
  24. }
  25. BufferBuilder.prototype.append = function(data) {
  26. if(typeof data === 'number') {
  27. this._pieces.push(data);
  28. } else {
  29. this._flush();
  30. this._parts.push(data);
  31. }
  32. };
  33. BufferBuilder.prototype._flush = function() {
  34. if (this._pieces.length > 0) {
  35. var buf = new Uint8Array(this._pieces);
  36. if(!binaryFeatures.useArrayBufferView) {
  37. buf = buf.buffer;
  38. }
  39. this._parts.push(buf);
  40. this._pieces = [];
  41. }
  42. };
  43. BufferBuilder.prototype.getBuffer = function() {
  44. this._flush();
  45. if(binaryFeatures.useBlobBuilder) {
  46. var builder = new BlobBuilder();
  47. for(var i = 0, ii = this._parts.length; i < ii; i++) {
  48. builder.append(this._parts[i]);
  49. }
  50. return builder.getBlob();
  51. } else {
  52. return new Blob(this._parts);
  53. }
  54. };
  55. exports.BinaryPack = {
  56. unpack: function(data){
  57. var unpacker = new Unpacker(data);
  58. return unpacker.unpack();
  59. },
  60. pack: function(data, utf8){
  61. var packer = new Packer(utf8);
  62. var buffer = packer.pack(data);
  63. return buffer;
  64. }
  65. };
  66. function Unpacker (data){
  67. // Data is ArrayBuffer
  68. this.index = 0;
  69. this.dataBuffer = data;
  70. this.dataView = new Uint8Array(this.dataBuffer);
  71. this.length = this.dataBuffer.byteLength;
  72. }
  73. Unpacker.prototype.unpack = function(){
  74. var type = this.unpack_uint8();
  75. if (type < 0x80){
  76. var positive_fixnum = type;
  77. return positive_fixnum;
  78. } else if ((type ^ 0xe0) < 0x20){
  79. var negative_fixnum = (type ^ 0xe0) - 0x20;
  80. return negative_fixnum;
  81. }
  82. var size;
  83. if ((size = type ^ 0xa0) <= 0x0f){
  84. return this.unpack_raw(size);
  85. } else if ((size = type ^ 0xb0) <= 0x0f){
  86. return this.unpack_string(size);
  87. } else if ((size = type ^ 0x90) <= 0x0f){
  88. return this.unpack_array(size);
  89. } else if ((size = type ^ 0x80) <= 0x0f){
  90. return this.unpack_map(size);
  91. }
  92. switch(type){
  93. case 0xc0:
  94. return null;
  95. case 0xc1:
  96. return undefined;
  97. case 0xc2:
  98. return false;
  99. case 0xc3:
  100. return true;
  101. case 0xca:
  102. return this.unpack_float();
  103. case 0xcb:
  104. return this.unpack_double();
  105. case 0xcc:
  106. return this.unpack_uint8();
  107. case 0xcd:
  108. return this.unpack_uint16();
  109. case 0xce:
  110. return this.unpack_uint32();
  111. case 0xcf:
  112. return this.unpack_uint64();
  113. case 0xd0:
  114. return this.unpack_int8();
  115. case 0xd1:
  116. return this.unpack_int16();
  117. case 0xd2:
  118. return this.unpack_int32();
  119. case 0xd3:
  120. return this.unpack_int64();
  121. case 0xd4:
  122. return undefined;
  123. case 0xd5:
  124. return undefined;
  125. case 0xd6:
  126. return undefined;
  127. case 0xd7:
  128. return undefined;
  129. case 0xd8:
  130. size = this.unpack_uint16();
  131. return this.unpack_string(size);
  132. case 0xd9:
  133. size = this.unpack_uint32();
  134. return this.unpack_string(size);
  135. case 0xda:
  136. size = this.unpack_uint16();
  137. return this.unpack_raw(size);
  138. case 0xdb:
  139. size = this.unpack_uint32();
  140. return this.unpack_raw(size);
  141. case 0xdc:
  142. size = this.unpack_uint16();
  143. return this.unpack_array(size);
  144. case 0xdd:
  145. size = this.unpack_uint32();
  146. return this.unpack_array(size);
  147. case 0xde:
  148. size = this.unpack_uint16();
  149. return this.unpack_map(size);
  150. case 0xdf:
  151. size = this.unpack_uint32();
  152. return this.unpack_map(size);
  153. }
  154. }
  155. Unpacker.prototype.unpack_uint8 = function(){
  156. var byte = this.dataView[this.index] & 0xff;
  157. this.index++;
  158. return byte;
  159. };
  160. Unpacker.prototype.unpack_uint16 = function(){
  161. var bytes = this.read(2);
  162. var uint16 =
  163. ((bytes[0] & 0xff) * 256) + (bytes[1] & 0xff);
  164. this.index += 2;
  165. return uint16;
  166. }
  167. Unpacker.prototype.unpack_uint32 = function(){
  168. var bytes = this.read(4);
  169. var uint32 =
  170. ((bytes[0] * 256 +
  171. bytes[1]) * 256 +
  172. bytes[2]) * 256 +
  173. bytes[3];
  174. this.index += 4;
  175. return uint32;
  176. }
  177. Unpacker.prototype.unpack_uint64 = function(){
  178. var bytes = this.read(8);
  179. var uint64 =
  180. ((((((bytes[0] * 256 +
  181. bytes[1]) * 256 +
  182. bytes[2]) * 256 +
  183. bytes[3]) * 256 +
  184. bytes[4]) * 256 +
  185. bytes[5]) * 256 +
  186. bytes[6]) * 256 +
  187. bytes[7];
  188. this.index += 8;
  189. return uint64;
  190. }
  191. Unpacker.prototype.unpack_int8 = function(){
  192. var uint8 = this.unpack_uint8();
  193. return (uint8 < 0x80 ) ? uint8 : uint8 - (1 << 8);
  194. };
  195. Unpacker.prototype.unpack_int16 = function(){
  196. var uint16 = this.unpack_uint16();
  197. return (uint16 < 0x8000 ) ? uint16 : uint16 - (1 << 16);
  198. }
  199. Unpacker.prototype.unpack_int32 = function(){
  200. var uint32 = this.unpack_uint32();
  201. return (uint32 < Math.pow(2, 31) ) ? uint32 :
  202. uint32 - Math.pow(2, 32);
  203. }
  204. Unpacker.prototype.unpack_int64 = function(){
  205. var uint64 = this.unpack_uint64();
  206. return (uint64 < Math.pow(2, 63) ) ? uint64 :
  207. uint64 - Math.pow(2, 64);
  208. }
  209. Unpacker.prototype.unpack_raw = function(size){
  210. if ( this.length < this.index + size){
  211. throw new Error('BinaryPackFailure: index is out of range'
  212. + ' ' + this.index + ' ' + size + ' ' + this.length);
  213. }
  214. var buf = this.dataBuffer.slice(this.index, this.index + size);
  215. this.index += size;
  216. //buf = util.bufferToString(buf);
  217. return buf;
  218. }
  219. Unpacker.prototype.unpack_string = function(size){
  220. var bytes = this.read(size);
  221. var i = 0, str = '', c, code;
  222. while(i < size){
  223. c = bytes[i];
  224. if ( c < 128){
  225. str += String.fromCharCode(c);
  226. i++;
  227. } else if ((c ^ 0xc0) < 32){
  228. code = ((c ^ 0xc0) << 6) | (bytes[i+1] & 63);
  229. str += String.fromCharCode(code);
  230. i += 2;
  231. } else {
  232. code = ((c & 15) << 12) | ((bytes[i+1] & 63) << 6) |
  233. (bytes[i+2] & 63);
  234. str += String.fromCharCode(code);
  235. i += 3;
  236. }
  237. }
  238. this.index += size;
  239. return str;
  240. }
  241. Unpacker.prototype.unpack_array = function(size){
  242. var objects = new Array(size);
  243. for(var i = 0; i < size ; i++){
  244. objects[i] = this.unpack();
  245. }
  246. return objects;
  247. }
  248. Unpacker.prototype.unpack_map = function(size){
  249. var map = {};
  250. for(var i = 0; i < size ; i++){
  251. var key = this.unpack();
  252. var value = this.unpack();
  253. map[key] = value;
  254. }
  255. return map;
  256. }
  257. Unpacker.prototype.unpack_float = function(){
  258. var uint32 = this.unpack_uint32();
  259. var sign = uint32 >> 31;
  260. var exp = ((uint32 >> 23) & 0xff) - 127;
  261. var fraction = ( uint32 & 0x7fffff ) | 0x800000;
  262. return (sign == 0 ? 1 : -1) *
  263. fraction * Math.pow(2, exp - 23);
  264. }
  265. Unpacker.prototype.unpack_double = function(){
  266. var h32 = this.unpack_uint32();
  267. var l32 = this.unpack_uint32();
  268. var sign = h32 >> 31;
  269. var exp = ((h32 >> 20) & 0x7ff) - 1023;
  270. var hfrac = ( h32 & 0xfffff ) | 0x100000;
  271. var frac = hfrac * Math.pow(2, exp - 20) +
  272. l32 * Math.pow(2, exp - 52);
  273. return (sign == 0 ? 1 : -1) * frac;
  274. }
  275. Unpacker.prototype.read = function(length){
  276. var j = this.index;
  277. if (j + length <= this.length) {
  278. return this.dataView.subarray(j, j + length);
  279. } else {
  280. throw new Error('BinaryPackFailure: read index out of range');
  281. }
  282. }
  283. function Packer(utf8){
  284. this.utf8 = utf8;
  285. this.bufferBuilder = new BufferBuilder();
  286. }
  287. Packer.prototype.pack = function(value){
  288. var type = typeof(value);
  289. if (type == 'string'){
  290. this.pack_string(value);
  291. } else if (type == 'number'){
  292. if (Math.floor(value) === value){
  293. this.pack_integer(value);
  294. } else{
  295. this.pack_double(value);
  296. }
  297. } else if (type == 'boolean'){
  298. if (value === true){
  299. this.bufferBuilder.append(0xc3);
  300. } else if (value === false){
  301. this.bufferBuilder.append(0xc2);
  302. }
  303. } else if (type == 'undefined'){
  304. this.bufferBuilder.append(0xc0);
  305. } else if (type == 'object'){
  306. if (value === null){
  307. this.bufferBuilder.append(0xc0);
  308. } else {
  309. var constructor = value.constructor;
  310. if (constructor == Array){
  311. this.pack_array(value);
  312. } else if (constructor == Blob || constructor == File) {
  313. this.pack_bin(value);
  314. } else if (constructor == ArrayBuffer) {
  315. if(binaryFeatures.useArrayBufferView) {
  316. this.pack_bin(new Uint8Array(value));
  317. } else {
  318. this.pack_bin(value);
  319. }
  320. } else if ('BYTES_PER_ELEMENT' in value){
  321. if(binaryFeatures.useArrayBufferView) {
  322. this.pack_bin(value);
  323. } else {
  324. this.pack_bin(value.buffer);
  325. }
  326. } else if (constructor == Object){
  327. this.pack_object(value);
  328. } else if (constructor == Date){
  329. this.pack_string(value.toString());
  330. } else if (typeof value.toBinaryPack == 'function'){
  331. this.bufferBuilder.append(value.toBinaryPack());
  332. } else {
  333. throw new Error('Type "' + constructor.toString() + '" not yet supported');
  334. }
  335. }
  336. } else {
  337. throw new Error('Type "' + type + '" not yet supported');
  338. }
  339. return this.bufferBuilder.getBuffer();
  340. }
  341. Packer.prototype.pack_bin = function(blob){
  342. var length = blob.length || blob.byteLength || blob.size;
  343. if (length <= 0x0f){
  344. this.pack_uint8(0xa0 + length);
  345. } else if (length <= 0xffff){
  346. this.bufferBuilder.append(0xda) ;
  347. this.pack_uint16(length);
  348. } else if (length <= 0xffffffff){
  349. this.bufferBuilder.append(0xdb);
  350. this.pack_uint32(length);
  351. } else{
  352. throw new Error('Invalid length');
  353. return;
  354. }
  355. this.bufferBuilder.append(blob);
  356. }
  357. Packer.prototype.pack_string = function(str){
  358. var length;
  359. if (this.utf8) {
  360. var blob = new Blob([str]);
  361. length = blob.size;
  362. } else {
  363. length = str.length;
  364. }
  365. if (length <= 0x0f){
  366. this.pack_uint8(0xb0 + length);
  367. } else if (length <= 0xffff){
  368. this.bufferBuilder.append(0xd8) ;
  369. this.pack_uint16(length);
  370. } else if (length <= 0xffffffff){
  371. this.bufferBuilder.append(0xd9);
  372. this.pack_uint32(length);
  373. } else{
  374. throw new Error('Invalid length');
  375. return;
  376. }
  377. this.bufferBuilder.append(str);
  378. }
  379. Packer.prototype.pack_array = function(ary){
  380. var length = ary.length;
  381. if (length <= 0x0f){
  382. this.pack_uint8(0x90 + length);
  383. } else if (length <= 0xffff){
  384. this.bufferBuilder.append(0xdc)
  385. this.pack_uint16(length);
  386. } else if (length <= 0xffffffff){
  387. this.bufferBuilder.append(0xdd);
  388. this.pack_uint32(length);
  389. } else{
  390. throw new Error('Invalid length');
  391. }
  392. for(var i = 0; i < length ; i++){
  393. this.pack(ary[i]);
  394. }
  395. }
  396. Packer.prototype.pack_integer = function(num){
  397. if ( -0x20 <= num && num <= 0x7f){
  398. this.bufferBuilder.append(num & 0xff);
  399. } else if (0x00 <= num && num <= 0xff){
  400. this.bufferBuilder.append(0xcc);
  401. this.pack_uint8(num);
  402. } else if (-0x80 <= num && num <= 0x7f){
  403. this.bufferBuilder.append(0xd0);
  404. this.pack_int8(num);
  405. } else if ( 0x0000 <= num && num <= 0xffff){
  406. this.bufferBuilder.append(0xcd);
  407. this.pack_uint16(num);
  408. } else if (-0x8000 <= num && num <= 0x7fff){
  409. this.bufferBuilder.append(0xd1);
  410. this.pack_int16(num);
  411. } else if ( 0x00000000 <= num && num <= 0xffffffff){
  412. this.bufferBuilder.append(0xce);
  413. this.pack_uint32(num);
  414. } else if (-0x80000000 <= num && num <= 0x7fffffff){
  415. this.bufferBuilder.append(0xd2);
  416. this.pack_int32(num);
  417. } else if (-0x8000000000000000 <= num && num <= 0x7FFFFFFFFFFFFFFF){
  418. this.bufferBuilder.append(0xd3);
  419. this.pack_int64(num);
  420. } else if (0x0000000000000000 <= num && num <= 0xFFFFFFFFFFFFFFFF){
  421. this.bufferBuilder.append(0xcf);
  422. this.pack_uint64(num);
  423. } else{
  424. throw new Error('Invalid integer');
  425. }
  426. }
  427. Packer.prototype.pack_double = function(num){
  428. var sign = 0;
  429. if (num < 0){
  430. sign = 1;
  431. num = -num;
  432. }
  433. var exp = Math.floor(Math.log(num) / Math.LN2);
  434. var frac0 = num / Math.pow(2, exp) - 1;
  435. var frac1 = Math.floor(frac0 * Math.pow(2, 52));
  436. var b32 = Math.pow(2, 32);
  437. var h32 = (sign << 31) | ((exp+1023) << 20) |
  438. (frac1 / b32) & 0x0fffff;
  439. var l32 = frac1 % b32;
  440. this.bufferBuilder.append(0xcb);
  441. this.pack_int32(h32);
  442. this.pack_int32(l32);
  443. }
  444. Packer.prototype.pack_object = function(obj){
  445. var keys = Object.keys(obj);
  446. var length = keys.length;
  447. if (length <= 0x0f){
  448. this.pack_uint8(0x80 + length);
  449. } else if (length <= 0xffff){
  450. this.bufferBuilder.append(0xde);
  451. this.pack_uint16(length);
  452. } else if (length <= 0xffffffff){
  453. this.bufferBuilder.append(0xdf);
  454. this.pack_uint32(length);
  455. } else{
  456. throw new Error('Invalid length');
  457. }
  458. for(var prop in obj){
  459. if (obj.hasOwnProperty(prop)){
  460. this.pack(prop);
  461. this.pack(obj[prop]);
  462. }
  463. }
  464. }
  465. Packer.prototype.pack_uint8 = function(num){
  466. this.bufferBuilder.append(num);
  467. }
  468. Packer.prototype.pack_uint16 = function(num){
  469. this.bufferBuilder.append(num >> 8);
  470. this.bufferBuilder.append(num & 0xff);
  471. }
  472. Packer.prototype.pack_uint32 = function(num){
  473. var n = num & 0xffffffff;
  474. this.bufferBuilder.append((n & 0xff000000) >>> 24);
  475. this.bufferBuilder.append((n & 0x00ff0000) >>> 16);
  476. this.bufferBuilder.append((n & 0x0000ff00) >>> 8);
  477. this.bufferBuilder.append((n & 0x000000ff));
  478. }
  479. Packer.prototype.pack_uint64 = function(num){
  480. var high = num / Math.pow(2, 32);
  481. var low = num % Math.pow(2, 32);
  482. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  483. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  484. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  485. this.bufferBuilder.append((high & 0x000000ff));
  486. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  487. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  488. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  489. this.bufferBuilder.append((low & 0x000000ff));
  490. }
  491. Packer.prototype.pack_int8 = function(num){
  492. this.bufferBuilder.append(num & 0xff);
  493. }
  494. Packer.prototype.pack_int16 = function(num){
  495. this.bufferBuilder.append((num & 0xff00) >> 8);
  496. this.bufferBuilder.append(num & 0xff);
  497. }
  498. Packer.prototype.pack_int32 = function(num){
  499. this.bufferBuilder.append((num >>> 24) & 0xff);
  500. this.bufferBuilder.append((num & 0x00ff0000) >>> 16);
  501. this.bufferBuilder.append((num & 0x0000ff00) >>> 8);
  502. this.bufferBuilder.append((num & 0x000000ff));
  503. }
  504. Packer.prototype.pack_int64 = function(num){
  505. var high = Math.floor(num / Math.pow(2, 32));
  506. var low = num % Math.pow(2, 32);
  507. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  508. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  509. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  510. this.bufferBuilder.append((high & 0x000000ff));
  511. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  512. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  513. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  514. this.bufferBuilder.append((low & 0x000000ff));
  515. }
  516. /**
  517. * Light EventEmitter. Ported from Node.js/events.js
  518. * Eric Zhang
  519. */
  520. /**
  521. * EventEmitter class
  522. * Creates an object with event registering and firing methods
  523. */
  524. function EventEmitter() {
  525. // Initialise required storage variables
  526. this._events = {};
  527. }
  528. var isArray = Array.isArray;
  529. EventEmitter.prototype.addListener = function(type, listener, scope, once) {
  530. if ('function' !== typeof listener) {
  531. throw new Error('addListener only takes instances of Function');
  532. }
  533. // To avoid recursion in the case that type == "newListeners"! Before
  534. // adding it to the listeners, first emit "newListeners".
  535. this.emit('newListener', type, typeof listener.listener === 'function' ?
  536. listener.listener : listener);
  537. if (!this._events[type]) {
  538. // Optimize the case of one listener. Don't need the extra array object.
  539. this._events[type] = listener;
  540. } else if (isArray(this._events[type])) {
  541. // If we've already got an array, just append.
  542. this._events[type].push(listener);
  543. } else {
  544. // Adding the second element, need to change to array.
  545. this._events[type] = [this._events[type], listener];
  546. }
  547. return this;
  548. };
  549. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  550. EventEmitter.prototype.once = function(type, listener, scope) {
  551. if ('function' !== typeof listener) {
  552. throw new Error('.once only takes instances of Function');
  553. }
  554. var self = this;
  555. function g() {
  556. self.removeListener(type, g);
  557. listener.apply(this, arguments);
  558. };
  559. g.listener = listener;
  560. self.on(type, g);
  561. return this;
  562. };
  563. EventEmitter.prototype.removeListener = function(type, listener, scope) {
  564. if ('function' !== typeof listener) {
  565. throw new Error('removeListener only takes instances of Function');
  566. }
  567. // does not use listeners(), so no side effect of creating _events[type]
  568. if (!this._events[type]) return this;
  569. var list = this._events[type];
  570. if (isArray(list)) {
  571. var position = -1;
  572. for (var i = 0, length = list.length; i < length; i++) {
  573. if (list[i] === listener ||
  574. (list[i].listener && list[i].listener === listener))
  575. {
  576. position = i;
  577. break;
  578. }
  579. }
  580. if (position < 0) return this;
  581. list.splice(position, 1);
  582. if (list.length == 0)
  583. delete this._events[type];
  584. } else if (list === listener ||
  585. (list.listener && list.listener === listener))
  586. {
  587. delete this._events[type];
  588. }
  589. return this;
  590. };
  591. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  592. EventEmitter.prototype.removeAllListeners = function(type) {
  593. if (arguments.length === 0) {
  594. this._events = {};
  595. return this;
  596. }
  597. // does not use listeners(), so no side effect of creating _events[type]
  598. if (type && this._events && this._events[type]) this._events[type] = null;
  599. return this;
  600. };
  601. EventEmitter.prototype.listeners = function(type) {
  602. if (!this._events[type]) this._events[type] = [];
  603. if (!isArray(this._events[type])) {
  604. this._events[type] = [this._events[type]];
  605. }
  606. return this._events[type];
  607. };
  608. EventEmitter.prototype.emit = function(type) {
  609. var type = arguments[0];
  610. var handler = this._events[type];
  611. if (!handler) return false;
  612. if (typeof handler == 'function') {
  613. switch (arguments.length) {
  614. // fast cases
  615. case 1:
  616. handler.call(this);
  617. break;
  618. case 2:
  619. handler.call(this, arguments[1]);
  620. break;
  621. case 3:
  622. handler.call(this, arguments[1], arguments[2]);
  623. break;
  624. // slower
  625. default:
  626. var l = arguments.length;
  627. var args = new Array(l - 1);
  628. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  629. handler.apply(this, args);
  630. }
  631. return true;
  632. } else if (isArray(handler)) {
  633. var l = arguments.length;
  634. var args = new Array(l - 1);
  635. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  636. var listeners = handler.slice();
  637. for (var i = 0, l = listeners.length; i < l; i++) {
  638. listeners[i].apply(this, args);
  639. }
  640. return true;
  641. } else {
  642. return false;
  643. }
  644. };
  645. /**
  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. exports.RTCIceCandidate = window.mozRTCIceCandidate || window.RTCIceCandidate;
  918. var defaultConfig = {'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }]};
  919. var util = {
  920. noop: function() {},
  921. CLOUD_HOST: '0.peerjs.com',
  922. CLOUD_PORT: 9000,
  923. // Logging logic
  924. logLevel: 0,
  925. setLogLevel: function(level) {
  926. var debugLevel = parseInt(level, 10);
  927. if (!isNaN(parseInt(level, 10))) {
  928. util.logLevel = debugLevel;
  929. } else {
  930. // If they are using truthy/falsy values for debug
  931. util.logLevel = level ? 3 : 0;
  932. }
  933. util.log = util.warn = util.error = util.noop;
  934. if (util.logLevel > 0) {
  935. util.error = util._printWith('ERROR');
  936. }
  937. if (util.logLevel > 1) {
  938. util.warn = util._printWith('WARNING');
  939. }
  940. if (util.logLevel > 2) {
  941. util.log = util._print;
  942. }
  943. },
  944. setLogFunction: function(fn) {
  945. if (fn.constructor !== Function) {
  946. util.warn('The log function you passed in is not a function. Defaulting to regular logs.');
  947. } else {
  948. util._print = fn;
  949. }
  950. },
  951. _printWith: function(prefix) {
  952. return function() {
  953. var copy = Array.prototype.slice.call(arguments);
  954. copy.unshift(prefix);
  955. util._print.apply(util, copy);
  956. };
  957. },
  958. _print: function () {
  959. var err = false;
  960. var copy = Array.prototype.slice.call(arguments);
  961. copy.unshift('PeerJS: ');
  962. for (var i = 0, l = copy.length; i < l; i++){
  963. if (copy[i] instanceof Error) {
  964. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  965. err = true;
  966. }
  967. }
  968. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  969. },
  970. //
  971. // Returns browser-agnostic default config
  972. defaultConfig: defaultConfig,
  973. //
  974. // Returns the current browser.
  975. browser: (function() {
  976. if (window.mozRTCPeerConnection) {
  977. return 'Firefox';
  978. } else if (window.webkitRTCPeerConnection) {
  979. return 'Chrome';
  980. } else if (window.RTCPeerConnection) {
  981. return 'Supported';
  982. } else {
  983. return 'Unsupported';
  984. }
  985. })(),
  986. //
  987. // Lists which features are supported
  988. supports: (function() {
  989. if (typeof RTCPeerConnection === 'undefined') {
  990. return {};
  991. }
  992. var data = true;
  993. var audioVideo = true;
  994. var binary = false;
  995. var reliable = false;
  996. var onnegotiationneeded = !!window.webkitRTCPeerConnection;
  997. var pc, dc;
  998. try {
  999. pc = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  1000. } catch (e) {
  1001. data = false;
  1002. audioVideo = false;
  1003. }
  1004. if (data) {
  1005. try {
  1006. dc = pc.createDataChannel('_PEERJSTEST');
  1007. } catch (e) {
  1008. data = false;
  1009. }
  1010. }
  1011. if (data) {
  1012. // Binary test
  1013. try {
  1014. dc.binaryType = 'blob';
  1015. binary = true;
  1016. } catch (e) {
  1017. }
  1018. // Reliable test.
  1019. // Unfortunately Chrome is a bit unreliable about whether or not they
  1020. // support reliable.
  1021. var reliablePC = new RTCPeerConnection(defaultConfig, {});
  1022. try {
  1023. var reliableDC = reliablePC.createDataChannel('_PEERJSRELIABLETEST', {});
  1024. reliable = reliableDC.reliable && navigator.mozRTCPeerConnection;
  1025. } catch (e) {
  1026. }
  1027. reliablePC.close();
  1028. }
  1029. // FIXME: not really the best check...
  1030. if (audioVideo) {
  1031. audioVideo = !!pc.addStream;
  1032. }
  1033. // FIXME: this is not great because in theory it doesn't work for
  1034. // av-only browsers (?).
  1035. if (!onnegotiationneeded && data) {
  1036. // sync default check.
  1037. var negotiationPC = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  1038. negotiationPC.onnegotiationneeded = function() {
  1039. onnegotiationneeded = true;
  1040. // async check.
  1041. if (util && util.supports) {
  1042. util.supports.onnegotiationneeded = true;
  1043. }
  1044. };
  1045. var negotiationDC = negotiationPC.createDataChannel('_PEERJSNEGOTIATIONTEST');
  1046. setTimeout(function() {
  1047. negotiationPC.close();
  1048. }, 1000);
  1049. }
  1050. if (pc) {
  1051. pc.close();
  1052. }
  1053. return {
  1054. audioVideo: audioVideo,
  1055. data: data,
  1056. binary: binary,
  1057. reliable: reliable,
  1058. onnegotiationneeded: onnegotiationneeded
  1059. };
  1060. }()),
  1061. //
  1062. // Ensure alphanumeric ids
  1063. validateId: function(id) {
  1064. // Allow empty ids
  1065. return !id || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id);
  1066. },
  1067. validateKey: function(key) {
  1068. // Allow empty keys
  1069. return !key || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(key);
  1070. },
  1071. debug: false,
  1072. inherits: function(ctor, superCtor) {
  1073. ctor.super_ = superCtor;
  1074. ctor.prototype = Object.create(superCtor.prototype, {
  1075. constructor: {
  1076. value: ctor,
  1077. enumerable: false,
  1078. writable: true,
  1079. configurable: true
  1080. }
  1081. });
  1082. },
  1083. extend: function(dest, source) {
  1084. for(var key in source) {
  1085. if(source.hasOwnProperty(key)) {
  1086. dest[key] = source[key];
  1087. }
  1088. }
  1089. return dest;
  1090. },
  1091. pack: BinaryPack.pack,
  1092. unpack: BinaryPack.unpack,
  1093. log: function () {
  1094. if (util.debug) {
  1095. var err = false;
  1096. var copy = Array.prototype.slice.call(arguments);
  1097. copy.unshift('PeerJS: ');
  1098. for (var i = 0, l = copy.length; i < l; i++){
  1099. if (copy[i] instanceof Error) {
  1100. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  1101. err = true;
  1102. }
  1103. }
  1104. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  1105. }
  1106. },
  1107. setZeroTimeout: (function(global) {
  1108. var timeouts = [];
  1109. var messageName = 'zero-timeout-message';
  1110. // Like setTimeout, but only takes a function argument. There's
  1111. // no time argument (always zero) and no arguments (you have to
  1112. // use a closure).
  1113. function setZeroTimeoutPostMessage(fn) {
  1114. timeouts.push(fn);
  1115. global.postMessage(messageName, '*');
  1116. }
  1117. function handleMessage(event) {
  1118. if (event.source == global && event.data == messageName) {
  1119. if (event.stopPropagation) {
  1120. event.stopPropagation();
  1121. }
  1122. if (timeouts.length) {
  1123. timeouts.shift()();
  1124. }
  1125. }
  1126. }
  1127. if (global.addEventListener) {
  1128. global.addEventListener('message', handleMessage, true);
  1129. } else if (global.attachEvent) {
  1130. global.attachEvent('onmessage', handleMessage);
  1131. }
  1132. return setZeroTimeoutPostMessage;
  1133. }(this)),
  1134. // Binary stuff
  1135. blobToArrayBuffer: function(blob, cb){
  1136. var fr = new FileReader();
  1137. fr.onload = function(evt) {
  1138. cb(evt.target.result);
  1139. };
  1140. fr.readAsArrayBuffer(blob);
  1141. },
  1142. blobToBinaryString: function(blob, cb){
  1143. var fr = new FileReader();
  1144. fr.onload = function(evt) {
  1145. cb(evt.target.result);
  1146. };
  1147. fr.readAsBinaryString(blob);
  1148. },
  1149. binaryStringToArrayBuffer: function(binary) {
  1150. var byteArray = new Uint8Array(binary.length);
  1151. for (var i = 0; i < binary.length; i++) {
  1152. byteArray[i] = binary.charCodeAt(i) & 0xff;
  1153. }
  1154. return byteArray.buffer;
  1155. },
  1156. randomToken: function () {
  1157. return Math.random().toString(36).substr(2);
  1158. },
  1159. //
  1160. isSecure: function() {
  1161. return location.protocol === 'https:';
  1162. }
  1163. };
  1164. exports.util = util;
  1165. /**
  1166. * A peer who can initiate connections with other peers.
  1167. */
  1168. function Peer(id, options) {
  1169. if (!(this instanceof Peer)) return new Peer(id, options);
  1170. EventEmitter.call(this);
  1171. // Deal with overloading
  1172. if (id && id.constructor == Object) {
  1173. options = id;
  1174. id = undefined;
  1175. } else if (id) {
  1176. // Ensure id is a string
  1177. id = id.toString();
  1178. }
  1179. //
  1180. // Configurize options
  1181. options = util.extend({
  1182. debug: 0, // 1: Errors, 2: Warnings, 3: All logs
  1183. host: util.CLOUD_HOST,
  1184. port: util.CLOUD_PORT,
  1185. key: 'peerjs',
  1186. config: util.defaultConfig
  1187. }, options);
  1188. this.options = options;
  1189. // Detect relative URL host.
  1190. if (options.host === '/') {
  1191. options.host = window.location.hostname;
  1192. }
  1193. // Set whether we use SSL to same as current host
  1194. if (options.secure === undefined && options.host !== util.CLOUD_HOST) {
  1195. options.secure = util.isSecure();
  1196. }
  1197. // Set a custom log function if present
  1198. if (options.logFunction) {
  1199. util.setLogFunction(options.logFunction);
  1200. }
  1201. util.setLogLevel(options.debug);
  1202. //
  1203. // Sanity checks
  1204. // Ensure WebRTC supported
  1205. if (!util.supports.audioVideo && !util.supports.data ) {
  1206. this._delayedAbort('browser-incompatible', 'The current browser does not support WebRTC');
  1207. return;
  1208. }
  1209. // Ensure alphanumeric id
  1210. if (!util.validateId(id)) {
  1211. this._delayedAbort('invalid-id', 'ID "' + id + '" is invalid');
  1212. return;
  1213. }
  1214. // Ensure valid key
  1215. if (!util.validateKey(options.key)) {
  1216. this._delayedAbort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  1217. return;
  1218. }
  1219. // Ensure not using unsecure cloud server on SSL page
  1220. if (options.secure && options.host === '0.peerjs.com') {
  1221. this._delayedAbort('ssl-unavailable',
  1222. 'The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS.');
  1223. return;
  1224. }
  1225. //
  1226. // States.
  1227. this.destroyed = false; // Connections have been killed
  1228. this.disconnected = false; // Connection to PeerServer killed manually but P2P connections still active
  1229. this.open = false; // Sockets and such are not yet open.
  1230. //
  1231. // References
  1232. this.connections = {}; // DataConnections for this peer.
  1233. this._lostMessages = {}; // src => [list of messages]
  1234. //
  1235. // Initialize the 'socket' (which is actually a mix of XHR streaming and
  1236. // websockets.)
  1237. var self = this;
  1238. this.socket = new Socket(this.options.secure, this.options.host, this.options.port, this.options.key);
  1239. this.socket.on('message', function(data) {
  1240. self._handleMessage(data);
  1241. });
  1242. this.socket.on('error', function(error) {
  1243. self._abort('socket-error', error);
  1244. });
  1245. this.socket.on('close', function() {
  1246. if (!self.disconnected) { // If we haven't explicitly disconnected, emit error.
  1247. self._abort('socket-closed', 'Underlying socket is already closed.');
  1248. }
  1249. });
  1250. //
  1251. // Start the connections
  1252. if (id) {
  1253. this._initialize(id);
  1254. } else {
  1255. this._retrieveId();
  1256. }
  1257. //
  1258. };
  1259. util.inherits(Peer, EventEmitter);
  1260. /** Get a unique ID from the server via XHR. */
  1261. Peer.prototype._retrieveId = function(cb) {
  1262. var self = this;
  1263. var http = new XMLHttpRequest();
  1264. var protocol = this.options.secure ? 'https://' : 'http://';
  1265. var url = protocol + this.options.host + ':' + this.options.port + '/' + this.options.key + '/id';
  1266. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  1267. url += queryString;
  1268. // If there's no ID we need to wait for one before trying to init socket.
  1269. http.open('get', url, true);
  1270. http.onerror = function(e) {
  1271. util.error('Error retrieving ID', e);
  1272. self._abort('server-error', 'Could not get an ID from the server');
  1273. }
  1274. http.onreadystatechange = function() {
  1275. if (http.readyState !== 4) {
  1276. return;
  1277. }
  1278. if (http.status !== 200) {
  1279. http.onerror();
  1280. return;
  1281. }
  1282. self._initialize(http.responseText);
  1283. };
  1284. http.send(null);
  1285. };
  1286. /** Initialize a connection with the server. */
  1287. Peer.prototype._initialize = function(id) {
  1288. var self = this;
  1289. this.id = id;
  1290. this.socket.start(this.id);
  1291. }
  1292. /** Handles messages from the server. */
  1293. Peer.prototype._handleMessage = function(message) {
  1294. var type = message.type;
  1295. var payload = message.payload;
  1296. var peer = message.src;
  1297. switch (type) {
  1298. case 'OPEN': // The connection to the server is open.
  1299. this.emit('open', this.id);
  1300. this.open = true;
  1301. break;
  1302. case 'ERROR': // Server error.
  1303. this._abort('server-error', payload.msg);
  1304. break;
  1305. case 'ID-TAKEN': // The selected ID is taken.
  1306. this._abort('unavailable-id', 'ID `' + this.id + '` is taken');
  1307. break;
  1308. case 'INVALID-KEY': // The given API key cannot be found.
  1309. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  1310. break;
  1311. //
  1312. case 'LEAVE': // Another peer has closed its connection to this peer.
  1313. util.log('Received leave message from', peer);
  1314. this._cleanupPeer(peer);
  1315. break;
  1316. case 'EXPIRE': // The offer sent to a peer has expired without response.
  1317. this.emit('error', new Error('Could not connect to peer ' + peer));
  1318. break;
  1319. case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  1320. var connectionId = payload.connectionId;
  1321. var connection = this.getConnection(peer, connectionId);
  1322. if (connection) {
  1323. util.warn('Offer received for existing Connection ID:', connectionId);
  1324. //connection.handleMessage(message);
  1325. } else {
  1326. // Create a new connection.
  1327. if (payload.type === 'media') {
  1328. var connection = new MediaConnection(peer, this, {
  1329. connectionId: connectionId,
  1330. _payload: payload,
  1331. metadata: payload.metadata,
  1332. });
  1333. this._addConnection(peer, connection);
  1334. this.emit('call', connection);
  1335. } else if (payload.type === 'data') {
  1336. connection = new DataConnection(peer, this, {
  1337. connectionId: connectionId,
  1338. _payload: payload,
  1339. metadata: payload.metadata,
  1340. label: payload.label,
  1341. serialization: payload.serialization,
  1342. reliable: payload.reliable
  1343. });
  1344. this._addConnection(peer, connection);
  1345. this.emit('connection', connection);
  1346. } else {
  1347. util.warn('Received malformed connection type:', payload.type);
  1348. return;
  1349. }
  1350. // Find messages.
  1351. var messages = this._getMessages(connectionId);
  1352. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  1353. connection.handleMessage(messages[i]);
  1354. }
  1355. }
  1356. break;
  1357. default:
  1358. if (!payload) {
  1359. util.warn('You received a malformed message from ' + peer + ' of type ' + type);
  1360. return;
  1361. }
  1362. var id = payload.connectionId;
  1363. var connection = this.getConnection(peer, id);
  1364. if (connection && connection.pc) {
  1365. // Pass it on.
  1366. connection.handleMessage(message);
  1367. } else if (id) {
  1368. // Store for possible later use
  1369. this._storeMessage(id, message);
  1370. } else {
  1371. util.warn('You received an unrecognized message:', message);
  1372. }
  1373. break;
  1374. }
  1375. }
  1376. /** Stores messages without a set up connection, to be claimed later. */
  1377. Peer.prototype._storeMessage = function(connectionId, message) {
  1378. if (!this._lostMessages[connectionId]) {
  1379. this._lostMessages[connectionId] = [];
  1380. }
  1381. this._lostMessages[connectionId].push(message);
  1382. }
  1383. /** Retrieve messages from lost message store */
  1384. Peer.prototype._getMessages = function(connectionId) {
  1385. var messages = this._lostMessages[connectionId];
  1386. if (messages) {
  1387. delete this._lostMessages[connectionId];
  1388. return messages;
  1389. } else {
  1390. return [];
  1391. }
  1392. }
  1393. /**
  1394. * Returns a DataConnection to the specified peer. See documentation for a
  1395. * complete list of options.
  1396. */
  1397. Peer.prototype.connect = function(peer, options) {
  1398. if (this.disconnected) {
  1399. util.warn('You cannot connect to a new Peer because you called '
  1400. + '.disconnect() on this Peer and ended your connection with the'
  1401. + ' server. You can create a new Peer to reconnect.');
  1402. this.emit('error', new Error('Cannot connect to new Peer after disconnecting from server.'));
  1403. return;
  1404. }
  1405. var connection = new DataConnection(peer, this, options);
  1406. this._addConnection(peer, connection);
  1407. return connection;
  1408. }
  1409. /**
  1410. * Returns a MediaConnection to the specified peer. See documentation for a
  1411. * complete list of options.
  1412. */
  1413. Peer.prototype.call = function(peer, stream, options) {
  1414. if (this.disconnected) {
  1415. util.warn('You cannot connect to a new Peer because you called '
  1416. + '.disconnect() on this Peer and ended your connection with the'
  1417. + ' server. You can create a new Peer to reconnect.');
  1418. this.emit('error', new Error('Cannot connect to new Peer after disconnecting from server.'));
  1419. return;
  1420. }
  1421. if (!stream) {
  1422. util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.');
  1423. return;
  1424. }
  1425. options = options || {};
  1426. options._stream = stream;
  1427. var call = new MediaConnection(peer, this, options);
  1428. this._addConnection(peer, call);
  1429. return call;
  1430. }
  1431. /** Add a data/media connection to this peer. */
  1432. Peer.prototype._addConnection = function(peer, connection) {
  1433. if (!this.connections[peer]) {
  1434. this.connections[peer] = [];
  1435. }
  1436. this.connections[peer].push(connection);
  1437. }
  1438. /** Retrieve a data/media connection for this peer. */
  1439. Peer.prototype.getConnection = function(peer, id) {
  1440. var connections = this.connections[peer];
  1441. if (!connections) {
  1442. return null;
  1443. }
  1444. for (var i = 0, ii = connections.length; i < ii; i++) {
  1445. if (connections[i].id === id) {
  1446. return connections[i];
  1447. }
  1448. }
  1449. return null;
  1450. }
  1451. Peer.prototype._delayedAbort = function(type, message) {
  1452. var self = this;
  1453. util.setZeroTimeout(function(){
  1454. self._abort(type, message);
  1455. });
  1456. }
  1457. /** Destroys the Peer and emits an error message. */
  1458. Peer.prototype._abort = function(type, message) {
  1459. util.error('Aborting. Error:', message);
  1460. var err = new Error(message);
  1461. err.type = type;
  1462. this.destroy();
  1463. this.emit('error', err);
  1464. };
  1465. /**
  1466. * Destroys the Peer: closes all active connections as well as the connection
  1467. * to the server.
  1468. * Warning: The peer can no longer create or accept connections after being
  1469. * destroyed.
  1470. */
  1471. Peer.prototype.destroy = function() {
  1472. if (!this.destroyed) {
  1473. this._cleanup();
  1474. this.disconnect();
  1475. this.destroyed = true;
  1476. }
  1477. }
  1478. /** Disconnects every connection on this peer. */
  1479. Peer.prototype._cleanup = function() {
  1480. var peers = Object.keys(this.connections);
  1481. for (var i = 0, ii = peers.length; i < ii; i++) {
  1482. this._cleanupPeer(peers[i]);
  1483. }
  1484. this.emit('close');
  1485. }
  1486. /** Closes all connections to this peer. */
  1487. Peer.prototype._cleanupPeer = function(peer) {
  1488. var connections = this.connections[peer];
  1489. for (var j = 0, jj = connections.length; j < jj; j += 1) {
  1490. connections[j].close();
  1491. }
  1492. }
  1493. /**
  1494. * Disconnects the Peer's connection to the PeerServer. Does not close any
  1495. * active connections.
  1496. * Warning: The peer can no longer create or accept connections after being
  1497. * disconnected. It also cannot reconnect to the server.
  1498. */
  1499. Peer.prototype.disconnect = function() {
  1500. var self = this;
  1501. util.setZeroTimeout(function(){
  1502. if (!self.disconnected) {
  1503. self.disconnected = true;
  1504. self.open = false;
  1505. if (self.socket) {
  1506. self.socket.close();
  1507. }
  1508. self.id = null;
  1509. }
  1510. });
  1511. }
  1512. exports.Peer = Peer;
  1513. /**
  1514. * Wraps a DataChannel between two Peers.
  1515. */
  1516. function DataConnection(peer, provider, options) {
  1517. if (!(this instanceof DataConnection)) return new DataConnection(peer, provider, options);
  1518. EventEmitter.call(this);
  1519. // TODO: perhaps default serialization should be binary-utf8?
  1520. this.options = util.extend({
  1521. serialization: 'binary',
  1522. reliable: false
  1523. }, options);
  1524. // Connection is not open yet.
  1525. this.open = false;
  1526. this.type = 'data';
  1527. this.peer = peer;
  1528. this.provider = provider;
  1529. this.id = this.options.connectionId || DataConnection._idPrefix + util.randomToken();
  1530. this.label = this.options.label || this.id;
  1531. this.metadata = this.options.metadata;
  1532. this.serialization = this.options.serialization;
  1533. this.reliable = this.options.reliable;
  1534. Negotiator.startConnection(
  1535. this,
  1536. this.options._payload || {
  1537. originator: true
  1538. }
  1539. );
  1540. }
  1541. util.inherits(DataConnection, EventEmitter);
  1542. DataConnection._idPrefix = 'dc_';
  1543. /** Called by the Negotiator when the DataChannel is ready. */
  1544. DataConnection.prototype.initialize = function(dc) {
  1545. this._dc = dc;
  1546. this._configureDataChannel();
  1547. }
  1548. DataConnection.prototype._configureDataChannel = function() {
  1549. var self = this;
  1550. if (util.supports.binary) {
  1551. // Webkit doesn't support binary yet
  1552. this._dc.binaryType = 'arraybuffer';
  1553. }
  1554. this._dc.onopen = function() {
  1555. util.log('Data channel connection success');
  1556. self.open = true;
  1557. self.emit('open');
  1558. }
  1559. // Use the Reliable shim for non Firefox browsers
  1560. if (!util.supports.reliable && this.reliable) {
  1561. this._reliable = new Reliable(this._dc, util.debug);
  1562. }
  1563. if (this._reliable) {
  1564. this._reliable.onmessage = function(msg) {
  1565. self.emit('data', msg);
  1566. };
  1567. } else {
  1568. this._dc.onmessage = function(e) {
  1569. self._handleDataMessage(e);
  1570. };
  1571. }
  1572. this._dc.onclose = function(e) {
  1573. util.log('DataChannel closed for:', self.peer);
  1574. self.close();
  1575. };
  1576. }
  1577. // Handles a DataChannel message.
  1578. DataConnection.prototype._handleDataMessage = function(e) {
  1579. var self = this;
  1580. var data = e.data;
  1581. var datatype = data.constructor;
  1582. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  1583. if (datatype === Blob) {
  1584. // Datatype should never be blob
  1585. util.blobToArrayBuffer(data, function(ab) {
  1586. data = util.unpack(ab);
  1587. self.emit('data', data);
  1588. });
  1589. return;
  1590. } else if (datatype === ArrayBuffer) {
  1591. data = util.unpack(data);
  1592. } else if (datatype === String) {
  1593. // String fallback for binary data for browsers that don't support binary yet
  1594. var ab = util.binaryStringToArrayBuffer(data);
  1595. data = util.unpack(ab);
  1596. }
  1597. } else if (this.serialization === 'json') {
  1598. data = JSON.parse(data);
  1599. }
  1600. this.emit('data', data);
  1601. }
  1602. /**
  1603. * Exposed functionality for users.
  1604. */
  1605. /** Allows user to close connection. */
  1606. DataConnection.prototype.close = function() {
  1607. if (!this.open) {
  1608. return;
  1609. }
  1610. this.open = false;
  1611. Negotiator.cleanup(this);
  1612. this.emit('close');
  1613. }
  1614. /** Allows user to send data. */
  1615. DataConnection.prototype.send = function(data) {
  1616. if (!this.open) {
  1617. this.emit('error', new Error('Connection is not open. You should listen for the `open` event before sending messages.'));
  1618. return;
  1619. }
  1620. if (this._reliable) {
  1621. // Note: reliable shim sending will make it so that you cannot customize
  1622. // serialization.
  1623. this._reliable.send(data);
  1624. return;
  1625. }
  1626. var self = this;
  1627. if (this.serialization === 'json') {
  1628. this._dc.send(JSON.stringify(data));
  1629. } else if ('binary-utf8'.indexOf(this.serialization) !== -1) {
  1630. var utf8 = (this.serialization === 'binary-utf8');
  1631. var blob = util.pack(data, utf8);
  1632. // DataChannel currently only supports strings.
  1633. if (!util.supports.binary) {
  1634. util.blobToBinaryString(blob, function(str){
  1635. self._dc.send(str);
  1636. });
  1637. } else {
  1638. this._dc.send(blob);
  1639. }
  1640. } else {
  1641. this._dc.send(data);
  1642. }
  1643. }
  1644. DataConnection.prototype.handleMessage = function(message) {
  1645. var payload = message.payload;
  1646. switch (message.type) {
  1647. case 'ANSWER':
  1648. // Forward to negotiator
  1649. Negotiator.handleSDP(message.type, this, payload.sdp);
  1650. break;
  1651. case 'CANDIDATE':
  1652. Negotiator.handleCandidate(this, payload.candidate);
  1653. break;
  1654. default:
  1655. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  1656. break;
  1657. }
  1658. }
  1659. /**
  1660. * Wraps the streaming interface between two Peers.
  1661. */
  1662. function MediaConnection(peer, provider, options) {
  1663. if (!(this instanceof MediaConnection)) return new MediaConnection(peer, provider, options);
  1664. EventEmitter.call(this);
  1665. this.options = util.extend({}, options);
  1666. this.open = false;
  1667. this.type = 'media';
  1668. this.peer = peer;
  1669. this.provider = provider;
  1670. this.metadata = this.options.metadata;
  1671. this.localStream = this.options._stream;
  1672. this.id = this.options.connectionId || MediaConnection._idPrefix + util.randomToken();
  1673. if (this.localStream) {
  1674. Negotiator.startConnection(
  1675. this,
  1676. {_stream: this.localStream, originator: true}
  1677. );
  1678. }
  1679. };
  1680. util.inherits(MediaConnection, EventEmitter);
  1681. MediaConnection._idPrefix = 'mc_';
  1682. MediaConnection.prototype.addStream = function(remoteStream) {
  1683. util.log('Receiving stream', remoteStream);
  1684. this.remoteStream = remoteStream;
  1685. this.emit('stream', remoteStream); // Should we call this `open`?
  1686. };
  1687. MediaConnection.prototype.handleMessage = function(message) {
  1688. var payload = message.payload;
  1689. switch (message.type) {
  1690. case 'ANSWER':
  1691. // Forward to negotiator
  1692. Negotiator.handleSDP(message.type, this, payload.sdp);
  1693. this.open = true;
  1694. break;
  1695. case 'CANDIDATE':
  1696. Negotiator.handleCandidate(this, payload.candidate);
  1697. break;
  1698. default:
  1699. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  1700. break;
  1701. }
  1702. }
  1703. MediaConnection.prototype.answer = function(stream) {
  1704. if (this.localStream) {
  1705. util.warn('Local stream already exists on this MediaConnection. Are you answering a call twice?');
  1706. return;
  1707. }
  1708. this.options._payload._stream = stream;
  1709. this.localStream = stream;
  1710. Negotiator.startConnection(
  1711. this,
  1712. this.options._payload
  1713. )
  1714. // Retrieve lost messages stored because PeerConnection not set up.
  1715. var messages = this.provider._getMessages(this.id);
  1716. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  1717. this.handleMessage(messages[i]);
  1718. }
  1719. this.open = true;
  1720. };
  1721. /**
  1722. * Exposed functionality for users.
  1723. */
  1724. /** Allows user to close connection. */
  1725. MediaConnection.prototype.close = function() {
  1726. if (!this.open) {
  1727. return;
  1728. }
  1729. this.open = false;
  1730. Negotiator.cleanup(this);
  1731. this.emit('close')
  1732. };
  1733. /**
  1734. * Manages all negotiations between Peers.
  1735. */
  1736. var Negotiator = {
  1737. pcs: {
  1738. data: {},
  1739. media: {}
  1740. }, // type => {peerId: {pc_id: pc}}.
  1741. //providers: {}, // provider's id => providers (there may be multiple providers/client.
  1742. queue: [] // connections that are delayed due to a PC being in use.
  1743. }
  1744. Negotiator._idPrefix = 'pc_';
  1745. /** Returns a PeerConnection object set up correctly (for data, media). */
  1746. Negotiator.startConnection = function(connection, options) {
  1747. var pc = Negotiator._getPeerConnection(connection, options);
  1748. if (connection.type === 'media' && options._stream) {
  1749. // Add the stream.
  1750. pc.addStream(options._stream);
  1751. }
  1752. // Set the connection's PC.
  1753. connection.pc = pc;
  1754. // What do we need to do now?
  1755. if (options.originator) {
  1756. if (connection.type === 'data') {
  1757. // Create the datachannel.
  1758. var config = {};
  1759. if (util.supports.reliable && !options.reliable) {
  1760. // If we have canonical reliable support...
  1761. config = {maxRetransmits: 0}
  1762. }
  1763. var dc = pc.createDataChannel(connection.label, config);
  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. var 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' && connection.reliable) {
  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' && connection.reliable) {
  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, ice) {
  1973. var candidate = ice.candidate;
  1974. var sdpMLineIndex = ice.sdpMLineIndex;
  1975. connection.pc.addIceCandidate(new RTCIceCandidate({
  1976. sdpMLineIndex: sdpMLineIndex,
  1977. candidate: candidate
  1978. }));
  1979. util.log('Added ICE candidate for:', connection.peer);
  1980. }
  1981. /**
  1982. * An abstraction on top of WebSockets and XHR streaming to provide fastest
  1983. * possible connection for peers.
  1984. */
  1985. function Socket(secure, host, port, key) {
  1986. if (!(this instanceof Socket)) return new Socket(secure, host, port, key);
  1987. EventEmitter.call(this);
  1988. // Disconnected manually.
  1989. this.disconnected = false;
  1990. this._queue = [];
  1991. var httpProtocol = secure ? 'https://' : 'http://';
  1992. var wsProtocol = secure ? 'wss://' : 'ws://';
  1993. this._httpUrl = httpProtocol + host + ':' + port + '/' + key;
  1994. this._wsUrl = wsProtocol + host + ':' + port + '/peerjs?key=' + key;
  1995. }
  1996. util.inherits(Socket, EventEmitter);
  1997. /** Check in with ID or get one from server. */
  1998. Socket.prototype.start = function(id) {
  1999. this.id = id;
  2000. var token = util.randomToken();
  2001. this._httpUrl += '/' + id + '/' + token;
  2002. this._wsUrl += '&id='+id+'&token='+token;
  2003. this._startXhrStream();
  2004. this._startWebSocket();
  2005. }
  2006. /** Start up websocket communications. */
  2007. Socket.prototype._startWebSocket = function(id) {
  2008. var self = this;
  2009. if (this._socket) {
  2010. return;
  2011. }
  2012. this._socket = new WebSocket(this._wsUrl);
  2013. this._socket.onmessage = function(event) {
  2014. var data;
  2015. try {
  2016. data = JSON.parse(event.data);
  2017. } catch(e) {
  2018. util.log('Invalid server message', event.data);
  2019. return;
  2020. }
  2021. self.emit('message', data);
  2022. };
  2023. // Take care of the queue of connections if necessary and make sure Peer knows
  2024. // socket is open.
  2025. this._socket.onopen = function() {
  2026. if (self._timeout) {
  2027. clearTimeout(self._timeout);
  2028. setTimeout(function(){
  2029. self._http.abort();
  2030. self._http = null;
  2031. }, 5000);
  2032. }
  2033. self._sendQueuedMessages();
  2034. util.log('Socket open');
  2035. };
  2036. }
  2037. /** Start XHR streaming. */
  2038. Socket.prototype._startXhrStream = function(n) {
  2039. try {
  2040. var self = this;
  2041. this._http = new XMLHttpRequest();
  2042. this._http._index = 1;
  2043. this._http._streamIndex = n || 0;
  2044. this._http.open('post', this._httpUrl + '/id?i=' + this._http._streamIndex, true);
  2045. this._http.onreadystatechange = function() {
  2046. if (this.readyState == 2 && this.old) {
  2047. this.old.abort();
  2048. delete this.old;
  2049. }
  2050. if (this.readyState > 2 && this.status == 200 && this.responseText) {
  2051. self._handleStream(this);
  2052. }
  2053. };
  2054. this._http.send(null);
  2055. this._setHTTPTimeout();
  2056. } catch(e) {
  2057. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  2058. }
  2059. }
  2060. /** Handles onreadystatechange response as a stream. */
  2061. Socket.prototype._handleStream = function(http) {
  2062. // 3 and 4 are loading/done state. All others are not relevant.
  2063. var messages = http.responseText.split('\n');
  2064. // Check to see if anything needs to be processed on buffer.
  2065. if (http._buffer) {
  2066. while (http._buffer.length > 0) {
  2067. var index = http._buffer.shift();
  2068. var bufferedMessage = messages[index];
  2069. try {
  2070. bufferedMessage = JSON.parse(bufferedMessage);
  2071. } catch(e) {
  2072. http._buffer.shift(index);
  2073. break;
  2074. }
  2075. this.emit('message', bufferedMessage);
  2076. }
  2077. }
  2078. var message = messages[http._index];
  2079. if (message) {
  2080. http._index += 1;
  2081. // Buffering--this message is incomplete and we'll get to it next time.
  2082. // This checks if the httpResponse ended in a `\n`, in which case the last
  2083. // element of messages should be the empty string.
  2084. if (http._index === messages.length) {
  2085. if (!http._buffer) {
  2086. http._buffer = [];
  2087. }
  2088. http._buffer.push(http._index - 1);
  2089. } else {
  2090. try {
  2091. message = JSON.parse(message);
  2092. } catch(e) {
  2093. util.log('Invalid server message', message);
  2094. return;
  2095. }
  2096. this.emit('message', message);
  2097. }
  2098. }
  2099. }
  2100. Socket.prototype._setHTTPTimeout = function() {
  2101. var self = this;
  2102. this._timeout = setTimeout(function() {
  2103. var old = self._http;
  2104. if (!self._wsOpen()) {
  2105. self._startXhrStream(old._streamIndex + 1);
  2106. self._http.old = old;
  2107. } else {
  2108. old.abort();
  2109. }
  2110. }, 25000);
  2111. }
  2112. /** Is the websocket currently open? */
  2113. Socket.prototype._wsOpen = function() {
  2114. return this._socket && this._socket.readyState == 1;
  2115. }
  2116. /** Send queued messages. */
  2117. Socket.prototype._sendQueuedMessages = function() {
  2118. for (var i = 0, ii = this._queue.length; i < ii; i += 1) {
  2119. this.send(this._queue[i]);
  2120. }
  2121. }
  2122. /** Exposed send for DC & Peer. */
  2123. Socket.prototype.send = function(data) {
  2124. if (this.disconnected) {
  2125. return;
  2126. }
  2127. // If we didn't get an ID yet, we can't yet send anything so we should queue
  2128. // up these messages.
  2129. if (!this.id) {
  2130. this._queue.push(data);
  2131. return;
  2132. }
  2133. if (!data.type) {
  2134. this.emit('error', 'Invalid message');
  2135. return;
  2136. }
  2137. var message = JSON.stringify(data);
  2138. if (this._wsOpen()) {
  2139. this._socket.send(message);
  2140. } else {
  2141. var http = new XMLHttpRequest();
  2142. var url = this._httpUrl + '/' + data.type.toLowerCase();
  2143. http.open('post', url, true);
  2144. http.setRequestHeader('Content-Type', 'application/json');
  2145. http.send(message);
  2146. }
  2147. }
  2148. Socket.prototype.close = function() {
  2149. if (!this.disconnected && this._wsOpen()) {
  2150. this._socket.close();
  2151. this.disconnected = true;
  2152. }
  2153. }
  2154. })(this);