peer.js 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712
  1. /*! peerjs.js build:0.3.9, 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._lastServerId) {
  1543. this.destroy();
  1544. } else {
  1545. this.disconnect();
  1546. }
  1547. this.emitError(type, message);
  1548. };
  1549. /** Emits a typed error message. */
  1550. Peer.prototype.emitError = function(type, err) {
  1551. util.error('Error:', err);
  1552. if (typeof err === 'string') {
  1553. err = new Error(err);
  1554. }
  1555. err.type = type;
  1556. this.emit('error', err);
  1557. };
  1558. /**
  1559. * Destroys the Peer: closes all active connections as well as the connection
  1560. * to the server.
  1561. * Warning: The peer can no longer create or accept connections after being
  1562. * destroyed.
  1563. */
  1564. Peer.prototype.destroy = function() {
  1565. if (!this.destroyed) {
  1566. this._cleanup();
  1567. this.disconnect();
  1568. this.destroyed = true;
  1569. }
  1570. }
  1571. /** Disconnects every connection on this peer. */
  1572. Peer.prototype._cleanup = function() {
  1573. if (this.connections) {
  1574. var peers = Object.keys(this.connections);
  1575. for (var i = 0, ii = peers.length; i < ii; i++) {
  1576. this._cleanupPeer(peers[i]);
  1577. }
  1578. }
  1579. this.emit('close');
  1580. }
  1581. /** Closes all connections to this peer. */
  1582. Peer.prototype._cleanupPeer = function(peer) {
  1583. var connections = this.connections[peer];
  1584. for (var j = 0, jj = connections.length; j < jj; j += 1) {
  1585. connections[j].close();
  1586. }
  1587. }
  1588. /**
  1589. * Disconnects the Peer's connection to the PeerServer. Does not close any
  1590. * active connections.
  1591. * Warning: The peer can no longer create or accept connections after being
  1592. * disconnected. It also cannot reconnect to the server.
  1593. */
  1594. Peer.prototype.disconnect = function() {
  1595. var self = this;
  1596. util.setZeroTimeout(function(){
  1597. if (!self.disconnected) {
  1598. self.disconnected = true;
  1599. self.open = false;
  1600. if (self.socket) {
  1601. self.socket.close();
  1602. }
  1603. self.emit('disconnected', self.id);
  1604. self._lastServerId = self.id;
  1605. self.id = null;
  1606. }
  1607. });
  1608. }
  1609. /** Attempts to reconnect with the same ID. */
  1610. Peer.prototype.reconnect = function() {
  1611. if (this.disconnected && !this.destroyed) {
  1612. util.log('Attempting reconnection to server with ID ' + this._lastServerId);
  1613. this.disconnected = false;
  1614. this._initializeServerConnection();
  1615. this._initialize(this._lastServerId);
  1616. } else if (this.destroyed) {
  1617. throw new Error('This peer cannot reconnect to the server. It has already been destroyed.');
  1618. } else if (!this.disconnected && !this.open) {
  1619. // Do nothing. We're still connecting the first time.
  1620. util.error('In a hurry? We\'re still trying to make the initial connection!');
  1621. } else {
  1622. throw new Error('Peer ' + this.id + ' cannot reconnect because it is not disconnected from the server!');
  1623. }
  1624. };
  1625. /**
  1626. * Get a list of available peer IDs. If you're running your own server, you'll
  1627. * want to set allow_discovery: true in the PeerServer options. If you're using
  1628. * the cloud server, email team@peerjs.com to get the functionality enabled for
  1629. * your key.
  1630. */
  1631. Peer.prototype.listAllPeers = function(cb) {
  1632. cb = cb || function() {};
  1633. var self = this;
  1634. var http = new XMLHttpRequest();
  1635. var protocol = this.options.secure ? 'https://' : 'http://';
  1636. var url = protocol + this.options.host + ':' + this.options.port
  1637. + this.options.path + this.options.key + '/peers';
  1638. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  1639. url += queryString;
  1640. // If there's no ID we need to wait for one before trying to init socket.
  1641. http.open('get', url, true);
  1642. http.onerror = function(e) {
  1643. self._abort('server-error', 'Could not get peers from the server.');
  1644. cb([]);
  1645. }
  1646. http.onreadystatechange = function() {
  1647. if (http.readyState !== 4) {
  1648. return;
  1649. }
  1650. if (http.status === 401) {
  1651. var helpfulError = '';
  1652. if (self.options.host !== util.CLOUD_HOST) {
  1653. helpfulError = 'It looks like you\'re using the cloud server. You can email '
  1654. + 'team@peerjs.com to enable peer listing for your API key.';
  1655. } else {
  1656. helpfulError = 'You need to enable `allow_discovery` on your self-hosted'
  1657. + ' PeerServer to use this feature.';
  1658. }
  1659. throw new Error('It doesn\'t look like you have permission to list peers IDs. ' + helpfulError);
  1660. cb([]);
  1661. } else if (http.status !== 200) {
  1662. cb([]);
  1663. } else {
  1664. cb(JSON.parse(http.responseText));
  1665. }
  1666. };
  1667. http.send(null);
  1668. }
  1669. exports.Peer = Peer;
  1670. /**
  1671. * Wraps a DataChannel between two Peers.
  1672. */
  1673. function DataConnection(peer, provider, options) {
  1674. if (!(this instanceof DataConnection)) return new DataConnection(peer, provider, options);
  1675. EventEmitter.call(this);
  1676. this.options = util.extend({
  1677. serialization: 'binary',
  1678. reliable: false
  1679. }, options);
  1680. // Connection is not open yet.
  1681. this.open = false;
  1682. this.type = 'data';
  1683. this.peer = peer;
  1684. this.provider = provider;
  1685. this.id = this.options.connectionId || DataConnection._idPrefix + util.randomToken();
  1686. this.label = this.options.label || this.id;
  1687. this.metadata = this.options.metadata;
  1688. this.serialization = this.options.serialization;
  1689. this.reliable = this.options.reliable;
  1690. // Data channel buffering.
  1691. this._buffer = [];
  1692. this._buffering = false;
  1693. this.bufferSize = 0;
  1694. // For storing large data.
  1695. this._chunkedData = {};
  1696. if (this.options._payload) {
  1697. this._peerBrowser = this.options._payload.browser;
  1698. }
  1699. Negotiator.startConnection(
  1700. this,
  1701. this.options._payload || {
  1702. originator: true
  1703. }
  1704. );
  1705. }
  1706. util.inherits(DataConnection, EventEmitter);
  1707. DataConnection._idPrefix = 'dc_';
  1708. /** Called by the Negotiator when the DataChannel is ready. */
  1709. DataConnection.prototype.initialize = function(dc) {
  1710. this._dc = this.dataChannel = dc;
  1711. this._configureDataChannel();
  1712. }
  1713. DataConnection.prototype._configureDataChannel = function() {
  1714. var self = this;
  1715. if (util.supports.sctp) {
  1716. this._dc.binaryType = 'arraybuffer';
  1717. }
  1718. this._dc.onopen = function() {
  1719. util.log('Data channel connection success');
  1720. self.open = true;
  1721. self.emit('open');
  1722. }
  1723. // Use the Reliable shim for non Firefox browsers
  1724. if (!util.supports.sctp && this.reliable) {
  1725. this._reliable = new Reliable(this._dc, util.debug);
  1726. }
  1727. if (this._reliable) {
  1728. this._reliable.onmessage = function(msg) {
  1729. self.emit('data', msg);
  1730. };
  1731. } else {
  1732. this._dc.onmessage = function(e) {
  1733. self._handleDataMessage(e);
  1734. };
  1735. }
  1736. this._dc.onclose = function(e) {
  1737. util.log('DataChannel closed for:', self.peer);
  1738. self.close();
  1739. };
  1740. }
  1741. // Handles a DataChannel message.
  1742. DataConnection.prototype._handleDataMessage = function(e) {
  1743. var self = this;
  1744. var data = e.data;
  1745. var datatype = data.constructor;
  1746. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  1747. if (datatype === Blob) {
  1748. // Datatype should never be blob
  1749. util.blobToArrayBuffer(data, function(ab) {
  1750. data = util.unpack(ab);
  1751. self.emit('data', data);
  1752. });
  1753. return;
  1754. } else if (datatype === ArrayBuffer) {
  1755. data = util.unpack(data);
  1756. } else if (datatype === String) {
  1757. // String fallback for binary data for browsers that don't support binary yet
  1758. var ab = util.binaryStringToArrayBuffer(data);
  1759. data = util.unpack(ab);
  1760. }
  1761. } else if (this.serialization === 'json') {
  1762. data = JSON.parse(data);
  1763. }
  1764. // Check if we've chunked--if so, piece things back together.
  1765. // We're guaranteed that this isn't 0.
  1766. if (data.__peerData) {
  1767. var id = data.__peerData;
  1768. var chunkInfo = this._chunkedData[id] || {data: [], count: 0, total: data.total};
  1769. chunkInfo.data[data.n] = data.data;
  1770. chunkInfo.count += 1;
  1771. if (chunkInfo.total === chunkInfo.count) {
  1772. // Clean up before making the recursive call to `_handleDataMessage`.
  1773. delete this._chunkedData[id];
  1774. // We've received all the chunks--time to construct the complete data.
  1775. data = new Blob(chunkInfo.data);
  1776. this._handleDataMessage({data: data});
  1777. }
  1778. this._chunkedData[id] = chunkInfo;
  1779. return;
  1780. }
  1781. this.emit('data', data);
  1782. }
  1783. /**
  1784. * Exposed functionality for users.
  1785. */
  1786. /** Allows user to close connection. */
  1787. DataConnection.prototype.close = function() {
  1788. if (!this.open) {
  1789. return;
  1790. }
  1791. this.open = false;
  1792. Negotiator.cleanup(this);
  1793. this.emit('close');
  1794. }
  1795. /** Allows user to send data. */
  1796. DataConnection.prototype.send = function(data, chunked) {
  1797. if (!this.open) {
  1798. this.emit('error', new Error('Connection is not open. You should listen for the `open` event before sending messages.'));
  1799. return;
  1800. }
  1801. if (this._reliable) {
  1802. // Note: reliable shim sending will make it so that you cannot customize
  1803. // serialization.
  1804. this._reliable.send(data);
  1805. return;
  1806. }
  1807. var self = this;
  1808. if (this.serialization === 'json') {
  1809. this._bufferedSend(JSON.stringify(data));
  1810. } else if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  1811. var blob = util.pack(data);
  1812. // For Chrome-Firefox interoperability, we need to make Firefox "chunk"
  1813. // the data it sends out.
  1814. var needsChunking = util.chunkedBrowsers[this._peerBrowser] || util.chunkedBrowsers[util.browser];
  1815. if (needsChunking && !chunked && blob.size > util.chunkedMTU) {
  1816. this._sendChunks(blob);
  1817. return;
  1818. }
  1819. // DataChannel currently only supports strings.
  1820. if (!util.supports.sctp) {
  1821. util.blobToBinaryString(blob, function(str) {
  1822. self._bufferedSend(str);
  1823. });
  1824. } else if (!util.supports.binaryBlob) {
  1825. // We only do this if we really need to (e.g. blobs are not supported),
  1826. // because this conversion is costly.
  1827. util.blobToArrayBuffer(blob, function(ab) {
  1828. self._bufferedSend(ab);
  1829. });
  1830. } else {
  1831. this._bufferedSend(blob);
  1832. }
  1833. } else {
  1834. this._bufferedSend(data);
  1835. }
  1836. }
  1837. DataConnection.prototype._bufferedSend = function(msg) {
  1838. if (this._buffering || !this._trySend(msg)) {
  1839. this._buffer.push(msg);
  1840. this.bufferSize = this._buffer.length;
  1841. }
  1842. }
  1843. // Returns true if the send succeeds.
  1844. DataConnection.prototype._trySend = function(msg) {
  1845. try {
  1846. this._dc.send(msg);
  1847. } catch (e) {
  1848. this._buffering = true;
  1849. var self = this;
  1850. setTimeout(function() {
  1851. // Try again.
  1852. self._buffering = false;
  1853. self._tryBuffer();
  1854. }, 100);
  1855. return false;
  1856. }
  1857. return true;
  1858. }
  1859. // Try to send the first message in the buffer.
  1860. DataConnection.prototype._tryBuffer = function() {
  1861. if (this._buffer.length === 0) {
  1862. return;
  1863. }
  1864. var msg = this._buffer[0];
  1865. if (this._trySend(msg)) {
  1866. this._buffer.shift();
  1867. this.bufferSize = this._buffer.length;
  1868. this._tryBuffer();
  1869. }
  1870. }
  1871. DataConnection.prototype._sendChunks = function(blob) {
  1872. var blobs = util.chunk(blob);
  1873. for (var i = 0, ii = blobs.length; i < ii; i += 1) {
  1874. var blob = blobs[i];
  1875. this.send(blob, true);
  1876. }
  1877. }
  1878. DataConnection.prototype.handleMessage = function(message) {
  1879. var payload = message.payload;
  1880. switch (message.type) {
  1881. case 'ANSWER':
  1882. this._peerBrowser = payload.browser;
  1883. // Forward to negotiator
  1884. Negotiator.handleSDP(message.type, this, payload.sdp);
  1885. break;
  1886. case 'CANDIDATE':
  1887. Negotiator.handleCandidate(this, payload.candidate);
  1888. break;
  1889. default:
  1890. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  1891. break;
  1892. }
  1893. }
  1894. /**
  1895. * Wraps the streaming interface between two Peers.
  1896. */
  1897. function MediaConnection(peer, provider, options) {
  1898. if (!(this instanceof MediaConnection)) return new MediaConnection(peer, provider, options);
  1899. EventEmitter.call(this);
  1900. this.options = util.extend({}, options);
  1901. this.open = false;
  1902. this.type = 'media';
  1903. this.peer = peer;
  1904. this.provider = provider;
  1905. this.metadata = this.options.metadata;
  1906. this.localStream = this.options._stream;
  1907. this.id = this.options.connectionId || MediaConnection._idPrefix + util.randomToken();
  1908. if (this.localStream) {
  1909. Negotiator.startConnection(
  1910. this,
  1911. {_stream: this.localStream, originator: true}
  1912. );
  1913. }
  1914. };
  1915. util.inherits(MediaConnection, EventEmitter);
  1916. MediaConnection._idPrefix = 'mc_';
  1917. MediaConnection.prototype.addStream = function(remoteStream) {
  1918. util.log('Receiving stream', remoteStream);
  1919. this.remoteStream = remoteStream;
  1920. this.emit('stream', remoteStream); // Should we call this `open`?
  1921. };
  1922. MediaConnection.prototype.handleMessage = function(message) {
  1923. var payload = message.payload;
  1924. switch (message.type) {
  1925. case 'ANSWER':
  1926. // Forward to negotiator
  1927. Negotiator.handleSDP(message.type, this, payload.sdp);
  1928. this.open = true;
  1929. break;
  1930. case 'CANDIDATE':
  1931. Negotiator.handleCandidate(this, payload.candidate);
  1932. break;
  1933. default:
  1934. util.warn('Unrecognized message type:', message.type, 'from peer:', this.peer);
  1935. break;
  1936. }
  1937. }
  1938. MediaConnection.prototype.answer = function(stream) {
  1939. if (this.localStream) {
  1940. util.warn('Local stream already exists on this MediaConnection. Are you answering a call twice?');
  1941. return;
  1942. }
  1943. this.options._payload._stream = stream;
  1944. this.localStream = stream;
  1945. Negotiator.startConnection(
  1946. this,
  1947. this.options._payload
  1948. )
  1949. // Retrieve lost messages stored because PeerConnection not set up.
  1950. var messages = this.provider._getMessages(this.id);
  1951. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  1952. this.handleMessage(messages[i]);
  1953. }
  1954. this.open = true;
  1955. };
  1956. /**
  1957. * Exposed functionality for users.
  1958. */
  1959. /** Allows user to close connection. */
  1960. MediaConnection.prototype.close = function() {
  1961. if (!this.open) {
  1962. return;
  1963. }
  1964. this.open = false;
  1965. Negotiator.cleanup(this);
  1966. this.emit('close')
  1967. };
  1968. /**
  1969. * Manages all negotiations between Peers.
  1970. */
  1971. var Negotiator = {
  1972. pcs: {
  1973. data: {},
  1974. media: {}
  1975. }, // type => {peerId: {pc_id: pc}}.
  1976. //providers: {}, // provider's id => providers (there may be multiple providers/client.
  1977. queue: [] // connections that are delayed due to a PC being in use.
  1978. }
  1979. Negotiator._idPrefix = 'pc_';
  1980. /** Returns a PeerConnection object set up correctly (for data, media). */
  1981. Negotiator.startConnection = function(connection, options) {
  1982. var pc = Negotiator._getPeerConnection(connection, options);
  1983. if (connection.type === 'media' && options._stream) {
  1984. // Add the stream.
  1985. pc.addStream(options._stream);
  1986. }
  1987. // Set the connection's PC.
  1988. connection.pc = connection.peerConnection = pc;
  1989. // What do we need to do now?
  1990. if (options.originator) {
  1991. if (connection.type === 'data') {
  1992. // Create the datachannel.
  1993. var config = {};
  1994. // Dropping reliable:false support, since it seems to be crashing
  1995. // Chrome.
  1996. /*if (util.supports.sctp && !options.reliable) {
  1997. // If we have canonical reliable support...
  1998. config = {maxRetransmits: 0};
  1999. }*/
  2000. // Fallback to ensure older browsers don't crash.
  2001. if (!util.supports.sctp) {
  2002. config = {reliable: options.reliable};
  2003. }
  2004. var dc = pc.createDataChannel(connection.label, config);
  2005. connection.initialize(dc);
  2006. }
  2007. if (!util.supports.onnegotiationneeded) {
  2008. Negotiator._makeOffer(connection);
  2009. }
  2010. } else {
  2011. Negotiator.handleSDP('OFFER', connection, options.sdp);
  2012. }
  2013. }
  2014. Negotiator._getPeerConnection = function(connection, options) {
  2015. if (!Negotiator.pcs[connection.type]) {
  2016. util.error(connection.type + ' is not a valid connection type. Maybe you overrode the `type` property somewhere.');
  2017. }
  2018. if (!Negotiator.pcs[connection.type][connection.peer]) {
  2019. Negotiator.pcs[connection.type][connection.peer] = {};
  2020. }
  2021. var peerConnections = Negotiator.pcs[connection.type][connection.peer];
  2022. var pc;
  2023. // Not multiplexing while FF and Chrome have not-great support for it.
  2024. /*if (options.multiplex) {
  2025. ids = Object.keys(peerConnections);
  2026. for (var i = 0, ii = ids.length; i < ii; i += 1) {
  2027. pc = peerConnections[ids[i]];
  2028. if (pc.signalingState === 'stable') {
  2029. break; // We can go ahead and use this PC.
  2030. }
  2031. }
  2032. } else */
  2033. if (options.pc) { // Simplest case: PC id already provided for us.
  2034. pc = Negotiator.pcs[connection.type][connection.peer][options.pc];
  2035. }
  2036. if (!pc || pc.signalingState !== 'stable') {
  2037. pc = Negotiator._startPeerConnection(connection);
  2038. }
  2039. return pc;
  2040. }
  2041. /*
  2042. Negotiator._addProvider = function(provider) {
  2043. if ((!provider.id && !provider.disconnected) || !provider.socket.open) {
  2044. // Wait for provider to obtain an ID.
  2045. provider.on('open', function(id) {
  2046. Negotiator._addProvider(provider);
  2047. });
  2048. } else {
  2049. Negotiator.providers[provider.id] = provider;
  2050. }
  2051. }*/
  2052. /** Start a PC. */
  2053. Negotiator._startPeerConnection = function(connection) {
  2054. util.log('Creating RTCPeerConnection.');
  2055. var id = Negotiator._idPrefix + util.randomToken();
  2056. var optional = {};
  2057. if (connection.type === 'data' && !util.supports.sctp) {
  2058. optional = {optional: [{RtpDataChannels: true}]};
  2059. } else if (connection.type === 'media') {
  2060. // Interop req for chrome.
  2061. optional = {optional: [{DtlsSrtpKeyAgreement: true}]};
  2062. }
  2063. var pc = new RTCPeerConnection(connection.provider.options.config, optional);
  2064. Negotiator.pcs[connection.type][connection.peer][id] = pc;
  2065. Negotiator._setupListeners(connection, pc, id);
  2066. return pc;
  2067. }
  2068. /** Set up various WebRTC listeners. */
  2069. Negotiator._setupListeners = function(connection, pc, pc_id) {
  2070. var peerId = connection.peer;
  2071. var connectionId = connection.id;
  2072. var provider = connection.provider;
  2073. // ICE CANDIDATES.
  2074. util.log('Listening for ICE candidates.');
  2075. pc.onicecandidate = function(evt) {
  2076. if (evt.candidate) {
  2077. util.log('Received ICE candidates for:', connection.peer);
  2078. provider.socket.send({
  2079. type: 'CANDIDATE',
  2080. payload: {
  2081. candidate: evt.candidate,
  2082. type: connection.type,
  2083. connectionId: connection.id
  2084. },
  2085. dst: peerId
  2086. });
  2087. }
  2088. };
  2089. pc.oniceconnectionstatechange = function() {
  2090. switch (pc.iceConnectionState) {
  2091. case 'disconnected':
  2092. case 'failed':
  2093. util.log('iceConnectionState is disconnected, closing connections to ' + peerId);
  2094. connection.close();
  2095. break;
  2096. case 'completed':
  2097. pc.onicecandidate = util.noop;
  2098. break;
  2099. }
  2100. };
  2101. // Fallback for older Chrome impls.
  2102. pc.onicechange = pc.oniceconnectionstatechange;
  2103. // ONNEGOTIATIONNEEDED (Chrome)
  2104. util.log('Listening for `negotiationneeded`');
  2105. pc.onnegotiationneeded = function() {
  2106. util.log('`negotiationneeded` triggered');
  2107. if (pc.signalingState == 'stable') {
  2108. Negotiator._makeOffer(connection);
  2109. } else {
  2110. util.log('onnegotiationneeded triggered when not stable. Is another connection being established?');
  2111. }
  2112. };
  2113. // DATACONNECTION.
  2114. util.log('Listening for data channel');
  2115. // Fired between offer and answer, so options should already be saved
  2116. // in the options hash.
  2117. pc.ondatachannel = function(evt) {
  2118. util.log('Received data channel');
  2119. var dc = evt.channel;
  2120. var connection = provider.getConnection(peerId, connectionId);
  2121. connection.initialize(dc);
  2122. };
  2123. // MEDIACONNECTION.
  2124. util.log('Listening for remote stream');
  2125. pc.onaddstream = function(evt) {
  2126. util.log('Received remote stream');
  2127. var stream = evt.stream;
  2128. provider.getConnection(peerId, connectionId).addStream(stream);
  2129. };
  2130. }
  2131. Negotiator.cleanup = function(connection) {
  2132. util.log('Cleaning up PeerConnection to ' + connection.peer);
  2133. var pc = connection.pc;
  2134. if (!!pc && (pc.readyState !== 'closed' || pc.signalingState !== 'closed')) {
  2135. pc.close();
  2136. connection.pc = null;
  2137. }
  2138. }
  2139. Negotiator._makeOffer = function(connection) {
  2140. var pc = connection.pc;
  2141. pc.createOffer(function(offer) {
  2142. util.log('Created offer.');
  2143. if (!util.supports.sctp && connection.type === 'data' && connection.reliable) {
  2144. offer.sdp = Reliable.higherBandwidthSDP(offer.sdp);
  2145. }
  2146. pc.setLocalDescription(offer, function() {
  2147. util.log('Set localDescription: offer', 'for:', connection.peer);
  2148. connection.provider.socket.send({
  2149. type: 'OFFER',
  2150. payload: {
  2151. sdp: offer,
  2152. type: connection.type,
  2153. label: connection.label,
  2154. connectionId: connection.id,
  2155. reliable: connection.reliable,
  2156. serialization: connection.serialization,
  2157. metadata: connection.metadata,
  2158. browser: util.browser
  2159. },
  2160. dst: connection.peer
  2161. });
  2162. }, function(err) {
  2163. connection.provider.emitError('webrtc', err);
  2164. util.log('Failed to setLocalDescription, ', err);
  2165. });
  2166. }, function(err) {
  2167. connection.provider.emitError('webrtc', err);
  2168. util.log('Failed to createOffer, ', err);
  2169. }, connection.options.constraints);
  2170. }
  2171. Negotiator._makeAnswer = function(connection) {
  2172. var pc = connection.pc;
  2173. pc.createAnswer(function(answer) {
  2174. util.log('Created answer.');
  2175. if (!util.supports.sctp && connection.type === 'data' && connection.reliable) {
  2176. answer.sdp = Reliable.higherBandwidthSDP(answer.sdp);
  2177. }
  2178. pc.setLocalDescription(answer, function() {
  2179. util.log('Set localDescription: answer', 'for:', connection.peer);
  2180. connection.provider.socket.send({
  2181. type: 'ANSWER',
  2182. payload: {
  2183. sdp: answer,
  2184. type: connection.type,
  2185. connectionId: connection.id,
  2186. browser: util.browser
  2187. },
  2188. dst: connection.peer
  2189. });
  2190. }, function(err) {
  2191. connection.provider.emitError('webrtc', err);
  2192. util.log('Failed to setLocalDescription, ', err);
  2193. });
  2194. }, function(err) {
  2195. connection.provider.emitError('webrtc', err);
  2196. util.log('Failed to create answer, ', err);
  2197. });
  2198. }
  2199. /** Handle an SDP. */
  2200. Negotiator.handleSDP = function(type, connection, sdp) {
  2201. sdp = new RTCSessionDescription(sdp);
  2202. var pc = connection.pc;
  2203. util.log('Setting remote description', sdp);
  2204. pc.setRemoteDescription(sdp, function() {
  2205. util.log('Set remoteDescription:', type, 'for:', connection.peer);
  2206. if (type === 'OFFER') {
  2207. Negotiator._makeAnswer(connection);
  2208. }
  2209. }, function(err) {
  2210. connection.provider.emitError('webrtc', err);
  2211. util.log('Failed to setRemoteDescription, ', err);
  2212. });
  2213. }
  2214. /** Handle a candidate. */
  2215. Negotiator.handleCandidate = function(connection, ice) {
  2216. var candidate = ice.candidate;
  2217. var sdpMLineIndex = ice.sdpMLineIndex;
  2218. connection.pc.addIceCandidate(new RTCIceCandidate({
  2219. sdpMLineIndex: sdpMLineIndex,
  2220. candidate: candidate
  2221. }));
  2222. util.log('Added ICE candidate for:', connection.peer);
  2223. }
  2224. /**
  2225. * An abstraction on top of WebSockets and XHR streaming to provide fastest
  2226. * possible connection for peers.
  2227. */
  2228. function Socket(secure, host, port, path, key) {
  2229. if (!(this instanceof Socket)) return new Socket(secure, host, port, path, key);
  2230. EventEmitter.call(this);
  2231. // Disconnected manually.
  2232. this.disconnected = false;
  2233. this._queue = [];
  2234. var httpProtocol = secure ? 'https://' : 'http://';
  2235. var wsProtocol = secure ? 'wss://' : 'ws://';
  2236. this._httpUrl = httpProtocol + host + ':' + port + path + key;
  2237. this._wsUrl = wsProtocol + host + ':' + port + path + 'peerjs?key=' + key;
  2238. }
  2239. util.inherits(Socket, EventEmitter);
  2240. /** Check in with ID or get one from server. */
  2241. Socket.prototype.start = function(id, token) {
  2242. this.id = id;
  2243. this._httpUrl += '/' + id + '/' + token;
  2244. this._wsUrl += '&id=' + id + '&token=' + token;
  2245. this._startXhrStream();
  2246. this._startWebSocket();
  2247. }
  2248. /** Start up websocket communications. */
  2249. Socket.prototype._startWebSocket = function(id) {
  2250. var self = this;
  2251. if (this._socket) {
  2252. return;
  2253. }
  2254. this._socket = new WebSocket(this._wsUrl);
  2255. this._socket.onmessage = function(event) {
  2256. try {
  2257. var data = JSON.parse(event.data);
  2258. self.emit('message', data);
  2259. } catch(e) {
  2260. util.log('Invalid server message', event.data);
  2261. return;
  2262. }
  2263. };
  2264. this._socket.onclose = function(event) {
  2265. util.log('Socket closed.');
  2266. self.disconnected = true;
  2267. self.emit('disconnected');
  2268. };
  2269. // Take care of the queue of connections if necessary and make sure Peer knows
  2270. // socket is open.
  2271. this._socket.onopen = function() {
  2272. if (self._timeout) {
  2273. clearTimeout(self._timeout);
  2274. setTimeout(function(){
  2275. self._http.abort();
  2276. self._http = null;
  2277. }, 5000);
  2278. }
  2279. self._sendQueuedMessages();
  2280. util.log('Socket open');
  2281. };
  2282. }
  2283. /** Start XHR streaming. */
  2284. Socket.prototype._startXhrStream = function(n) {
  2285. try {
  2286. var self = this;
  2287. this._http = new XMLHttpRequest();
  2288. this._http._index = 1;
  2289. this._http._streamIndex = n || 0;
  2290. this._http.open('post', this._httpUrl + '/id?i=' + this._http._streamIndex, true);
  2291. this._http.onreadystatechange = function() {
  2292. if (this.readyState == 2 && this.old) {
  2293. this.old.abort();
  2294. delete this.old;
  2295. } else if (this.readyState > 2 && this.status === 200 && this.responseText) {
  2296. self._handleStream(this);
  2297. } else if (this.status !== 200) {
  2298. // If we get a different status code, likely something went wrong.
  2299. // Stop streaming.
  2300. clearTimeout(self._timeout);
  2301. self.emit('disconnected');
  2302. }
  2303. };
  2304. this._http.send(null);
  2305. this._setHTTPTimeout();
  2306. } catch(e) {
  2307. util.log('XMLHttpRequest not available; defaulting to WebSockets');
  2308. }
  2309. }
  2310. /** Handles onreadystatechange response as a stream. */
  2311. Socket.prototype._handleStream = function(http) {
  2312. // 3 and 4 are loading/done state. All others are not relevant.
  2313. var messages = http.responseText.split('\n');
  2314. // Check to see if anything needs to be processed on buffer.
  2315. if (http._buffer) {
  2316. while (http._buffer.length > 0) {
  2317. var index = http._buffer.shift();
  2318. var bufferedMessage = messages[index];
  2319. try {
  2320. bufferedMessage = JSON.parse(bufferedMessage);
  2321. } catch(e) {
  2322. http._buffer.shift(index);
  2323. break;
  2324. }
  2325. this.emit('message', bufferedMessage);
  2326. }
  2327. }
  2328. var message = messages[http._index];
  2329. if (message) {
  2330. http._index += 1;
  2331. // Buffering--this message is incomplete and we'll get to it next time.
  2332. // This checks if the httpResponse ended in a `\n`, in which case the last
  2333. // element of messages should be the empty string.
  2334. if (http._index === messages.length) {
  2335. if (!http._buffer) {
  2336. http._buffer = [];
  2337. }
  2338. http._buffer.push(http._index - 1);
  2339. } else {
  2340. try {
  2341. message = JSON.parse(message);
  2342. } catch(e) {
  2343. util.log('Invalid server message', message);
  2344. return;
  2345. }
  2346. this.emit('message', message);
  2347. }
  2348. }
  2349. }
  2350. Socket.prototype._setHTTPTimeout = function() {
  2351. var self = this;
  2352. this._timeout = setTimeout(function() {
  2353. var old = self._http;
  2354. if (!self._wsOpen()) {
  2355. self._startXhrStream(old._streamIndex + 1);
  2356. self._http.old = old;
  2357. } else {
  2358. old.abort();
  2359. }
  2360. }, 25000);
  2361. }
  2362. /** Is the websocket currently open? */
  2363. Socket.prototype._wsOpen = function() {
  2364. return this._socket && this._socket.readyState == 1;
  2365. }
  2366. /** Send queued messages. */
  2367. Socket.prototype._sendQueuedMessages = function() {
  2368. for (var i = 0, ii = this._queue.length; i < ii; i += 1) {
  2369. this.send(this._queue[i]);
  2370. }
  2371. }
  2372. /** Exposed send for DC & Peer. */
  2373. Socket.prototype.send = function(data) {
  2374. if (this.disconnected) {
  2375. return;
  2376. }
  2377. // If we didn't get an ID yet, we can't yet send anything so we should queue
  2378. // up these messages.
  2379. if (!this.id) {
  2380. this._queue.push(data);
  2381. return;
  2382. }
  2383. if (!data.type) {
  2384. this.emit('error', 'Invalid message');
  2385. return;
  2386. }
  2387. var message = JSON.stringify(data);
  2388. if (this._wsOpen()) {
  2389. this._socket.send(message);
  2390. } else {
  2391. var http = new XMLHttpRequest();
  2392. var url = this._httpUrl + '/' + data.type.toLowerCase();
  2393. http.open('post', url, true);
  2394. http.setRequestHeader('Content-Type', 'application/json');
  2395. http.send(message);
  2396. }
  2397. }
  2398. Socket.prototype.close = function() {
  2399. if (!this.disconnected && this._wsOpen()) {
  2400. this._socket.close();
  2401. this.disconnected = true;
  2402. }
  2403. }
  2404. })(this);