peer.js 64 KB

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