peer.js 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708
  1. /*! peerjs.js build:0.3.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){
  61. var packer = new Packer();
  62. packer.pack(data);
  63. var buffer = packer.getBuffer();
  64. return buffer;
  65. }
  66. };
  67. function Unpacker (data){
  68. // Data is ArrayBuffer
  69. this.index = 0;
  70. this.dataBuffer = data;
  71. this.dataView = new Uint8Array(this.dataBuffer);
  72. this.length = this.dataBuffer.byteLength;
  73. }
  74. Unpacker.prototype.unpack = function(){
  75. var type = this.unpack_uint8();
  76. if (type < 0x80){
  77. var positive_fixnum = type;
  78. return positive_fixnum;
  79. } else if ((type ^ 0xe0) < 0x20){
  80. var negative_fixnum = (type ^ 0xe0) - 0x20;
  81. return negative_fixnum;
  82. }
  83. var size;
  84. if ((size = type ^ 0xa0) <= 0x0f){
  85. return this.unpack_raw(size);
  86. } else if ((size = type ^ 0xb0) <= 0x0f){
  87. return this.unpack_string(size);
  88. } else if ((size = type ^ 0x90) <= 0x0f){
  89. return this.unpack_array(size);
  90. } else if ((size = type ^ 0x80) <= 0x0f){
  91. return this.unpack_map(size);
  92. }
  93. switch(type){
  94. case 0xc0:
  95. return null;
  96. case 0xc1:
  97. return undefined;
  98. case 0xc2:
  99. return false;
  100. case 0xc3:
  101. return true;
  102. case 0xca:
  103. return this.unpack_float();
  104. case 0xcb:
  105. return this.unpack_double();
  106. case 0xcc:
  107. return this.unpack_uint8();
  108. case 0xcd:
  109. return this.unpack_uint16();
  110. case 0xce:
  111. return this.unpack_uint32();
  112. case 0xcf:
  113. return this.unpack_uint64();
  114. case 0xd0:
  115. return this.unpack_int8();
  116. case 0xd1:
  117. return this.unpack_int16();
  118. case 0xd2:
  119. return this.unpack_int32();
  120. case 0xd3:
  121. return this.unpack_int64();
  122. case 0xd4:
  123. return undefined;
  124. case 0xd5:
  125. return undefined;
  126. case 0xd6:
  127. return undefined;
  128. case 0xd7:
  129. return undefined;
  130. case 0xd8:
  131. size = this.unpack_uint16();
  132. return this.unpack_string(size);
  133. case 0xd9:
  134. size = this.unpack_uint32();
  135. return this.unpack_string(size);
  136. case 0xda:
  137. size = this.unpack_uint16();
  138. return this.unpack_raw(size);
  139. case 0xdb:
  140. size = this.unpack_uint32();
  141. return this.unpack_raw(size);
  142. case 0xdc:
  143. size = this.unpack_uint16();
  144. return this.unpack_array(size);
  145. case 0xdd:
  146. size = this.unpack_uint32();
  147. return this.unpack_array(size);
  148. case 0xde:
  149. size = this.unpack_uint16();
  150. return this.unpack_map(size);
  151. case 0xdf:
  152. size = this.unpack_uint32();
  153. return this.unpack_map(size);
  154. }
  155. }
  156. Unpacker.prototype.unpack_uint8 = function(){
  157. var byte = this.dataView[this.index] & 0xff;
  158. this.index++;
  159. return byte;
  160. };
  161. Unpacker.prototype.unpack_uint16 = function(){
  162. var bytes = this.read(2);
  163. var uint16 =
  164. ((bytes[0] & 0xff) * 256) + (bytes[1] & 0xff);
  165. this.index += 2;
  166. return uint16;
  167. }
  168. Unpacker.prototype.unpack_uint32 = function(){
  169. var bytes = this.read(4);
  170. var uint32 =
  171. ((bytes[0] * 256 +
  172. bytes[1]) * 256 +
  173. bytes[2]) * 256 +
  174. bytes[3];
  175. this.index += 4;
  176. return uint32;
  177. }
  178. Unpacker.prototype.unpack_uint64 = function(){
  179. var bytes = this.read(8);
  180. var uint64 =
  181. ((((((bytes[0] * 256 +
  182. bytes[1]) * 256 +
  183. bytes[2]) * 256 +
  184. bytes[3]) * 256 +
  185. bytes[4]) * 256 +
  186. bytes[5]) * 256 +
  187. bytes[6]) * 256 +
  188. bytes[7];
  189. this.index += 8;
  190. return uint64;
  191. }
  192. Unpacker.prototype.unpack_int8 = function(){
  193. var uint8 = this.unpack_uint8();
  194. return (uint8 < 0x80 ) ? uint8 : uint8 - (1 << 8);
  195. };
  196. Unpacker.prototype.unpack_int16 = function(){
  197. var uint16 = this.unpack_uint16();
  198. return (uint16 < 0x8000 ) ? uint16 : uint16 - (1 << 16);
  199. }
  200. Unpacker.prototype.unpack_int32 = function(){
  201. var uint32 = this.unpack_uint32();
  202. return (uint32 < Math.pow(2, 31) ) ? uint32 :
  203. uint32 - Math.pow(2, 32);
  204. }
  205. Unpacker.prototype.unpack_int64 = function(){
  206. var uint64 = this.unpack_uint64();
  207. return (uint64 < Math.pow(2, 63) ) ? uint64 :
  208. uint64 - Math.pow(2, 64);
  209. }
  210. Unpacker.prototype.unpack_raw = function(size){
  211. if ( this.length < this.index + size){
  212. throw new Error('BinaryPackFailure: index is out of range'
  213. + ' ' + this.index + ' ' + size + ' ' + this.length);
  214. }
  215. var buf = this.dataBuffer.slice(this.index, this.index + size);
  216. this.index += size;
  217. //buf = util.bufferToString(buf);
  218. return buf;
  219. }
  220. Unpacker.prototype.unpack_string = function(size){
  221. var bytes = this.read(size);
  222. var i = 0, str = '', c, code;
  223. while(i < size){
  224. c = bytes[i];
  225. if ( c < 128){
  226. str += String.fromCharCode(c);
  227. i++;
  228. } else if ((c ^ 0xc0) < 32){
  229. code = ((c ^ 0xc0) << 6) | (bytes[i+1] & 63);
  230. str += String.fromCharCode(code);
  231. i += 2;
  232. } else {
  233. code = ((c & 15) << 12) | ((bytes[i+1] & 63) << 6) |
  234. (bytes[i+2] & 63);
  235. str += String.fromCharCode(code);
  236. i += 3;
  237. }
  238. }
  239. this.index += size;
  240. return str;
  241. }
  242. Unpacker.prototype.unpack_array = function(size){
  243. var objects = new Array(size);
  244. for(var i = 0; i < size ; i++){
  245. objects[i] = this.unpack();
  246. }
  247. return objects;
  248. }
  249. Unpacker.prototype.unpack_map = function(size){
  250. var map = {};
  251. for(var i = 0; i < size ; i++){
  252. var key = this.unpack();
  253. var value = this.unpack();
  254. map[key] = value;
  255. }
  256. return map;
  257. }
  258. Unpacker.prototype.unpack_float = function(){
  259. var uint32 = this.unpack_uint32();
  260. var sign = uint32 >> 31;
  261. var exp = ((uint32 >> 23) & 0xff) - 127;
  262. var fraction = ( uint32 & 0x7fffff ) | 0x800000;
  263. return (sign == 0 ? 1 : -1) *
  264. fraction * Math.pow(2, exp - 23);
  265. }
  266. Unpacker.prototype.unpack_double = function(){
  267. var h32 = this.unpack_uint32();
  268. var l32 = this.unpack_uint32();
  269. var sign = h32 >> 31;
  270. var exp = ((h32 >> 20) & 0x7ff) - 1023;
  271. var hfrac = ( h32 & 0xfffff ) | 0x100000;
  272. var frac = hfrac * Math.pow(2, exp - 20) +
  273. l32 * Math.pow(2, exp - 52);
  274. return (sign == 0 ? 1 : -1) * frac;
  275. }
  276. Unpacker.prototype.read = function(length){
  277. var j = this.index;
  278. if (j + length <= this.length) {
  279. return this.dataView.subarray(j, j + length);
  280. } else {
  281. throw new Error('BinaryPackFailure: read index out of range');
  282. }
  283. }
  284. function Packer(){
  285. this.bufferBuilder = new BufferBuilder();
  286. }
  287. Packer.prototype.getBuffer = function(){
  288. return this.bufferBuilder.getBuffer();
  289. }
  290. Packer.prototype.pack = function(value){
  291. var type = typeof(value);
  292. if (type == 'string'){
  293. this.pack_string(value);
  294. } else if (type == 'number'){
  295. if (Math.floor(value) === value){
  296. this.pack_integer(value);
  297. } else{
  298. this.pack_double(value);
  299. }
  300. } else if (type == 'boolean'){
  301. if (value === true){
  302. this.bufferBuilder.append(0xc3);
  303. } else if (value === false){
  304. this.bufferBuilder.append(0xc2);
  305. }
  306. } else if (type == 'undefined'){
  307. this.bufferBuilder.append(0xc0);
  308. } else if (type == 'object'){
  309. if (value === null){
  310. this.bufferBuilder.append(0xc0);
  311. } else {
  312. var constructor = value.constructor;
  313. if (constructor == Array){
  314. this.pack_array(value);
  315. } else if (constructor == Blob || constructor == File) {
  316. this.pack_bin(value);
  317. } else if (constructor == ArrayBuffer) {
  318. if(binaryFeatures.useArrayBufferView) {
  319. this.pack_bin(new Uint8Array(value));
  320. } else {
  321. this.pack_bin(value);
  322. }
  323. } else if ('BYTES_PER_ELEMENT' in value){
  324. if(binaryFeatures.useArrayBufferView) {
  325. this.pack_bin(new Uint8Array(value.buffer));
  326. } else {
  327. this.pack_bin(value.buffer);
  328. }
  329. } else if (constructor == Object){
  330. this.pack_object(value);
  331. } else if (constructor == Date){
  332. this.pack_string(value.toString());
  333. } else if (typeof value.toBinaryPack == 'function'){
  334. this.bufferBuilder.append(value.toBinaryPack());
  335. } else {
  336. throw new Error('Type "' + constructor.toString() + '" not yet supported');
  337. }
  338. }
  339. } else {
  340. throw new Error('Type "' + type + '" not yet supported');
  341. }
  342. this.bufferBuilder.flush();
  343. }
  344. Packer.prototype.pack_bin = function(blob){
  345. var length = blob.length || blob.byteLength || blob.size;
  346. if (length <= 0x0f){
  347. this.pack_uint8(0xa0 + length);
  348. } else if (length <= 0xffff){
  349. this.bufferBuilder.append(0xda) ;
  350. this.pack_uint16(length);
  351. } else if (length <= 0xffffffff){
  352. this.bufferBuilder.append(0xdb);
  353. this.pack_uint32(length);
  354. } else{
  355. throw new Error('Invalid length');
  356. return;
  357. }
  358. this.bufferBuilder.append(blob);
  359. }
  360. Packer.prototype.pack_string = function(str){
  361. var length = utf8Length(str);
  362. if (length <= 0x0f){
  363. this.pack_uint8(0xb0 + length);
  364. } else if (length <= 0xffff){
  365. this.bufferBuilder.append(0xd8) ;
  366. this.pack_uint16(length);
  367. } else if (length <= 0xffffffff){
  368. this.bufferBuilder.append(0xd9);
  369. this.pack_uint32(length);
  370. } else{
  371. throw new Error('Invalid length');
  372. return;
  373. }
  374. this.bufferBuilder.append(str);
  375. }
  376. Packer.prototype.pack_array = function(ary){
  377. var length = ary.length;
  378. if (length <= 0x0f){
  379. this.pack_uint8(0x90 + length);
  380. } else if (length <= 0xffff){
  381. this.bufferBuilder.append(0xdc)
  382. this.pack_uint16(length);
  383. } else if (length <= 0xffffffff){
  384. this.bufferBuilder.append(0xdd);
  385. this.pack_uint32(length);
  386. } else{
  387. throw new Error('Invalid length');
  388. }
  389. for(var i = 0; i < length ; i++){
  390. this.pack(ary[i]);
  391. }
  392. }
  393. Packer.prototype.pack_integer = function(num){
  394. if ( -0x20 <= num && num <= 0x7f){
  395. this.bufferBuilder.append(num & 0xff);
  396. } else if (0x00 <= num && num <= 0xff){
  397. this.bufferBuilder.append(0xcc);
  398. this.pack_uint8(num);
  399. } else if (-0x80 <= num && num <= 0x7f){
  400. this.bufferBuilder.append(0xd0);
  401. this.pack_int8(num);
  402. } else if ( 0x0000 <= num && num <= 0xffff){
  403. this.bufferBuilder.append(0xcd);
  404. this.pack_uint16(num);
  405. } else if (-0x8000 <= num && num <= 0x7fff){
  406. this.bufferBuilder.append(0xd1);
  407. this.pack_int16(num);
  408. } else if ( 0x00000000 <= num && num <= 0xffffffff){
  409. this.bufferBuilder.append(0xce);
  410. this.pack_uint32(num);
  411. } else if (-0x80000000 <= num && num <= 0x7fffffff){
  412. this.bufferBuilder.append(0xd2);
  413. this.pack_int32(num);
  414. } else if (-0x8000000000000000 <= num && num <= 0x7FFFFFFFFFFFFFFF){
  415. this.bufferBuilder.append(0xd3);
  416. this.pack_int64(num);
  417. } else if (0x0000000000000000 <= num && num <= 0xFFFFFFFFFFFFFFFF){
  418. this.bufferBuilder.append(0xcf);
  419. this.pack_uint64(num);
  420. } else{
  421. throw new Error('Invalid integer');
  422. }
  423. }
  424. Packer.prototype.pack_double = function(num){
  425. var sign = 0;
  426. if (num < 0){
  427. sign = 1;
  428. num = -num;
  429. }
  430. var exp = Math.floor(Math.log(num) / Math.LN2);
  431. var frac0 = num / Math.pow(2, exp) - 1;
  432. var frac1 = Math.floor(frac0 * Math.pow(2, 52));
  433. var b32 = Math.pow(2, 32);
  434. var h32 = (sign << 31) | ((exp+1023) << 20) |
  435. (frac1 / b32) & 0x0fffff;
  436. var l32 = frac1 % b32;
  437. this.bufferBuilder.append(0xcb);
  438. this.pack_int32(h32);
  439. this.pack_int32(l32);
  440. }
  441. Packer.prototype.pack_object = function(obj){
  442. var keys = Object.keys(obj);
  443. var length = keys.length;
  444. if (length <= 0x0f){
  445. this.pack_uint8(0x80 + length);
  446. } else if (length <= 0xffff){
  447. this.bufferBuilder.append(0xde);
  448. this.pack_uint16(length);
  449. } else if (length <= 0xffffffff){
  450. this.bufferBuilder.append(0xdf);
  451. this.pack_uint32(length);
  452. } else{
  453. throw new Error('Invalid length');
  454. }
  455. for(var prop in obj){
  456. if (obj.hasOwnProperty(prop)){
  457. this.pack(prop);
  458. this.pack(obj[prop]);
  459. }
  460. }
  461. }
  462. Packer.prototype.pack_uint8 = function(num){
  463. this.bufferBuilder.append(num);
  464. }
  465. Packer.prototype.pack_uint16 = function(num){
  466. this.bufferBuilder.append(num >> 8);
  467. this.bufferBuilder.append(num & 0xff);
  468. }
  469. Packer.prototype.pack_uint32 = function(num){
  470. var n = num & 0xffffffff;
  471. this.bufferBuilder.append((n & 0xff000000) >>> 24);
  472. this.bufferBuilder.append((n & 0x00ff0000) >>> 16);
  473. this.bufferBuilder.append((n & 0x0000ff00) >>> 8);
  474. this.bufferBuilder.append((n & 0x000000ff));
  475. }
  476. Packer.prototype.pack_uint64 = function(num){
  477. var high = num / Math.pow(2, 32);
  478. var low = num % Math.pow(2, 32);
  479. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  480. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  481. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  482. this.bufferBuilder.append((high & 0x000000ff));
  483. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  484. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  485. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  486. this.bufferBuilder.append((low & 0x000000ff));
  487. }
  488. Packer.prototype.pack_int8 = function(num){
  489. this.bufferBuilder.append(num & 0xff);
  490. }
  491. Packer.prototype.pack_int16 = function(num){
  492. this.bufferBuilder.append((num & 0xff00) >> 8);
  493. this.bufferBuilder.append(num & 0xff);
  494. }
  495. Packer.prototype.pack_int32 = function(num){
  496. this.bufferBuilder.append((num >>> 24) & 0xff);
  497. this.bufferBuilder.append((num & 0x00ff0000) >>> 16);
  498. this.bufferBuilder.append((num & 0x0000ff00) >>> 8);
  499. this.bufferBuilder.append((num & 0x000000ff));
  500. }
  501. Packer.prototype.pack_int64 = function(num){
  502. var high = Math.floor(num / Math.pow(2, 32));
  503. var low = num % Math.pow(2, 32);
  504. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  505. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  506. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  507. this.bufferBuilder.append((high & 0x000000ff));
  508. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  509. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  510. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  511. this.bufferBuilder.append((low & 0x000000ff));
  512. }
  513. function _utf8Replace(m){
  514. var code = m.charCodeAt(0);
  515. if(code <= 0x7ff) return '00';
  516. if(code <= 0xffff) return '000';
  517. if(code <= 0x1fffff) return '0000';
  518. if(code <= 0x3ffffff) return '00000';
  519. return '000000';
  520. }
  521. function utf8Length(str){
  522. if (str.length > 600) {
  523. // Blob method faster for large strings
  524. return (new Blob([str])).size;
  525. } else {
  526. return str.replace(/[^\u0000-\u007F]/g, _utf8Replace).length;
  527. }
  528. }
  529. /**
  530. * Light EventEmitter. Ported from Node.js/events.js
  531. * Eric Zhang
  532. */
  533. /**
  534. * EventEmitter class
  535. * Creates an object with event registering and firing methods
  536. */
  537. function EventEmitter() {
  538. // Initialise required storage variables
  539. this._events = {};
  540. }
  541. var isArray = Array.isArray;
  542. EventEmitter.prototype.addListener = function(type, listener, scope, once) {
  543. if ('function' !== typeof listener) {
  544. throw new Error('addListener only takes instances of Function');
  545. }
  546. // To avoid recursion in the case that type == "newListeners"! Before
  547. // adding it to the listeners, first emit "newListeners".
  548. this.emit('newListener', type, typeof listener.listener === 'function' ?
  549. listener.listener : listener);
  550. if (!this._events[type]) {
  551. // Optimize the case of one listener. Don't need the extra array object.
  552. this._events[type] = listener;
  553. } else if (isArray(this._events[type])) {
  554. // If we've already got an array, just append.
  555. this._events[type].push(listener);
  556. } else {
  557. // Adding the second element, need to change to array.
  558. this._events[type] = [this._events[type], listener];
  559. }
  560. return this;
  561. };
  562. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  563. EventEmitter.prototype.once = function(type, listener, scope) {
  564. if ('function' !== typeof listener) {
  565. throw new Error('.once only takes instances of Function');
  566. }
  567. var self = this;
  568. function g() {
  569. self.removeListener(type, g);
  570. listener.apply(this, arguments);
  571. };
  572. g.listener = listener;
  573. self.on(type, g);
  574. return this;
  575. };
  576. EventEmitter.prototype.removeListener = function(type, listener, scope) {
  577. if ('function' !== typeof listener) {
  578. throw new Error('removeListener only takes instances of Function');
  579. }
  580. // does not use listeners(), so no side effect of creating _events[type]
  581. if (!this._events[type]) return this;
  582. var list = this._events[type];
  583. if (isArray(list)) {
  584. var position = -1;
  585. for (var i = 0, length = list.length; i < length; i++) {
  586. if (list[i] === listener ||
  587. (list[i].listener && list[i].listener === listener))
  588. {
  589. position = i;
  590. break;
  591. }
  592. }
  593. if (position < 0) return this;
  594. list.splice(position, 1);
  595. if (list.length == 0)
  596. delete this._events[type];
  597. } else if (list === listener ||
  598. (list.listener && list.listener === listener))
  599. {
  600. delete this._events[type];
  601. }
  602. return this;
  603. };
  604. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  605. EventEmitter.prototype.removeAllListeners = function(type) {
  606. if (arguments.length === 0) {
  607. this._events = {};
  608. return this;
  609. }
  610. // does not use listeners(), so no side effect of creating _events[type]
  611. if (type && this._events && this._events[type]) this._events[type] = null;
  612. return this;
  613. };
  614. EventEmitter.prototype.listeners = function(type) {
  615. if (!this._events[type]) this._events[type] = [];
  616. if (!isArray(this._events[type])) {
  617. this._events[type] = [this._events[type]];
  618. }
  619. return this._events[type];
  620. };
  621. EventEmitter.prototype.emit = function(type) {
  622. var type = arguments[0];
  623. var handler = this._events[type];
  624. if (!handler) return false;
  625. if (typeof handler == 'function') {
  626. switch (arguments.length) {
  627. // fast cases
  628. case 1:
  629. handler.call(this);
  630. break;
  631. case 2:
  632. handler.call(this, arguments[1]);
  633. break;
  634. case 3:
  635. handler.call(this, arguments[1], arguments[2]);
  636. break;
  637. // slower
  638. default:
  639. var l = arguments.length;
  640. var args = new Array(l - 1);
  641. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  642. handler.apply(this, args);
  643. }
  644. return true;
  645. } else if (isArray(handler)) {
  646. var l = arguments.length;
  647. var args = new Array(l - 1);
  648. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  649. var listeners = handler.slice();
  650. for (var i = 0, l = listeners.length; i < l; i++) {
  651. listeners[i].apply(this, args);
  652. }
  653. return true;
  654. } else {
  655. return false;
  656. }
  657. };
  658. /**
  659. * Reliable transfer for Chrome Canary DataChannel impl.
  660. * Author: @michellebu
  661. */
  662. function Reliable(dc, debug) {
  663. if (!(this instanceof Reliable)) return new Reliable(dc);
  664. this._dc = dc;
  665. util.debug = debug;
  666. // Messages sent/received so far.
  667. // id: { ack: n, chunks: [...] }
  668. this._outgoing = {};
  669. // id: { ack: ['ack', id, n], chunks: [...] }
  670. this._incoming = {};
  671. this._received = {};
  672. // Window size.
  673. this._window = 1000;
  674. // MTU.
  675. this._mtu = 500;
  676. // Interval for setInterval. In ms.
  677. this._interval = 0;
  678. // Messages sent.
  679. this._count = 0;
  680. // Outgoing message queue.
  681. this._queue = [];
  682. this._setupDC();
  683. };
  684. // Send a message reliably.
  685. Reliable.prototype.send = function(msg) {
  686. // Determine if chunking is necessary.
  687. var bl = util.pack(msg);
  688. if (bl.size < this._mtu) {
  689. this._handleSend(['no', bl]);
  690. return;
  691. }
  692. this._outgoing[this._count] = {
  693. ack: 0,
  694. chunks: this._chunk(bl)
  695. };
  696. if (util.debug) {
  697. this._outgoing[this._count].timer = new Date();
  698. }
  699. // Send prelim window.
  700. this._sendWindowedChunks(this._count);
  701. this._count += 1;
  702. };
  703. // Set up interval for processing queue.
  704. Reliable.prototype._setupInterval = function() {
  705. // TODO: fail gracefully.
  706. var self = this;
  707. this._timeout = setInterval(function() {
  708. // FIXME: String stuff makes things terribly async.
  709. var msg = self._queue.shift();
  710. if (msg._multiple) {
  711. for (var i = 0, ii = msg.length; i < ii; i += 1) {
  712. self._intervalSend(msg[i]);
  713. }
  714. } else {
  715. self._intervalSend(msg);
  716. }
  717. }, this._interval);
  718. };
  719. Reliable.prototype._intervalSend = function(msg) {
  720. var self = this;
  721. msg = util.pack(msg);
  722. util.blobToBinaryString(msg, function(str) {
  723. self._dc.send(str);
  724. });
  725. if (self._queue.length === 0) {
  726. clearTimeout(self._timeout);
  727. self._timeout = null;
  728. //self._processAcks();
  729. }
  730. };
  731. // Go through ACKs to send missing pieces.
  732. Reliable.prototype._processAcks = function() {
  733. for (var id in this._outgoing) {
  734. if (this._outgoing.hasOwnProperty(id)) {
  735. this._sendWindowedChunks(id);
  736. }
  737. }
  738. };
  739. // Handle sending a message.
  740. // FIXME: Don't wait for interval time for all messages...
  741. Reliable.prototype._handleSend = function(msg) {
  742. var push = true;
  743. for (var i = 0, ii = this._queue.length; i < ii; i += 1) {
  744. var item = this._queue[i];
  745. if (item === msg) {
  746. push = false;
  747. } else if (item._multiple && item.indexOf(msg) !== -1) {
  748. push = false;
  749. }
  750. }
  751. if (push) {
  752. this._queue.push(msg);
  753. if (!this._timeout) {
  754. this._setupInterval();
  755. }
  756. }
  757. };
  758. // Set up DataChannel handlers.
  759. Reliable.prototype._setupDC = function() {
  760. // Handle various message types.
  761. var self = this;
  762. this._dc.onmessage = function(e) {
  763. var msg = e.data;
  764. var datatype = msg.constructor;
  765. // FIXME: msg is String until binary is supported.
  766. // Once that happens, this will have to be smarter.
  767. if (datatype === String) {
  768. var ab = util.binaryStringToArrayBuffer(msg);
  769. msg = util.unpack(ab);
  770. self._handleMessage(msg);
  771. }
  772. };
  773. };
  774. // Handles an incoming message.
  775. Reliable.prototype._handleMessage = function(msg) {
  776. var id = msg[1];
  777. var idata = this._incoming[id];
  778. var odata = this._outgoing[id];
  779. var data;
  780. switch (msg[0]) {
  781. // No chunking was done.
  782. case 'no':
  783. var message = id;
  784. if (!!message) {
  785. this.onmessage(util.unpack(message));
  786. }
  787. break;
  788. // Reached the end of the message.
  789. case 'end':
  790. data = idata;
  791. // In case end comes first.
  792. this._received[id] = msg[2];
  793. if (!data) {
  794. break;
  795. }
  796. this._ack(id);
  797. break;
  798. case 'ack':
  799. data = odata;
  800. if (!!data) {
  801. var ack = msg[2];
  802. // Take the larger ACK, for out of order messages.
  803. data.ack = Math.max(ack, data.ack);
  804. // Clean up when all chunks are ACKed.
  805. if (data.ack >= data.chunks.length) {
  806. util.log('Time: ', new Date() - data.timer);
  807. delete this._outgoing[id];
  808. } else {
  809. this._processAcks();
  810. }
  811. }
  812. // If !data, just ignore.
  813. break;
  814. // Received a chunk of data.
  815. case 'chunk':
  816. // Create a new entry if none exists.
  817. data = idata;
  818. if (!data) {
  819. var end = this._received[id];
  820. if (end === true) {
  821. break;
  822. }
  823. data = {
  824. ack: ['ack', id, 0],
  825. chunks: []
  826. };
  827. this._incoming[id] = data;
  828. }
  829. var n = msg[2];
  830. var chunk = msg[3];
  831. data.chunks[n] = new Uint8Array(chunk);
  832. // If we get the chunk we're looking for, ACK for next missing.
  833. // Otherwise, ACK the same N again.
  834. if (n === data.ack[2]) {
  835. this._calculateNextAck(id);
  836. }
  837. this._ack(id);
  838. break;
  839. default:
  840. // Shouldn't happen, but would make sense for message to just go
  841. // through as is.
  842. this._handleSend(msg);
  843. break;
  844. }
  845. };
  846. // Chunks BL into smaller messages.
  847. Reliable.prototype._chunk = function(bl) {
  848. var chunks = [];
  849. var size = bl.size;
  850. var start = 0;
  851. while (start < size) {
  852. var end = Math.min(size, start + this._mtu);
  853. var b = bl.slice(start, end);
  854. var chunk = {
  855. payload: b
  856. }
  857. chunks.push(chunk);
  858. start = end;
  859. }
  860. util.log('Created', chunks.length, 'chunks.');
  861. return chunks;
  862. };
  863. // Sends ACK N, expecting Nth blob chunk for message ID.
  864. Reliable.prototype._ack = function(id) {
  865. var ack = this._incoming[id].ack;
  866. // if ack is the end value, then call _complete.
  867. if (this._received[id] === ack[2]) {
  868. this._complete(id);
  869. this._received[id] = true;
  870. }
  871. this._handleSend(ack);
  872. };
  873. // Calculates the next ACK number, given chunks.
  874. Reliable.prototype._calculateNextAck = function(id) {
  875. var data = this._incoming[id];
  876. var chunks = data.chunks;
  877. for (var i = 0, ii = chunks.length; i < ii; i += 1) {
  878. // This chunk is missing!!! Better ACK for it.
  879. if (chunks[i] === undefined) {
  880. data.ack[2] = i;
  881. return;
  882. }
  883. }
  884. data.ack[2] = chunks.length;
  885. };
  886. // Sends the next window of chunks.
  887. Reliable.prototype._sendWindowedChunks = function(id) {
  888. util.log('sendWindowedChunks for: ', id);
  889. var data = this._outgoing[id];
  890. var ch = data.chunks;
  891. var chunks = [];
  892. var limit = Math.min(data.ack + this._window, ch.length);
  893. for (var i = data.ack; i < limit; i += 1) {
  894. if (!ch[i].sent || i === data.ack) {
  895. ch[i].sent = true;
  896. chunks.push(['chunk', id, i, ch[i].payload]);
  897. }
  898. }
  899. if (data.ack + this._window >= ch.length) {
  900. chunks.push(['end', id, ch.length])
  901. }
  902. chunks._multiple = true;
  903. this._handleSend(chunks);
  904. };
  905. // Puts together a message from chunks.
  906. Reliable.prototype._complete = function(id) {
  907. util.log('Completed called for', id);
  908. var self = this;
  909. var chunks = this._incoming[id].chunks;
  910. var bl = new Blob(chunks);
  911. util.blobToArrayBuffer(bl, function(ab) {
  912. self.onmessage(util.unpack(ab));
  913. });
  914. delete this._incoming[id];
  915. };
  916. // Ups bandwidth limit on SDP. Meant to be called during offer/answer.
  917. Reliable.higherBandwidthSDP = function(sdp) {
  918. // AS stands for Application-Specific Maximum.
  919. // Bandwidth number is in kilobits / sec.
  920. // See RFC for more info: http://www.ietf.org/rfc/rfc2327.txt
  921. // Chrome 31+ doesn't want us munging the SDP, so we'll let them have their
  922. // way.
  923. var version = navigator.appVersion.match(/Chrome\/(.*?) /);
  924. if (version) {
  925. version = parseInt(version[1].split('.').shift());
  926. if (version < 31) {
  927. var parts = sdp.split('b=AS:30');
  928. var replace = 'b=AS:102400'; // 100 Mbps
  929. if (parts.length > 1) {
  930. return parts[0] + replace + parts[1];
  931. }
  932. }
  933. }
  934. return sdp;
  935. };
  936. // Overwritten, typically.
  937. Reliable.prototype.onmessage = function(msg) {};
  938. exports.Reliable = Reliable;
  939. exports.RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription;
  940. exports.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  941. exports.RTCIceCandidate = window.RTCIceCandidate || window.mozRTCIceCandidate;
  942. var defaultConfig = {'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }]};
  943. var dataCount = 1;
  944. var util = {
  945. noop: function() {},
  946. CLOUD_HOST: '0.peerjs.com',
  947. CLOUD_PORT: 9000,
  948. // Browsers that need chunking:
  949. chunkedBrowsers: {'Chrome': 1},
  950. chunkedMTU: 16300, // The original 60000 bytes setting does not work when sending data from Firefox to Chrome, which is "cut off" after 16384 bytes and delivered individually.
  951. // Logging logic
  952. logLevel: 0,
  953. setLogLevel: function(level) {
  954. var debugLevel = parseInt(level, 10);
  955. if (!isNaN(parseInt(level, 10))) {
  956. util.logLevel = debugLevel;
  957. } else {
  958. // If they are using truthy/falsy values for debug
  959. util.logLevel = level ? 3 : 0;
  960. }
  961. util.log = util.warn = util.error = util.noop;
  962. if (util.logLevel > 0) {
  963. util.error = util._printWith('ERROR');
  964. }
  965. if (util.logLevel > 1) {
  966. util.warn = util._printWith('WARNING');
  967. }
  968. if (util.logLevel > 2) {
  969. util.log = util._print;
  970. }
  971. },
  972. setLogFunction: function(fn) {
  973. if (fn.constructor !== Function) {
  974. util.warn('The log function you passed in is not a function. Defaulting to regular logs.');
  975. } else {
  976. util._print = fn;
  977. }
  978. },
  979. _printWith: function(prefix) {
  980. return function() {
  981. var copy = Array.prototype.slice.call(arguments);
  982. copy.unshift(prefix);
  983. util._print.apply(util, copy);
  984. };
  985. },
  986. _print: function () {
  987. var err = false;
  988. var copy = Array.prototype.slice.call(arguments);
  989. copy.unshift('PeerJS: ');
  990. for (var i = 0, l = copy.length; i < l; i++){
  991. if (copy[i] instanceof Error) {
  992. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  993. err = true;
  994. }
  995. }
  996. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  997. },
  998. //
  999. // Returns browser-agnostic default config
  1000. defaultConfig: defaultConfig,
  1001. //
  1002. // Returns the current browser.
  1003. browser: (function() {
  1004. if (window.mozRTCPeerConnection) {
  1005. return 'Firefox';
  1006. } else if (window.webkitRTCPeerConnection) {
  1007. return 'Chrome';
  1008. } else if (window.RTCPeerConnection) {
  1009. return 'Supported';
  1010. } else {
  1011. return 'Unsupported';
  1012. }
  1013. })(),
  1014. //
  1015. // Lists which features are supported
  1016. supports: (function() {
  1017. if (typeof RTCPeerConnection === 'undefined') {
  1018. return {};
  1019. }
  1020. var data = true;
  1021. var audioVideo = true;
  1022. var binaryBlob = false;
  1023. var sctp = false;
  1024. var onnegotiationneeded = !!window.webkitRTCPeerConnection;
  1025. var pc, dc;
  1026. try {
  1027. pc = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  1028. } catch (e) {
  1029. data = false;
  1030. audioVideo = false;
  1031. }
  1032. if (data) {
  1033. try {
  1034. dc = pc.createDataChannel('_PEERJSTEST');
  1035. } catch (e) {
  1036. data = false;
  1037. }
  1038. }
  1039. if (data) {
  1040. // Binary test
  1041. try {
  1042. dc.binaryType = 'blob';
  1043. binaryBlob = true;
  1044. } catch (e) {
  1045. }
  1046. // Reliable test.
  1047. // Unfortunately Chrome is a bit unreliable about whether or not they
  1048. // support reliable.
  1049. var reliablePC = new RTCPeerConnection(defaultConfig, {});
  1050. try {
  1051. var reliableDC = reliablePC.createDataChannel('_PEERJSRELIABLETEST', {});
  1052. sctp = reliableDC.reliable;
  1053. } catch (e) {
  1054. }
  1055. reliablePC.close();
  1056. }
  1057. // FIXME: not really the best check...
  1058. if (audioVideo) {
  1059. audioVideo = !!pc.addStream;
  1060. }
  1061. // FIXME: this is not great because in theory it doesn't work for
  1062. // av-only browsers (?).
  1063. if (!onnegotiationneeded && data) {
  1064. // sync default check.
  1065. var negotiationPC = new RTCPeerConnection(defaultConfig, {optional: [{RtpDataChannels: true}]});
  1066. negotiationPC.onnegotiationneeded = function() {
  1067. onnegotiationneeded = true;
  1068. // async check.
  1069. if (util && util.supports) {
  1070. util.supports.onnegotiationneeded = true;
  1071. }
  1072. };
  1073. var negotiationDC = negotiationPC.createDataChannel('_PEERJSNEGOTIATIONTEST');
  1074. setTimeout(function() {
  1075. negotiationPC.close();
  1076. }, 1000);
  1077. }
  1078. if (pc) {
  1079. pc.close();
  1080. }
  1081. return {
  1082. audioVideo: audioVideo,
  1083. data: data,
  1084. binaryBlob: binaryBlob,
  1085. binary: sctp, // deprecated; sctp implies binary support.
  1086. reliable: sctp, // deprecated; sctp implies reliable data.
  1087. sctp: sctp,
  1088. onnegotiationneeded: onnegotiationneeded
  1089. };
  1090. }()),
  1091. //
  1092. // Ensure alphanumeric ids
  1093. validateId: function(id) {
  1094. // Allow empty ids
  1095. return !id || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id);
  1096. },
  1097. validateKey: function(key) {
  1098. // Allow empty keys
  1099. return !key || /^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(key);
  1100. },
  1101. debug: false,
  1102. inherits: function(ctor, superCtor) {
  1103. ctor.super_ = superCtor;
  1104. ctor.prototype = Object.create(superCtor.prototype, {
  1105. constructor: {
  1106. value: ctor,
  1107. enumerable: false,
  1108. writable: true,
  1109. configurable: true
  1110. }
  1111. });
  1112. },
  1113. extend: function(dest, source) {
  1114. for(var key in source) {
  1115. if(source.hasOwnProperty(key)) {
  1116. dest[key] = source[key];
  1117. }
  1118. }
  1119. return dest;
  1120. },
  1121. pack: BinaryPack.pack,
  1122. unpack: BinaryPack.unpack,
  1123. log: function () {
  1124. if (util.debug) {
  1125. var err = false;
  1126. var copy = Array.prototype.slice.call(arguments);
  1127. copy.unshift('PeerJS: ');
  1128. for (var i = 0, l = copy.length; i < l; i++){
  1129. if (copy[i] instanceof Error) {
  1130. copy[i] = '(' + copy[i].name + ') ' + copy[i].message;
  1131. err = true;
  1132. }
  1133. }
  1134. err ? console.error.apply(console, copy) : console.log.apply(console, copy);
  1135. }
  1136. },
  1137. setZeroTimeout: (function(global) {
  1138. var timeouts = [];
  1139. var messageName = 'zero-timeout-message';
  1140. // Like setTimeout, but only takes a function argument. There's
  1141. // no time argument (always zero) and no arguments (you have to
  1142. // use a closure).
  1143. function setZeroTimeoutPostMessage(fn) {
  1144. timeouts.push(fn);
  1145. global.postMessage(messageName, '*');
  1146. }
  1147. function handleMessage(event) {
  1148. if (event.source == global && event.data == messageName) {
  1149. if (event.stopPropagation) {
  1150. event.stopPropagation();
  1151. }
  1152. if (timeouts.length) {
  1153. timeouts.shift()();
  1154. }
  1155. }
  1156. }
  1157. if (global.addEventListener) {
  1158. global.addEventListener('message', handleMessage, true);
  1159. } else if (global.attachEvent) {
  1160. global.attachEvent('onmessage', handleMessage);
  1161. }
  1162. return setZeroTimeoutPostMessage;
  1163. }(this)),
  1164. // Binary stuff
  1165. // chunks a blob.
  1166. chunk: function(bl) {
  1167. var chunks = [];
  1168. var size = bl.size;
  1169. var start = index = 0;
  1170. var total = Math.ceil(size / util.chunkedMTU);
  1171. while (start < size) {
  1172. var end = Math.min(size, start + util.chunkedMTU);
  1173. var b = bl.slice(start, end);
  1174. var chunk = {
  1175. __peerData: dataCount,
  1176. n: index,
  1177. data: b,
  1178. total: total
  1179. };
  1180. chunks.push(chunk);
  1181. start = end;
  1182. index += 1;
  1183. }
  1184. dataCount += 1;
  1185. return chunks;
  1186. },
  1187. blobToArrayBuffer: function(blob, cb){
  1188. var fr = new FileReader();
  1189. fr.onload = function(evt) {
  1190. cb(evt.target.result);
  1191. };
  1192. fr.readAsArrayBuffer(blob);
  1193. },
  1194. blobToBinaryString: function(blob, cb){
  1195. var fr = new FileReader();
  1196. fr.onload = function(evt) {
  1197. cb(evt.target.result);
  1198. };
  1199. fr.readAsBinaryString(blob);
  1200. },
  1201. binaryStringToArrayBuffer: function(binary) {
  1202. var byteArray = new Uint8Array(binary.length);
  1203. for (var i = 0; i < binary.length; i++) {
  1204. byteArray[i] = binary.charCodeAt(i) & 0xff;
  1205. }
  1206. return byteArray.buffer;
  1207. },
  1208. randomToken: function () {
  1209. return Math.random().toString(36).substr(2);
  1210. },
  1211. //
  1212. isSecure: function() {
  1213. return location.protocol === 'https:';
  1214. }
  1215. };
  1216. exports.util = util;
  1217. /**
  1218. * A peer who can initiate connections with other peers.
  1219. */
  1220. function Peer(id, options) {
  1221. if (!(this instanceof Peer)) return new Peer(id, options);
  1222. EventEmitter.call(this);
  1223. // Deal with overloading
  1224. if (id && id.constructor == Object) {
  1225. options = id;
  1226. id = undefined;
  1227. } else if (id) {
  1228. // Ensure id is a string
  1229. id = id.toString();
  1230. }
  1231. //
  1232. // Configurize options
  1233. options = util.extend({
  1234. debug: 0, // 1: Errors, 2: Warnings, 3: All logs
  1235. host: util.CLOUD_HOST,
  1236. port: util.CLOUD_PORT,
  1237. key: 'peerjs',
  1238. path: '/',
  1239. token: util.randomToken(),
  1240. config: util.defaultConfig
  1241. }, options);
  1242. this.options = options;
  1243. // Detect relative URL host.
  1244. if (options.host === '/') {
  1245. options.host = window.location.hostname;
  1246. }
  1247. // Set path correctly.
  1248. if (options.path[0] !== '/') {
  1249. options.path = '/' + options.path;
  1250. }
  1251. if (options.path[options.path.length - 1] !== '/') {
  1252. options.path += '/';
  1253. }
  1254. // Set whether we use SSL to same as current host
  1255. if (options.secure === undefined && options.host !== util.CLOUD_HOST) {
  1256. options.secure = util.isSecure();
  1257. }
  1258. // Set a custom log function if present
  1259. if (options.logFunction) {
  1260. util.setLogFunction(options.logFunction);
  1261. }
  1262. util.setLogLevel(options.debug);
  1263. //
  1264. // Sanity checks
  1265. // Ensure WebRTC supported
  1266. if (!util.supports.audioVideo && !util.supports.data ) {
  1267. this._delayedAbort('browser-incompatible', 'The current browser does not support WebRTC');
  1268. return;
  1269. }
  1270. // Ensure alphanumeric id
  1271. if (!util.validateId(id)) {
  1272. this._delayedAbort('invalid-id', 'ID "' + id + '" is invalid');
  1273. return;
  1274. }
  1275. // Ensure valid key
  1276. if (!util.validateKey(options.key)) {
  1277. this._delayedAbort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  1278. return;
  1279. }
  1280. // Ensure not using unsecure cloud server on SSL page
  1281. if (options.secure && options.host === '0.peerjs.com') {
  1282. this._delayedAbort('ssl-unavailable',
  1283. 'The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS.');
  1284. return;
  1285. }
  1286. //
  1287. // States.
  1288. this.destroyed = false; // Connections have been killed
  1289. this.disconnected = false; // Connection to PeerServer killed but P2P connections still active
  1290. this.open = false; // Sockets and such are not yet open.
  1291. //
  1292. // References
  1293. this.connections = {}; // DataConnections for this peer.
  1294. this._lostMessages = {}; // src => [list of messages]
  1295. //
  1296. // Start the server connection
  1297. this._initializeServerConnection();
  1298. if (id) {
  1299. this._initialize(id);
  1300. } else {
  1301. this._retrieveId();
  1302. }
  1303. //
  1304. };
  1305. util.inherits(Peer, EventEmitter);
  1306. // Initialize the 'socket' (which is actually a mix of XHR streaming and
  1307. // websockets.)
  1308. Peer.prototype._initializeServerConnection = function() {
  1309. var self = this;
  1310. this.socket = new Socket(this.options.secure, this.options.host, this.options.port, this.options.path, this.options.key);
  1311. this.socket.on('message', function(data) {
  1312. self._handleMessage(data);
  1313. });
  1314. this.socket.on('error', function(error) {
  1315. self._abort('socket-error', error);
  1316. });
  1317. this.socket.on('disconnected', function() {
  1318. // If we haven't explicitly disconnected, emit error and disconnect.
  1319. if (!self.disconnected) {
  1320. self.emitError('network', 'Lost connection to server.')
  1321. self.disconnect();
  1322. }
  1323. });
  1324. this.socket.on('close', function() {
  1325. // If we haven't explicitly disconnected, emit error.
  1326. if (!self.disconnected) {
  1327. self._abort('socket-closed', 'Underlying socket is already closed.');
  1328. }
  1329. });
  1330. };
  1331. /** Get a unique ID from the server via XHR. */
  1332. Peer.prototype._retrieveId = function(cb) {
  1333. var self = this;
  1334. var http = new XMLHttpRequest();
  1335. var protocol = this.options.secure ? 'https://' : 'http://';
  1336. var url = protocol + this.options.host + ':' + this.options.port
  1337. + this.options.path + this.options.key + '/id';
  1338. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  1339. url += queryString;
  1340. // If there's no ID we need to wait for one before trying to init socket.
  1341. http.open('get', url, true);
  1342. http.onerror = function(e) {
  1343. util.error('Error retrieving ID', e);
  1344. var pathError = '';
  1345. if (self.options.path === '/' && self.options.host !== util.CLOUD_HOST) {
  1346. pathError = ' If you passed in a `path` to your self-hosted PeerServer, '
  1347. + 'you\'ll also need to pass in that same path when creating a new'
  1348. + ' Peer.';
  1349. }
  1350. self._abort('server-error', 'Could not get an ID from the server.' + pathError);
  1351. }
  1352. http.onreadystatechange = function() {
  1353. if (http.readyState !== 4) {
  1354. return;
  1355. }
  1356. if (http.status !== 200) {
  1357. http.onerror();
  1358. return;
  1359. }
  1360. self._initialize(http.responseText);
  1361. };
  1362. http.send(null);
  1363. };
  1364. /** Initialize a connection with the server. */
  1365. Peer.prototype._initialize = function(id) {
  1366. this.id = id;
  1367. this.socket.start(this.id, this.options.token);
  1368. }
  1369. /** Handles messages from the server. */
  1370. Peer.prototype._handleMessage = function(message) {
  1371. var type = message.type;
  1372. var payload = message.payload;
  1373. var peer = message.src;
  1374. switch (type) {
  1375. case 'OPEN': // The connection to the server is open.
  1376. this.emit('open', this.id);
  1377. this.open = true;
  1378. break;
  1379. case 'ERROR': // Server error.
  1380. this._abort('server-error', payload.msg);
  1381. break;
  1382. case 'ID-TAKEN': // The selected ID is taken.
  1383. this._abort('unavailable-id', 'ID `' + this.id + '` is taken');
  1384. break;
  1385. case 'INVALID-KEY': // The given API key cannot be found.
  1386. this._abort('invalid-key', 'API KEY "' + this.options.key + '" is invalid');
  1387. break;
  1388. //
  1389. case 'LEAVE': // Another peer has closed its connection to this peer.
  1390. util.log('Received leave message from', peer);
  1391. this._cleanupPeer(peer);
  1392. break;
  1393. case 'EXPIRE': // The offer sent to a peer has expired without response.
  1394. this.emitError('peer-unavailable', 'Could not connect to peer ' + peer);
  1395. break;
  1396. case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  1397. var connectionId = payload.connectionId;
  1398. var connection = this.getConnection(peer, connectionId);
  1399. if (connection) {
  1400. util.warn('Offer received for existing Connection ID:', connectionId);
  1401. //connection.handleMessage(message);
  1402. } else {
  1403. // Create a new connection.
  1404. if (payload.type === 'media') {
  1405. var connection = new MediaConnection(peer, this, {
  1406. connectionId: connectionId,
  1407. _payload: payload,
  1408. metadata: payload.metadata
  1409. });
  1410. this._addConnection(peer, connection);
  1411. this.emit('call', connection);
  1412. } else if (payload.type === 'data') {
  1413. connection = new DataConnection(peer, this, {
  1414. connectionId: connectionId,
  1415. _payload: payload,
  1416. metadata: payload.metadata,
  1417. label: payload.label,
  1418. serialization: payload.serialization,
  1419. reliable: payload.reliable
  1420. });
  1421. this._addConnection(peer, connection);
  1422. this.emit('connection', connection);
  1423. } else {
  1424. util.warn('Received malformed connection type:', payload.type);
  1425. return;
  1426. }
  1427. // Find messages.
  1428. var messages = this._getMessages(connectionId);
  1429. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  1430. connection.handleMessage(messages[i]);
  1431. }
  1432. }
  1433. break;
  1434. default:
  1435. if (!payload) {
  1436. util.warn('You received a malformed message from ' + peer + ' of type ' + type);
  1437. return;
  1438. }
  1439. var id = payload.connectionId;
  1440. var connection = this.getConnection(peer, id);
  1441. if (connection && connection.pc) {
  1442. // Pass it on.
  1443. connection.handleMessage(message);
  1444. } else if (id) {
  1445. // Store for possible later use
  1446. this._storeMessage(id, message);
  1447. } else {
  1448. util.warn('You received an unrecognized message:', message);
  1449. }
  1450. break;
  1451. }
  1452. }
  1453. /** Stores messages without a set up connection, to be claimed later. */
  1454. Peer.prototype._storeMessage = function(connectionId, message) {
  1455. if (!this._lostMessages[connectionId]) {
  1456. this._lostMessages[connectionId] = [];
  1457. }
  1458. this._lostMessages[connectionId].push(message);
  1459. }
  1460. /** Retrieve messages from lost message store */
  1461. Peer.prototype._getMessages = function(connectionId) {
  1462. var messages = this._lostMessages[connectionId];
  1463. if (messages) {
  1464. delete this._lostMessages[connectionId];
  1465. return messages;
  1466. } else {
  1467. return [];
  1468. }
  1469. }
  1470. /**
  1471. * Returns a DataConnection to the specified peer. See documentation for a
  1472. * complete list of options.
  1473. */
  1474. Peer.prototype.connect = function(peer, options) {
  1475. if (this.disconnected) {
  1476. util.warn('You cannot connect to a new Peer because you called '
  1477. + '.disconnect() on this Peer and ended your connection with the'
  1478. + ' server. You can create a new Peer to reconnect, or call reconnect'
  1479. + ' on this peer if you believe its ID to still be available.');
  1480. this.emitError('disconnected', 'Cannot connect to new Peer after disconnecting from server.');
  1481. return;
  1482. }
  1483. var connection = new DataConnection(peer, this, options);
  1484. this._addConnection(peer, connection);
  1485. return connection;
  1486. }
  1487. /**
  1488. * Returns a MediaConnection to the specified peer. See documentation for a
  1489. * complete list of options.
  1490. */
  1491. Peer.prototype.call = function(peer, stream, options) {
  1492. if (this.disconnected) {
  1493. util.warn('You cannot connect to a new Peer because you called '
  1494. + '.disconnect() on this Peer and ended your connection with the'
  1495. + ' server. You can create a new Peer to reconnect.');
  1496. this.emitError('disconnected', 'Cannot connect to new Peer after disconnecting from server.');
  1497. return;
  1498. }
  1499. if (!stream) {
  1500. util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.');
  1501. return;
  1502. }
  1503. options = options || {};
  1504. options._stream = stream;
  1505. var call = new MediaConnection(peer, this, options);
  1506. this._addConnection(peer, call);
  1507. return call;
  1508. }
  1509. /** Add a data/media connection to this peer. */
  1510. Peer.prototype._addConnection = function(peer, connection) {
  1511. if (!this.connections[peer]) {
  1512. this.connections[peer] = [];
  1513. }
  1514. this.connections[peer].push(connection);
  1515. }
  1516. /** Retrieve a data/media connection for this peer. */
  1517. Peer.prototype.getConnection = function(peer, id) {
  1518. var connections = this.connections[peer];
  1519. if (!connections) {
  1520. return null;
  1521. }
  1522. for (var i = 0, ii = connections.length; i < ii; i++) {
  1523. if (connections[i].id === id) {
  1524. return connections[i];
  1525. }
  1526. }
  1527. return null;
  1528. }
  1529. Peer.prototype._delayedAbort = function(type, message) {
  1530. var self = this;
  1531. util.setZeroTimeout(function(){
  1532. self._abort(type, message);
  1533. });
  1534. }
  1535. /**
  1536. * Destroys the Peer and emits an error message.
  1537. * The Peer is not destroyed if it's in a disconnected state, in which case
  1538. * it retains its disconnected state and its existing connections.
  1539. */
  1540. Peer.prototype._abort = function(type, message) {
  1541. util.error('Aborting!');
  1542. if (!this.disconnected) {
  1543. this.destroy();
  1544. }
  1545. this.emitError(type, message);
  1546. };
  1547. /** Emits a typed error message. */
  1548. Peer.prototype.emitError = function(type, err) {
  1549. util.error('Error:', err);
  1550. if (typeof err === 'string') {
  1551. err = new Error(err);
  1552. }
  1553. err.type = type;
  1554. this.emit('error', err);
  1555. };
  1556. /**
  1557. * Destroys the Peer: closes all active connections as well as the connection
  1558. * to the server.
  1559. * Warning: The peer can no longer create or accept connections after being
  1560. * destroyed.
  1561. */
  1562. Peer.prototype.destroy = function() {
  1563. if (!this.destroyed) {
  1564. this._cleanup();
  1565. this.disconnect();
  1566. this.destroyed = true;
  1567. }
  1568. }
  1569. /** Disconnects every connection on this peer. */
  1570. Peer.prototype._cleanup = function() {
  1571. if (this.connections) {
  1572. var peers = Object.keys(this.connections);
  1573. for (var i = 0, ii = peers.length; i < ii; i++) {
  1574. this._cleanupPeer(peers[i]);
  1575. }
  1576. }
  1577. this.emit('close');
  1578. }
  1579. /** Closes all connections to this peer. */
  1580. Peer.prototype._cleanupPeer = function(peer) {
  1581. var connections = this.connections[peer];
  1582. for (var j = 0, jj = connections.length; j < jj; j += 1) {
  1583. connections[j].close();
  1584. }
  1585. }
  1586. /**
  1587. * Disconnects the Peer's connection to the PeerServer. Does not close any
  1588. * active connections.
  1589. * Warning: The peer can no longer create or accept connections after being
  1590. * disconnected. It also cannot reconnect to the server.
  1591. */
  1592. Peer.prototype.disconnect = function() {
  1593. var self = this;
  1594. util.setZeroTimeout(function(){
  1595. if (!self.disconnected) {
  1596. self.disconnected = true;
  1597. self.open = false;
  1598. if (self.socket) {
  1599. self.socket.close();
  1600. }
  1601. self.emit('disconnected', self.id);
  1602. self._lastServerId = self.id;
  1603. self.id = null;
  1604. }
  1605. });
  1606. }
  1607. /** Attempts to reconnect with the same ID. */
  1608. Peer.prototype.reconnect = function() {
  1609. if (this.disconnected && !this.destroyed) {
  1610. util.log('Attempting reconnection to server with ID ' + this._lastServerId);
  1611. this._initializeServerConnection();
  1612. this._initialize(this._lastServerId);
  1613. } else if (this.destroyed) {
  1614. throw new Error('This peer cannot reconnect to the server. It has already been destroyed.');
  1615. } else if (!this.disconnected && !this.open) {
  1616. // Do nothing. We're still connecting the first time.
  1617. util.error('In a hurry? We\'re still trying to make the initial connection!');
  1618. } else {
  1619. throw new Error('Peer ' + this.id + ' cannot reconnect because it is not disconnected from the server!');
  1620. }
  1621. };
  1622. /**
  1623. * Get a list of available peer IDs. If you're running your own server, you'll
  1624. * want to set allow_discovery: true in the PeerServer options. If you're using
  1625. * the cloud server, email team@peerjs.com to get the functionality enabled for
  1626. * your key.
  1627. */
  1628. Peer.prototype.listAllPeers = function(cb) {
  1629. cb = cb || function() {};
  1630. var self = this;
  1631. var http = new XMLHttpRequest();
  1632. var protocol = this.options.secure ? 'https://' : 'http://';
  1633. var url = protocol + this.options.host + ':' + this.options.port
  1634. + this.options.path + this.options.key + '/peers';
  1635. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  1636. url += queryString;
  1637. // If there's no ID we need to wait for one before trying to init socket.
  1638. http.open('get', url, true);
  1639. http.onerror = function(e) {
  1640. self._abort('server-error', 'Could not get peers from the server.');
  1641. cb([]);
  1642. }
  1643. http.onreadystatechange = function() {
  1644. if (http.readyState !== 4) {
  1645. return;
  1646. }
  1647. if (http.status === 401) {
  1648. var helpfulError = '';
  1649. if (self.options.host !== util.CLOUD_HOST) {
  1650. helpfulError = 'It looks like you\'re using the cloud server. You can email '
  1651. + 'team@peerjs.com to enable peer listing for your API key.';
  1652. } else {
  1653. helpfulError = 'You need to enable `allow_discovery` on your self-hosted'
  1654. + ' PeerServer to use this feature.';
  1655. }
  1656. throw new Error('It doesn\'t look like you have permission to list peers IDs. ' + helpfulError);
  1657. cb([]);
  1658. } else if (http.status !== 200) {
  1659. cb([]);
  1660. } else {
  1661. cb(JSON.parse(http.responseText));
  1662. }
  1663. };
  1664. http.send(null);
  1665. }
  1666. exports.Peer = Peer;
  1667. /**
  1668. * Wraps a DataChannel between two Peers.
  1669. */
  1670. function DataConnection(peer, provider, options) {
  1671. if (!(this instanceof DataConnection)) return new DataConnection(peer, provider, options);
  1672. EventEmitter.call(this);
  1673. this.options = util.extend({
  1674. serialization: 'binary',
  1675. reliable: false
  1676. }, options);
  1677. // Connection is not open yet.
  1678. this.open = false;
  1679. this.type = 'data';
  1680. this.peer = peer;
  1681. this.provider = provider;
  1682. this.id = this.options.connectionId || DataConnection._idPrefix + util.randomToken();
  1683. this.label = this.options.label || this.id;
  1684. this.metadata = this.options.metadata;
  1685. this.serialization = this.options.serialization;
  1686. this.reliable = this.options.reliable;
  1687. // Data channel buffering.
  1688. this._buffer = [];
  1689. this._buffering = false;
  1690. this.bufferSize = 0;
  1691. // For storing large data.
  1692. this._chunkedData = {};
  1693. if (this.options._payload) {
  1694. this._peerBrowser = this.options._payload.browser;
  1695. }
  1696. Negotiator.startConnection(
  1697. this,
  1698. this.options._payload || {
  1699. originator: true
  1700. }
  1701. );
  1702. }
  1703. util.inherits(DataConnection, EventEmitter);
  1704. DataConnection._idPrefix = 'dc_';
  1705. /** Called by the Negotiator when the DataChannel is ready. */
  1706. DataConnection.prototype.initialize = function(dc) {
  1707. this._dc = this.dataChannel = dc;
  1708. this._configureDataChannel();
  1709. }
  1710. DataConnection.prototype._configureDataChannel = function() {
  1711. var self = this;
  1712. if (util.supports.sctp) {
  1713. this._dc.binaryType = 'arraybuffer';
  1714. }
  1715. this._dc.onopen = function() {
  1716. util.log('Data channel connection success');
  1717. self.open = true;
  1718. self.emit('open');
  1719. }
  1720. // Use the Reliable shim for non Firefox browsers
  1721. if (!util.supports.sctp && this.reliable) {
  1722. this._reliable = new Reliable(this._dc, util.debug);
  1723. }
  1724. if (this._reliable) {
  1725. this._reliable.onmessage = function(msg) {
  1726. self.emit('data', msg);
  1727. };
  1728. } else {
  1729. this._dc.onmessage = function(e) {
  1730. self._handleDataMessage(e);
  1731. };
  1732. }
  1733. this._dc.onclose = function(e) {
  1734. util.log('DataChannel closed for:', self.peer);
  1735. self.close();
  1736. };
  1737. }
  1738. // Handles a DataChannel message.
  1739. DataConnection.prototype._handleDataMessage = function(e) {
  1740. var self = this;
  1741. var data = e.data;
  1742. var datatype = data.constructor;
  1743. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  1744. if (datatype === Blob) {
  1745. // Datatype should never be blob
  1746. util.blobToArrayBuffer(data, function(ab) {
  1747. data = util.unpack(ab);
  1748. self.emit('data', data);
  1749. });
  1750. return;
  1751. } else if (datatype === ArrayBuffer) {
  1752. data = util.unpack(data);
  1753. } else if (datatype === String) {
  1754. // String fallback for binary data for browsers that don't support binary yet
  1755. var ab = util.binaryStringToArrayBuffer(data);
  1756. data = util.unpack(ab);
  1757. }
  1758. } else if (this.serialization === 'json') {
  1759. data = JSON.parse(data);
  1760. }
  1761. // Check if we've chunked--if so, piece things back together.
  1762. // We're guaranteed that this isn't 0.
  1763. if (data.__peerData) {
  1764. var id = data.__peerData;
  1765. var chunkInfo = this._chunkedData[id] || {data: [], count: 0, total: data.total};
  1766. chunkInfo.data[data.n] = data.data;
  1767. chunkInfo.count += 1;
  1768. if (chunkInfo.total === chunkInfo.count) {
  1769. // Clean up before making the recursive call to `_handleDataMessage`.
  1770. delete this._chunkedData[id];
  1771. // We've received all the chunks--time to construct the complete data.
  1772. data = new Blob(chunkInfo.data);
  1773. this._handleDataMessage({data: data});
  1774. }
  1775. this._chunkedData[id] = chunkInfo;
  1776. return;
  1777. }
  1778. this.emit('data', data);
  1779. }
  1780. /**
  1781. * Exposed functionality for users.
  1782. */
  1783. /** Allows user to close connection. */
  1784. DataConnection.prototype.close = function() {
  1785. if (!this.open) {
  1786. return;
  1787. }
  1788. this.open = false;
  1789. Negotiator.cleanup(this);
  1790. this.emit('close');
  1791. }
  1792. /** Allows user to send data. */
  1793. DataConnection.prototype.send = function(data, chunked) {
  1794. if (!this.open) {
  1795. this.emit('error', new Error('Connection is not open. You should listen for the `open` event before sending messages.'));
  1796. return;
  1797. }
  1798. if (this._reliable) {
  1799. // Note: reliable shim sending will make it so that you cannot customize
  1800. // serialization.
  1801. this._reliable.send(data);
  1802. return;
  1803. }
  1804. var self = this;
  1805. if (this.serialization === 'json') {
  1806. this._bufferedSend(JSON.stringify(data));
  1807. } else if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  1808. var blob = util.pack(data);
  1809. // For Chrome-Firefox interoperability, we need to make Firefox "chunk"
  1810. // the data it sends out.
  1811. var needsChunking = util.chunkedBrowsers[this._peerBrowser] || util.chunkedBrowsers[util.browser];
  1812. if (needsChunking && !chunked && blob.size > util.chunkedMTU) {
  1813. this._sendChunks(blob);
  1814. return;
  1815. }
  1816. // DataChannel currently only supports strings.
  1817. if (!util.supports.sctp) {
  1818. util.blobToBinaryString(blob, function(str) {
  1819. self._bufferedSend(str);
  1820. });
  1821. } else if (!util.supports.binaryBlob) {
  1822. // We only do this if we really need to (e.g. blobs are not supported),
  1823. // because this conversion is costly.
  1824. util.blobToArrayBuffer(blob, function(ab) {
  1825. self._bufferedSend(ab);
  1826. });
  1827. } else {
  1828. this._bufferedSend(blob);
  1829. }
  1830. } else {
  1831. this._bufferedSend(data);
  1832. }
  1833. }
  1834. DataConnection.prototype._bufferedSend = function(msg) {
  1835. if (this._buffering || !this._trySend(msg)) {
  1836. this._buffer.push(msg);
  1837. this.bufferSize = this._buffer.length;
  1838. }
  1839. }
  1840. // Returns true if the send succeeds.
  1841. DataConnection.prototype._trySend = function(msg) {
  1842. try {
  1843. this._dc.send(msg);
  1844. } catch (e) {
  1845. this._buffering = true;
  1846. var self = this;
  1847. setTimeout(function() {
  1848. // Try again.
  1849. self._buffering = false;
  1850. self._tryBuffer();
  1851. }, 100);
  1852. return false;
  1853. }
  1854. return true;
  1855. }
  1856. // Try to send the first message in the buffer.
  1857. DataConnection.prototype._tryBuffer = function() {
  1858. if (this._buffer.length === 0) {
  1859. return;
  1860. }
  1861. var msg = this._buffer[0];
  1862. if (this._trySend(msg)) {
  1863. this._buffer.shift();
  1864. this.bufferSize = this._buffer.length;
  1865. this._tryBuffer();
  1866. }
  1867. }
  1868. DataConnection.prototype._sendChunks = function(blob) {
  1869. var blobs = util.chunk(blob);
  1870. for (var i = 0, ii = blobs.length; i < ii; i += 1) {
  1871. var blob = blobs[i];
  1872. this.send(blob, true);
  1873. }
  1874. }
  1875. DataConnection.prototype.handleMessage = function(message) {
  1876. var payload = message.payload;
  1877. switch (message.type) {
  1878. case 'ANSWER':
  1879. this._peerBrowser = payload.browser;
  1880. // Forward to negotiator
  1881. Negotiator.handleSDP(message.type, this, payload.sdp);
  1882. break;
  1883. case 'CANDIDATE':
  1884. Negotiator.handleCandidate(this, payload.candidate);
  1885. break;
  1886. default:
  1887. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  1888. break;
  1889. }
  1890. }
  1891. /**
  1892. * Wraps the streaming interface between two Peers.
  1893. */
  1894. function MediaConnection(peer, provider, options) {
  1895. if (!(this instanceof MediaConnection)) return new MediaConnection(peer, provider, options);
  1896. EventEmitter.call(this);
  1897. this.options = util.extend({}, options);
  1898. this.open = false;
  1899. this.type = 'media';
  1900. this.peer = peer;
  1901. this.provider = provider;
  1902. this.metadata = this.options.metadata;
  1903. this.localStream = this.options._stream;
  1904. this.id = this.options.connectionId || MediaConnection._idPrefix + util.randomToken();
  1905. if (this.localStream) {
  1906. Negotiator.startConnection(
  1907. this,
  1908. {_stream: this.localStream, originator: true}
  1909. );
  1910. }
  1911. };
  1912. util.inherits(MediaConnection, EventEmitter);
  1913. MediaConnection._idPrefix = 'mc_';
  1914. MediaConnection.prototype.addStream = function(remoteStream) {
  1915. util.log('Receiving stream', remoteStream);
  1916. this.remoteStream = remoteStream;
  1917. this.emit('stream', remoteStream); // Should we call this `open`?
  1918. };
  1919. MediaConnection.prototype.handleMessage = function(message) {
  1920. var payload = message.payload;
  1921. switch (message.type) {
  1922. case 'ANSWER':
  1923. // Forward to negotiator
  1924. Negotiator.handleSDP(message.type, this, payload.sdp);
  1925. this.open = true;
  1926. break;
  1927. case 'CANDIDATE':
  1928. Negotiator.handleCandidate(this, payload.candidate);
  1929. break;
  1930. default:
  1931. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  1932. break;
  1933. }
  1934. }
  1935. MediaConnection.prototype.answer = function(stream) {
  1936. if (this.localStream) {
  1937. util.warn('Local stream already exists on this MediaConnection. Are you answering a call twice?');
  1938. return;
  1939. }
  1940. this.options._payload._stream = stream;
  1941. this.localStream = stream;
  1942. Negotiator.startConnection(
  1943. this,
  1944. this.options._payload
  1945. )
  1946. // Retrieve lost messages stored because PeerConnection not set up.
  1947. var messages = this.provider._getMessages(this.id);
  1948. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  1949. this.handleMessage(messages[i]);
  1950. }
  1951. this.open = true;
  1952. };
  1953. /**
  1954. * Exposed functionality for users.
  1955. */
  1956. /** Allows user to close connection. */
  1957. MediaConnection.prototype.close = function() {
  1958. if (!this.open) {
  1959. return;
  1960. }
  1961. this.open = false;
  1962. Negotiator.cleanup(this);
  1963. this.emit('close')
  1964. };
  1965. /**
  1966. * Manages all negotiations between Peers.
  1967. */
  1968. var Negotiator = {
  1969. pcs: {
  1970. data: {},
  1971. media: {}
  1972. }, // type => {peerId: {pc_id: pc}}.
  1973. //providers: {}, // provider's id => providers (there may be multiple providers/client.
  1974. queue: [] // connections that are delayed due to a PC being in use.
  1975. }
  1976. Negotiator._idPrefix = 'pc_';
  1977. /** Returns a PeerConnection object set up correctly (for data, media). */
  1978. Negotiator.startConnection = function(connection, options) {
  1979. var pc = Negotiator._getPeerConnection(connection, options);
  1980. if (connection.type === 'media' && options._stream) {
  1981. // Add the stream.
  1982. pc.addStream(options._stream);
  1983. }
  1984. // Set the connection's PC.
  1985. connection.pc = connection.peerConnection = pc;
  1986. // What do we need to do now?
  1987. if (options.originator) {
  1988. if (connection.type === 'data') {
  1989. // Create the datachannel.
  1990. var config = {};
  1991. // Dropping reliable:false support, since it seems to be crashing
  1992. // Chrome.
  1993. /*if (util.supports.sctp && !options.reliable) {
  1994. // If we have canonical reliable support...
  1995. config = {maxRetransmits: 0};
  1996. }*/
  1997. // Fallback to ensure older browsers don't crash.
  1998. if (!util.supports.sctp) {
  1999. config = {reliable: options.reliable};
  2000. }
  2001. var dc = pc.createDataChannel(connection.label, config);
  2002. connection.initialize(dc);
  2003. }
  2004. if (!util.supports.onnegotiationneeded) {
  2005. Negotiator._makeOffer(connection);
  2006. }
  2007. } else {
  2008. Negotiator.handleSDP('OFFER', connection, options.sdp);
  2009. }
  2010. }
  2011. Negotiator._getPeerConnection = function(connection, options) {
  2012. if (!Negotiator.pcs[connection.type]) {
  2013. util.error(connection.type + ' is not a valid connection type. Maybe you overrode the `type` property somewhere.');
  2014. }
  2015. if (!Negotiator.pcs[connection.type][connection.peer]) {
  2016. Negotiator.pcs[connection.type][connection.peer] = {};
  2017. }
  2018. var peerConnections = Negotiator.pcs[connection.type][connection.peer];
  2019. var pc;
  2020. // Not multiplexing while FF and Chrome have not-great support for it.
  2021. /*if (options.multiplex) {
  2022. ids = Object.keys(peerConnections);
  2023. for (var i = 0, ii = ids.length; i < ii; i += 1) {
  2024. pc = peerConnections[ids[i]];
  2025. if (pc.signalingState === 'stable') {
  2026. break; // We can go ahead and use this PC.
  2027. }
  2028. }
  2029. } else */
  2030. if (options.pc) { // Simplest case: PC id already provided for us.
  2031. pc = Negotiator.pcs[connection.type][connection.peer][options.pc];
  2032. }
  2033. if (!pc || pc.signalingState !== 'stable') {
  2034. pc = Negotiator._startPeerConnection(connection);
  2035. }
  2036. return pc;
  2037. }
  2038. /*
  2039. Negotiator._addProvider = function(provider) {
  2040. if ((!provider.id && !provider.disconnected) || !provider.socket.open) {
  2041. // Wait for provider to obtain an ID.
  2042. provider.on('open', function(id) {
  2043. Negotiator._addProvider(provider);
  2044. });
  2045. } else {
  2046. Negotiator.providers[provider.id] = provider;
  2047. }
  2048. }*/
  2049. /** Start a PC. */
  2050. Negotiator._startPeerConnection = function(connection) {
  2051. util.log('Creating RTCPeerConnection.');
  2052. var id = Negotiator._idPrefix + util.randomToken();
  2053. var optional = {};
  2054. if (connection.type === 'data' && !util.supports.sctp) {
  2055. optional = {optional: [{RtpDataChannels: true}]};
  2056. } else if (connection.type === 'media') {
  2057. // Interop req for chrome.
  2058. optional = {optional: [{DtlsSrtpKeyAgreement: true}]};
  2059. }
  2060. var pc = new RTCPeerConnection(connection.provider.options.config, optional);
  2061. Negotiator.pcs[connection.type][connection.peer][id] = pc;
  2062. Negotiator._setupListeners(connection, pc, id);
  2063. return pc;
  2064. }
  2065. /** Set up various WebRTC listeners. */
  2066. Negotiator._setupListeners = function(connection, pc, pc_id) {
  2067. var peerId = connection.peer;
  2068. var connectionId = connection.id;
  2069. var provider = connection.provider;
  2070. // ICE CANDIDATES.
  2071. util.log('Listening for ICE candidates.');
  2072. pc.onicecandidate = function(evt) {
  2073. if (evt.candidate) {
  2074. util.log('Received ICE candidates for:', connection.peer);
  2075. provider.socket.send({
  2076. type: 'CANDIDATE',
  2077. payload: {
  2078. candidate: evt.candidate,
  2079. type: connection.type,
  2080. connectionId: connection.id
  2081. },
  2082. dst: peerId
  2083. });
  2084. }
  2085. };
  2086. pc.oniceconnectionstatechange = function() {
  2087. switch (pc.iceConnectionState) {
  2088. case 'disconnected':
  2089. case 'failed':
  2090. util.log('iceConnectionState is disconnected, closing connections to ' + peerId);
  2091. connection.close();
  2092. break;
  2093. case 'completed':
  2094. pc.onicecandidate = util.noop;
  2095. break;
  2096. }
  2097. };
  2098. // Fallback for older Chrome impls.
  2099. pc.onicechange = pc.oniceconnectionstatechange;
  2100. // ONNEGOTIATIONNEEDED (Chrome)
  2101. util.log('Listening for `negotiationneeded`');
  2102. pc.onnegotiationneeded = function() {
  2103. util.log('`negotiationneeded` triggered');
  2104. if (pc.signalingState == 'stable') {
  2105. Negotiator._makeOffer(connection);
  2106. } else {
  2107. util.log('onnegotiationneeded triggered when not stable. Is another connection being established?');
  2108. }
  2109. };
  2110. // DATACONNECTION.
  2111. util.log('Listening for data channel');
  2112. // Fired between offer and answer, so options should already be saved
  2113. // in the options hash.
  2114. pc.ondatachannel = function(evt) {
  2115. util.log('Received data channel');
  2116. var dc = evt.channel;
  2117. var connection = provider.getConnection(peerId, connectionId);
  2118. connection.initialize(dc);
  2119. };
  2120. // MEDIACONNECTION.
  2121. util.log('Listening for remote stream');
  2122. pc.onaddstream = function(evt) {
  2123. util.log('Received remote stream');
  2124. var stream = evt.stream;
  2125. provider.getConnection(peerId, connectionId).addStream(stream);
  2126. };
  2127. }
  2128. Negotiator.cleanup = function(connection) {
  2129. util.log('Cleaning up PeerConnection to ' + connection.peer);
  2130. var pc = connection.pc;
  2131. if (!!pc && (pc.readyState !== 'closed' || pc.signalingState !== 'closed')) {
  2132. pc.close();
  2133. connection.pc = null;
  2134. }
  2135. }
  2136. Negotiator._makeOffer = function(connection) {
  2137. var pc = connection.pc;
  2138. pc.createOffer(function(offer) {
  2139. util.log('Created offer.');
  2140. if (!util.supports.sctp && connection.type === 'data' && connection.reliable) {
  2141. offer.sdp = Reliable.higherBandwidthSDP(offer.sdp);
  2142. }
  2143. pc.setLocalDescription(offer, function() {
  2144. util.log('Set localDescription: offer', 'for:', connection.peer);
  2145. connection.provider.socket.send({
  2146. type: 'OFFER',
  2147. payload: {
  2148. sdp: offer,
  2149. type: connection.type,
  2150. label: connection.label,
  2151. connectionId: connection.id,
  2152. reliable: connection.reliable,
  2153. serialization: connection.serialization,
  2154. metadata: connection.metadata,
  2155. browser: util.browser
  2156. },
  2157. dst: connection.peer
  2158. });
  2159. }, function(err) {
  2160. connection.provider.emitError('webrtc', err);
  2161. util.log('Failed to setLocalDescription, ', err);
  2162. });
  2163. }, function(err) {
  2164. connection.provider.emitError('webrtc', err);
  2165. util.log('Failed to createOffer, ', err);
  2166. }, connection.options.constraints);
  2167. }
  2168. Negotiator._makeAnswer = function(connection) {
  2169. var pc = connection.pc;
  2170. pc.createAnswer(function(answer) {
  2171. util.log('Created answer.');
  2172. if (!util.supports.sctp && connection.type === 'data' && connection.reliable) {
  2173. answer.sdp = Reliable.higherBandwidthSDP(answer.sdp);
  2174. }
  2175. pc.setLocalDescription(answer, function() {
  2176. util.log('Set localDescription: answer', 'for:', connection.peer);
  2177. connection.provider.socket.send({
  2178. type: 'ANSWER',
  2179. payload: {
  2180. sdp: answer,
  2181. type: connection.type,
  2182. connectionId: connection.id,
  2183. browser: util.browser
  2184. },
  2185. dst: connection.peer
  2186. });
  2187. }, function(err) {
  2188. connection.provider.emitError('webrtc', err);
  2189. util.log('Failed to setLocalDescription, ', err);
  2190. });
  2191. }, function(err) {
  2192. connection.provider.emitError('webrtc', err);
  2193. util.log('Failed to create answer, ', err);
  2194. });
  2195. }
  2196. /** Handle an SDP. */
  2197. Negotiator.handleSDP = function(type, connection, sdp) {
  2198. sdp = new RTCSessionDescription(sdp);
  2199. var pc = connection.pc;
  2200. util.log('Setting remote description', sdp);
  2201. pc.setRemoteDescription(sdp, function() {
  2202. util.log('Set remoteDescription:', type, 'for:', connection.peer);
  2203. if (type === 'OFFER') {
  2204. Negotiator._makeAnswer(connection);
  2205. }
  2206. }, function(err) {
  2207. connection.provider.emitError('webrtc', err);
  2208. util.log('Failed to setRemoteDescription, ', err);
  2209. });
  2210. }
  2211. /** Handle a candidate. */
  2212. Negotiator.handleCandidate = function(connection, ice) {
  2213. var candidate = ice.candidate;
  2214. var sdpMLineIndex = ice.sdpMLineIndex;
  2215. connection.pc.addIceCandidate(new RTCIceCandidate({
  2216. sdpMLineIndex: sdpMLineIndex,
  2217. candidate: candidate
  2218. }));
  2219. util.log('Added ICE candidate for:', connection.peer);
  2220. }
  2221. /**
  2222. * An abstraction on top of WebSockets and XHR streaming to provide fastest
  2223. * possible connection for peers.
  2224. */
  2225. function Socket(secure, host, port, path, key) {
  2226. if (!(this instanceof Socket)) return new Socket(secure, host, port, path, key);
  2227. EventEmitter.call(this);
  2228. // Disconnected manually.
  2229. this.disconnected = false;
  2230. this._queue = [];
  2231. var httpProtocol = secure ? 'https://' : 'http://';
  2232. var wsProtocol = secure ? 'wss://' : 'ws://';
  2233. this._httpUrl = httpProtocol + host + ':' + port + path + key;
  2234. this._wsUrl = wsProtocol + host + ':' + port + path + 'peerjs?key=' + key;
  2235. }
  2236. util.inherits(Socket, EventEmitter);
  2237. /** Check in with ID or get one from server. */
  2238. Socket.prototype.start = function(id, token) {
  2239. this.id = id;
  2240. this._httpUrl += '/' + id + '/' + token;
  2241. this._wsUrl += '&id=' + id + '&token=' + token;
  2242. this._startXhrStream();
  2243. this._startWebSocket();
  2244. }
  2245. /** Start up websocket communications. */
  2246. Socket.prototype._startWebSocket = function(id) {
  2247. var self = this;
  2248. if (this._socket) {
  2249. return;
  2250. }
  2251. this._socket = new WebSocket(this._wsUrl);
  2252. this._socket.onmessage = function(event) {
  2253. try {
  2254. var data = JSON.parse(event.data);
  2255. self.emit('message', data);
  2256. } catch(e) {
  2257. util.log('Invalid server message', event.data);
  2258. return;
  2259. }
  2260. };
  2261. this._socket.onclose = function(event) {
  2262. util.log('Socket closed.');
  2263. self.disconnected = true;
  2264. self.emit('disconnected');
  2265. };
  2266. // Take care of the queue of connections if necessary and make sure Peer knows
  2267. // socket is open.
  2268. this._socket.onopen = function() {
  2269. if (self._timeout) {
  2270. clearTimeout(self._timeout);
  2271. setTimeout(function(){
  2272. self._http.abort();
  2273. self._http = null;
  2274. }, 5000);
  2275. }
  2276. self._sendQueuedMessages();
  2277. util.log('Socket open');
  2278. };
  2279. }
  2280. /** Start XHR streaming. */
  2281. Socket.prototype._startXhrStream = function(n) {
  2282. try {
  2283. var self = this;
  2284. this._http = new XMLHttpRequest();
  2285. this._http._index = 1;
  2286. this._http._streamIndex = n || 0;
  2287. this._http.open('post', this._httpUrl + '/id?i=' + this._http._streamIndex, true);
  2288. this._http.onreadystatechange = function() {
  2289. if (this.readyState == 2 && this.old) {
  2290. this.old.abort();
  2291. delete this.old;
  2292. } else if (this.readyState > 2 && this.status === 200 && this.responseText) {
  2293. self._handleStream(this);
  2294. } else if (this.status !== 200) {
  2295. // If we get a different status code, likely something went wrong.
  2296. // Stop streaming.
  2297. clearTimeout(self._timeout);
  2298. self.emit('disconnected');
  2299. }
  2300. };
  2301. this._http.send(null);
  2302. this._setHTTPTimeout();
  2303. } catch(e) {
  2304. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  2305. }
  2306. }
  2307. /** Handles onreadystatechange response as a stream. */
  2308. Socket.prototype._handleStream = function(http) {
  2309. // 3 and 4 are loading/done state. All others are not relevant.
  2310. var messages = http.responseText.split('\n');
  2311. // Check to see if anything needs to be processed on buffer.
  2312. if (http._buffer) {
  2313. while (http._buffer.length > 0) {
  2314. var index = http._buffer.shift();
  2315. var bufferedMessage = messages[index];
  2316. try {
  2317. bufferedMessage = JSON.parse(bufferedMessage);
  2318. } catch(e) {
  2319. http._buffer.shift(index);
  2320. break;
  2321. }
  2322. this.emit('message', bufferedMessage);
  2323. }
  2324. }
  2325. var message = messages[http._index];
  2326. if (message) {
  2327. http._index += 1;
  2328. // Buffering--this message is incomplete and we'll get to it next time.
  2329. // This checks if the httpResponse ended in a `\n`, in which case the last
  2330. // element of messages should be the empty string.
  2331. if (http._index === messages.length) {
  2332. if (!http._buffer) {
  2333. http._buffer = [];
  2334. }
  2335. http._buffer.push(http._index - 1);
  2336. } else {
  2337. try {
  2338. message = JSON.parse(message);
  2339. } catch(e) {
  2340. util.log('Invalid server message', message);
  2341. return;
  2342. }
  2343. this.emit('message', message);
  2344. }
  2345. }
  2346. }
  2347. Socket.prototype._setHTTPTimeout = function() {
  2348. var self = this;
  2349. this._timeout = setTimeout(function() {
  2350. var old = self._http;
  2351. if (!self._wsOpen()) {
  2352. self._startXhrStream(old._streamIndex + 1);
  2353. self._http.old = old;
  2354. } else {
  2355. old.abort();
  2356. }
  2357. }, 25000);
  2358. }
  2359. /** Is the websocket currently open? */
  2360. Socket.prototype._wsOpen = function() {
  2361. return this._socket && this._socket.readyState == 1;
  2362. }
  2363. /** Send queued messages. */
  2364. Socket.prototype._sendQueuedMessages = function() {
  2365. for (var i = 0, ii = this._queue.length; i < ii; i += 1) {
  2366. this.send(this._queue[i]);
  2367. }
  2368. }
  2369. /** Exposed send for DC & Peer. */
  2370. Socket.prototype.send = function(data) {
  2371. if (this.disconnected) {
  2372. return;
  2373. }
  2374. // If we didn't get an ID yet, we can't yet send anything so we should queue
  2375. // up these messages.
  2376. if (!this.id) {
  2377. this._queue.push(data);
  2378. return;
  2379. }
  2380. if (!data.type) {
  2381. this.emit('error', 'Invalid message');
  2382. return;
  2383. }
  2384. var message = JSON.stringify(data);
  2385. if (this._wsOpen()) {
  2386. this._socket.send(message);
  2387. } else {
  2388. var http = new XMLHttpRequest();
  2389. var url = this._httpUrl + '/' + data.type.toLowerCase();
  2390. http.open('post', url, true);
  2391. http.setRequestHeader('Content-Type', 'application/json');
  2392. http.send(message);
  2393. }
  2394. }
  2395. Socket.prototype.close = function() {
  2396. if (!this.disconnected && this._wsOpen()) {
  2397. this._socket.close();
  2398. this.disconnected = true;
  2399. }
  2400. }
  2401. })(this);