peer.js 83 KB

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