Skip to content

Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.

Updates the library. Removes oncontextmenu handlers.

hristoterezov6ad924344687
diff --git a/index.html b/index.html
index fda53fe7dc..6f7f2d76af 100644
--- a/index.html
+++ b/index.html
@@ -154,7 +154,7 @@
<canvas id="dominantSpeakerAudioLevel"></canvas>
</div>
<div id="largeVideoWrapper">
- <video id="largeVideo" muted="true" autoplay oncontextmenu="return false;"></video>
+ <video id="largeVideo" muted="true" autoplay></video>
</div>
<span id="videoConnectionMessage"></span>
</div>
@@ -163,9 +163,9 @@
<span id="localVideoContainer" class="videocontainer">
<span id="localNick" class="nick"></span>
<span id="localVideoWrapper">
- <!--<video id="localVideo" autoplay oncontextmenu="return false;" muted></video> - is now per stream generated -->
+ <!--<video id="localVideo" autoplay muted></video> - is now per stream generated -->
</span>
- <audio id="localAudio" autoplay oncontextmenu="return false;" muted></audio>
+ <audio id="localAudio" autoplay muted></audio>
<span class="focusindicator"></span>
</span>
<audio id="userJoined" src="sounds/joined.wav" preload="auto"></audio>
diff --git a/libs/lib-jitsi-meet.js b/libs/lib-jitsi-meet.js
index 53ea2fffbe..10d936168a 100644
--- a/libs/lib-jitsi-meet.js
+++ b/libs/lib-jitsi-meet.js
@@ -14,6 +14,7 @@ var JitsiParticipant = require("./JitsiParticipant");
var Statistics = require("./modules/statistics/statistics");
var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
var JitsiTrackEvents = require("./JitsiTrackEvents");
+var Settings = require("./modules/settings/Settings");
/**
* Creates a JitsiConference object with the given name and properties.
@@ -34,12 +35,22 @@ function JitsiConference(options) {
this.connection = this.options.connection;
this.xmpp = this.connection.xmpp;
this.eventEmitter = new EventEmitter();
- this.room = this.xmpp.createRoom(this.options.name, this.options.config);
+ var confID = this.options.name + '@' + this.xmpp.options.hosts.muc;
+ this.settings = new Settings(confID);
+ this.room = this.xmpp.createRoom(this.options.name, this.options.config,
+ this.settings);
this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
this.rtc = new RTC(this.room, options);
- if(!RTC.options.disableAudioLevels)
- this.statistics = new Statistics();
+ this.statistics = new Statistics({
+ disableAudioLevels: RTC.options.disableAudioLevels,
+ callStatsID: this.options.config.callStatsID,
+ callStatsSecret: this.options.config.callStatsSecret,
+ disableThirdPartyRequests: this.options.config.disableThirdPartyRequests
+ });
setupListeners(this);
+ JitsiMeetJS._gumFailedHandler.push(function(error) {
+ this.statistics.sendGetUserMediaFailed(error);
+ }.bind(this));
this.participants = {};
this.lastDominantSpeaker = null;
this.dtmfManager = null;
@@ -261,9 +272,12 @@ JitsiConference.prototype.addTrack = function (track) {
track.muteHandler = this._fireMuteChangeEvent.bind(this, track);
track.stopHandler = this.removeTrack.bind(this, track);
track.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
- track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, track.muteHandler);
- track.addEventListener(JitsiTrackEvents.TRACK_STOPPED, track.stopHandler);
- track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, track.audioLevelHandler);
+ track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
+ track.muteHandler);
+ track.addEventListener(JitsiTrackEvents.TRACK_STOPPED,
+ track.stopHandler);
+ track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
+ track.audioLevelHandler);
this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
}.bind(this));
};
@@ -719,6 +733,29 @@ JitsiConference.prototype.getLogs = function () {
return data;
};
+/**
+ * Sends the given feedback through CallStats if enabled.
+ *
+ * @param overallFeedback an integer between 1 and 5 indicating the
+ * user feedback
+ * @param detailedFeedback detailed feedback from the user. Not yet used
+ */
+JitsiConference.prototype.sendFeedback =
+function(overallFeedback, detailedFeedback){
+ this.statistics.sendFeedback(overallFeedback, detailedFeedback);
+}
+
+/**
+ * Returns true if the callstats integration is enabled, otherwise returns
+ * false.
+ *
+ * @returns true if the callstats integration is enabled, otherwise returns
+ * false.
+ */
+JitsiConference.prototype.isCallstatsEnabled = function () {
+ return this.statistics.isCallstatsEnabled();
+}
+
/**
* Setups the listeners needed for the conference.
* @param conference the conference
@@ -726,8 +763,7 @@ JitsiConference.prototype.getLogs = function () {
function setupListeners(conference) {
conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
conference.rtc.onIncommingCall(event);
- if(conference.statistics)
- conference.statistics.startRemoteStats(event.peerconnection);
+ conference.statistics.startRemoteStats(event.peerconnection);
});
conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
@@ -909,6 +945,51 @@ function setupListeners(conference) {
// RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
// conference.room.updateDeviceAvailability(devices);
// });
+
+ conference.room.addListener(XMPPEvents.PEERCONNECTION_READY,
+ function (session) {
+ conference.statistics.startCallStats(
+ session, conference.settings);
+ });
+
+ conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED,
+ function () {
+ conference.statistics.sendSetupFailedEvent();
+ });
+
+ conference.on(JitsiConferenceEvents.TRACK_MUTE_CHANGED,
+ function (track) {
+ if(!track.isLocal())
+ return;
+ var type = (track.getType() === "audio")? "audio" : "video";
+ conference.statistics.sendMuteEvent(track.isMuted(), type);
+ });
+
+ conference.room.addListener(XMPPEvents.CREATE_OFFER_FAILED, function (e, pc) {
+ conference.statistics.sendCreateOfferFailed(e, pc);
+ });
+
+ conference.room.addListener(XMPPEvents.CREATE_ANSWER_FAILED, function (e, pc) {
+ conference.statistics.sendCreateAnswerFailed(e, pc);
+ });
+
+ conference.room.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_FAILED,
+ function (e, pc) {
+ conference.statistics.sendSetLocalDescFailed(e, pc);
+ }
+ );
+
+ conference.room.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_FAILED,
+ function (e, pc) {
+ conference.statistics.sendSetRemoteDescFailed(e, pc);
+ }
+ );
+
+ conference.room.addListener(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
+ function (e, pc) {
+ conference.statistics.sendAddIceCandidateFailed(e, pc);
+ }
+ );
}
}
@@ -916,7 +997,7 @@ function setupListeners(conference) {
module.exports = JitsiConference;
}).call(this,"/JitsiConference.js")
-},{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/RTCEvents":75,"./service/authentication/AuthenticationEvents":77,"./service/xmpp/XMPPEvents":81,"events":43,"jitsi-meet-logger":47}],2:[function(require,module,exports){
+},{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/settings/Settings":21,"./modules/statistics/statistics":25,"./service/RTC/RTCEvents":132,"./service/authentication/AuthenticationEvents":134,"./service/xmpp/XMPPEvents":138,"events":45,"jitsi-meet-logger":49}],2:[function(require,module,exports){
/**
* Enumeration with the errors for the conference.
* @type {{string: string}}
@@ -1145,7 +1226,7 @@ JitsiConnection.prototype.removeEventListener = function (event, listener) {
module.exports = JitsiConnection;
-},{"./JitsiConference":1,"./modules/xmpp/xmpp":41}],5:[function(require,module,exports){
+},{"./JitsiConference":1,"./modules/xmpp/xmpp":43}],5:[function(require,module,exports){
/**
* Enumeration with the errors for the connection.
* @type {{string: string}}
@@ -1241,6 +1322,10 @@ var LibJitsiMeet = {
track: JitsiTrackErrors
},
logLevels: Logger.levels,
+ /**
+ * Array of functions that will receive the GUM error.
+ */
+ _gumFailedHandler: [],
init: function (options) {
return RTC.init(options || {});
},
@@ -1288,6 +1373,10 @@ var LibJitsiMeet = {
}
return tracks;
}).catch(function (error) {
+ this._gumFailedHandler.forEach(function (handler) {
+ handler(error);
+ });
+ Statistics.sendGetUserMediaFailed(error);
if(error === JitsiTrackErrors.UNSUPPORTED_RESOLUTION) {
var oldResolution = options.resolution || '360';
var newResolution = getLowerResolution(oldResolution);
@@ -1297,7 +1386,7 @@ var LibJitsiMeet = {
return LibJitsiMeet.createLocalTracks(options);
}
return Promise.reject(error);
- });
+ }.bind(this));
},
/**
* Checks if its possible to enumerate available cameras/micropones.
@@ -1324,7 +1413,7 @@ window.Promise = window.Promise || require("es6-promise").Promise;
module.exports = LibJitsiMeet;
-},{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":24,"./service/RTC/Resolutions":76,"es6-promise":45,"jitsi-meet-logger":47}],8:[function(require,module,exports){
+},{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":25,"./service/RTC/Resolutions":133,"es6-promise":47,"jitsi-meet-logger":49}],8:[function(require,module,exports){
/* global Strophe */
/**
@@ -1548,7 +1637,7 @@ JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
};
}).call(this,"/modules/DTMF/JitsiDTMFManager.js")
-},{"jitsi-meet-logger":47}],12:[function(require,module,exports){
+},{"jitsi-meet-logger":49}],12:[function(require,module,exports){
(function (__filename){
/* global config, APP, Strophe */
@@ -1772,7 +1861,7 @@ module.exports = DataChannels;
}).call(this,"/modules/RTC/DataChannels.js")
-},{"../../service/RTC/RTCEvents":75,"jitsi-meet-logger":47}],13:[function(require,module,exports){
+},{"../../service/RTC/RTCEvents":132,"jitsi-meet-logger":49}],13:[function(require,module,exports){
var JitsiTrack = require("./JitsiTrack");
var RTCBrowserType = require("./RTCBrowserType");
var JitsiTrackEvents = require('../../JitsiTrackEvents');
@@ -1955,7 +2044,7 @@ function JitsiRemoteTrack(RTC, data, sid, ssrc) {
JitsiTrack.call(this, RTC, data.stream,
function () {
this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
- }.bind(this));
+ }.bind(this), data.type);
this.rtc = RTC;
this.sid = sid;
this.stream = data.stream;
@@ -2011,8 +2100,6 @@ JitsiRemoteTrack.prototype.isLocal = function () {
delete JitsiRemoteTrack.prototype.stop;
-delete JitsiRemoteTrack.prototype.start;
-
module.exports = JitsiRemoteTrack;
},{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
@@ -2029,6 +2116,10 @@ var RTC = require("./RTCUtils");
*/
function implementOnEndedHandling(jitsiTrack) {
var stream = jitsiTrack.getOriginalStream();
+
+ if(!stream)
+ return;
+
var originalStop = stream.stop;
stream.stop = function () {
originalStop.apply(stream);
@@ -2074,8 +2165,11 @@ function addMediaStreamInactiveHandler(mediaStream, handler) {
* @param stream the stream
* @param streamInactiveHandler the function that will handle
* onended/oninactive events of the stream.
+ * @param type optionally a type can be specified.
+ * This is the case where we are creating a dummy track with no stream
+ * Currently this happens when a remote side is starting with video muted
*/
-function JitsiTrack(rtc, stream, streamInactiveHandler)
+function JitsiTrack(rtc, stream, streamInactiveHandler, type)
{
/**
* Array with the HTML elements that are displaying the streams.
@@ -2086,9 +2180,9 @@ function JitsiTrack(rtc, stream, streamInactiveHandler)
this.stream = stream;
this.eventEmitter = new EventEmitter();
this.audioLevel = -1;
- this.type = (this.stream.getVideoTracks().length > 0)?
+ this.type = type || (this.stream.getVideoTracks().length > 0)?
JitsiTrack.VIDEO : JitsiTrack.AUDIO;
- if(this.type == "audio") {
+ if(this.type == JitsiTrack.AUDIO) {
this._getTracks = function () {
return this.stream.getAudioTracks();
}.bind(this);
@@ -2278,7 +2372,7 @@ JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
module.exports = JitsiTrack;
-},{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":43}],16:[function(require,module,exports){
+},{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":45}],16:[function(require,module,exports){
/* global APP */
var EventEmitter = require("events");
var RTCBrowserType = require("./RTCBrowserType");
@@ -2317,12 +2411,25 @@ function RTC(room, options) {
this.options = options || {};
room.addPresenceListener("videomuted", function (values, from) {
if(self.remoteStreams[from]) {
- self.remoteStreams[from][JitsiTrack.VIDEO].setMute(values.value == "true");
+ // If there is no video track, but we receive it is muted,
+ // we need to create a dummy track which we will mute, so we can
+ // notify interested about the muting
+ if(!self.remoteStreams[from][JitsiTrack.VIDEO]) {
+ self.createRemoteStream(
+ {peerjid:room.roomjid + "/" + from,
+ videoType:"camera",
+ type:JitsiTrack.VIDEO},
+ null, null);
+ }
+
+ self.remoteStreams[from][JitsiTrack.VIDEO]
+ .setMute(values.value == "true");
}
});
room.addPresenceListener("audiomuted", function (values, from) {
if(self.remoteStreams[from]) {
- self.remoteStreams[from][JitsiTrack.AUDIO].setMute(values.value == "true");
+ self.remoteStreams[from][JitsiTrack.AUDIO]
+ .setMute(values.value == "true");
}
});
}
@@ -2523,7 +2630,7 @@ RTC.prototype.setAudioLevel = function (jid, audioLevel) {
}
module.exports = RTC;
-},{"../../service/RTC/MediaStreamTypes":74,"../../service/RTC/RTCEvents.js":75,"../../service/desktopsharing/DesktopSharingEventTypes":78,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":43}],17:[function(require,module,exports){
+},{"../../service/RTC/MediaStreamTypes":131,"../../service/RTC/RTCEvents.js":132,"../../service/desktopsharing/DesktopSharingEventTypes":135,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":45}],17:[function(require,module,exports){
var currentBrowser;
@@ -3516,7 +3623,7 @@ var RTCUtils = {
module.exports = RTCUtils;
}).call(this,"/modules/RTC/RTCUtils.js")
-},{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":75,"../../service/RTC/Resolutions":76,"../xmpp/SDPUtil":31,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":43,"jitsi-meet-logger":47}],19:[function(require,module,exports){
+},{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":132,"../../service/RTC/Resolutions":133,"../xmpp/SDPUtil":33,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":45,"jitsi-meet-logger":49}],19:[function(require,module,exports){
(function (__filename){
/* global chrome, $, alert */
/* jshint -W003 */
@@ -3932,7 +4039,7 @@ function initFirefoxExtensionDetection(options) {
module.exports = ScreenObtainer;
}).call(this,"/modules/RTC/ScreenObtainer.js")
-},{"../../JitsiTrackErrors":9,"../../service/desktopsharing/DesktopSharingEventTypes":78,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":47}],20:[function(require,module,exports){
+},{"../../JitsiTrackErrors":9,"../../service/desktopsharing/DesktopSharingEventTypes":135,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":49}],20:[function(require,module,exports){
(function (__filename){
/*! adapterjs - v0.12.3 - 2015-11-16 */
var console = require("jitsi-meet-logger").getLogger(__filename);
@@ -5116,10 +5223,12 @@ if (navigator.mozGetUserMedia) {
}
}).call(this,"/modules/RTC/adapter.screenshare.js")
-},{"jitsi-meet-logger":47}],21:[function(require,module,exports){
+},{"jitsi-meet-logger":49}],21:[function(require,module,exports){
(function (__filename){
-
var logger = require("jitsi-meet-logger").getLogger(__filename);
+
+var UsernameGenerator = require('../util/UsernameGenerator');
+
function supportsLocalStorage() {
try {
return 'localStorage' in window && window.localStorage !== null;
@@ -5142,6 +5251,7 @@ function Settings(conferenceID) {
this.userId;
this.confSettings = null;
this.conferenceID = conferenceID;
+ this.callStatsUserName;
if (supportsLocalStorage()) {
if(!window.localStorage.getItem(conferenceID))
this.confSettings = {};
@@ -5153,11 +5263,21 @@ function Settings(conferenceID) {
this.confSettings.jitsiMeetId);
this.save();
}
+ if (!this.confSettings.callStatsUserName) {
+ this.confSettings.callStatsUserName
+ = UsernameGenerator.generateUsername();
+ logger.log('generated callstats uid',
+ this.confSettings.callStatsUserName);
+ this.save();
+ }
+
this.userId = this.confSettings.jitsiMeetId || '';
this.displayName = this.confSettings.displayname || '';
+ this.callStatsUserName = this.confSettings.callStatsUserName || '';
} else {
logger.log("local storage is not supported");
this.userId = generateUniqueId();
+ this.callStatsUserName = UsernameGenerator.generateUsername();
}
}
@@ -5172,18 +5292,288 @@ Settings.prototype.setDisplayName = function (newDisplayName) {
this.confSettings.displayname = displayName;
this.save();
return this.displayName;
-},
+}
+
Settings.prototype.getSettings = function () {
return {
displayName: this.displayName,
uid: this.userId
};
-},
+}
+
+/**
+ * Returns fake username for callstats
+ * @returns {string} fake username for callstats
+ */
+Settings.prototype.getCallStatsUserName = function () {
+ return this.callStatsUserName;
+}
module.exports = Settings;
}).call(this,"/modules/settings/Settings.js")
-},{"jitsi-meet-logger":47}],22:[function(require,module,exports){
+},{"../util/UsernameGenerator":27,"jitsi-meet-logger":49}],22:[function(require,module,exports){
+(function (__filename){
+/* global $, Strophe, callstats */
+var logger = require("jitsi-meet-logger").getLogger(__filename);
+
+var jsSHA = require('jssha');
+var io = require('socket.io-client');
+
+/**
+ * @const
+ * @see http://www.callstats.io/api/#enumeration-of-wrtcfuncnames
+ */
+var wrtcFuncNames = {
+ createOffer: "createOffer",
+ createAnswer: "createAnswer",
+ setLocalDescription: "setLocalDescription",
+ setRemoteDescription: "setRemoteDescription",
+ addIceCandidate: "addIceCandidate",
+ getUserMedia: "getUserMedia"
+};
+
+var callStats = null;
+
+function initCallback (err, msg) {
+ logger.log("CallStats Status: err=" + err + " msg=" + msg);
+}
+
+/**
+ * Returns a function which invokes f in a try/catch block, logs any exception
+ * to the console, and then swallows it.
+ *
+ * @param f the function to invoke in a try/catch block
+ * @return a function which invokes f in a try/catch block, logs any exception
+ * to the console, and then swallows it
+ */
+function _try_catch (f) {
+ return function () {
+ try {
+ f.apply(this, arguments);
+ } catch (e) {
+ logger.error(e);
+ }
+ };
+}
+
+/**
+ * Creates new CallStats instance that handles all callstats API calls.
+ * @param peerConnection {JingleSessionPC} the session object
+ * @param Settings {Settings} the settings instance. Declared in
+ * /modules/settings/Settings.js
+ * @param options {object} credentials for callstats.
+ */
+var CallStats = _try_catch(function(jingleSession, Settings, options) {
+ try{
+ //check weather that should work with more than 1 peerconnection
+ if(!callStats) {
+ callStats = new callstats($, io, jsSHA);
+ } else {
+ return;
+ }
+
+ this.session = jingleSession;
+ this.peerconnection = jingleSession.peerconnection.peerconnection;
+
+ this.userID = Settings.getCallStatsUserName();
+
+ //FIXME: change it to something else (maybe roomName)
+ var location = window.location;
+ this.confID = location.hostname + location.pathname;
+
+ //userID is generated or given by the origin server
+ callStats.initialize(options.callStatsID,
+ options.callStatsSecret,
+ this.userID,
+ initCallback);
+
+ callStats.addNewFabric(this.peerconnection,
+ Strophe.getResourceFromJid(jingleSession.peerjid),
+ callStats.fabricUsage.multiplex,
+ this.confID,
+ this.pcCallback.bind(this));
+ } catch (e) {
+ // The callstats.io API failed to initialize (e.g. because its
+ // download failed to succeed in general or on time). Further
+ // attempts to utilize it cannot possibly succeed.
+ callStats = null;
+ logger.error(e);
+ }
+ // notify callstats about failures if there were any
+ if (CallStats.pendingErrors.length) {
+ CallStats.pendingErrors.forEach(function (error) {
+ CallStats._reportError.call(this, error.type, error.error,
+ error.pc);
+ }, this);
+ CallStats.pendingErrors.length = 0;
+ }
+});
+
+// some errors may happen before CallStats init
+// in this case we accumulate them in this array
+// and send them to callstats on init
+CallStats.pendingErrors = [];
+
+CallStats.prototype.pcCallback = _try_catch(function (err, msg) {
+ if (!callStats) {
+ return;
+ }
+ logger.log("Monitoring status: "+ err + " msg: " + msg);
+ callStats.sendFabricEvent(this.peerconnection,
+ callStats.fabricEvent.fabricSetup, this.confID);
+});
+
+/**
+ * Notifies CallStats for mute events
+ * @param mute {boolean} true for muted and false for not muted
+ * @param type {String} "audio"/"video"
+ */
+CallStats.prototype.sendMuteEvent = _try_catch(function (mute, type) {
+ if (!callStats) {
+ return;
+ }
+ var event = null;
+ if (type === "video") {
+ event = (mute? callStats.fabricEvent.videoPause :
+ callStats.fabricEvent.videoResume);
+ }
+ else {
+ event = (mute? callStats.fabricEvent.audioMute :
+ callStats.fabricEvent.audioUnmute);
+ }
+ callStats.sendFabricEvent(this.peerconnection, event, this.confID);
+});
+
+/**
+ * Notifies CallStats for connection setup errors
+ */
+CallStats.prototype.sendTerminateEvent = _try_catch(function () {
+ if(!callStats) {
+ return;
+ }
+ callStats.sendFabricEvent(this.peerconnection,
+ callStats.fabricEvent.fabricTerminated, this.confID);
+});
+
+/**
+ * Notifies CallStats for connection setup errors
+ */
+CallStats.prototype.sendSetupFailedEvent = _try_catch(function () {
+ if(!callStats) {
+ return;
+ }
+ callStats.sendFabricEvent(this.peerconnection,
+ callStats.fabricEvent.fabricSetupFailed, this.confID);
+});
+
+/**
+ * Sends the given feedback through CallStats.
+ *
+ * @param overallFeedback an integer between 1 and 5 indicating the
+ * user feedback
+ * @param detailedFeedback detailed feedback from the user. Not yet used
+ */
+CallStats.prototype.sendFeedback = _try_catch(
+function(overallFeedback, detailedFeedback) {
+ if(!callStats) {
+ return;
+ }
+ var feedbackString = '{"userID":"' + this.userID + '"' +
+ ', "overall":' + overallFeedback +
+ ', "comment": "' + detailedFeedback + '"}';
+
+ var feedbackJSON = JSON.parse(feedbackString);
+
+ callStats.sendUserFeedback(this.confID, feedbackJSON);
+});
+
+/**
+ * Reports an error to callstats.
+ *
+ * @param type the type of the error, which will be one of the wrtcFuncNames
+ * @param e the error
+ * @param pc the peerconnection
+ * @private
+ */
+CallStats._reportError = function (type, e, pc) {
+ if (callStats) {
+ callStats.reportError(pc, this.confID, type, e);
+ } else {
+ CallStats.pendingErrors.push({ type: type, error: e, pc: pc});
+ }
+ // else just ignore it
+};
+
+/**
+ * Notifies CallStats that getUserMedia failed.
+ *
+ * @param {Error} e error to send
+ * @param {CallStats} cs callstats instance related to the error (optional)
+ */
+CallStats.sendGetUserMediaFailed = _try_catch(function (e, cs) {
+ CallStats._reportError.call(cs, wrtcFuncNames.getUserMedia, e, null);
+});
+
+/**
+ * Notifies CallStats that peer connection failed to create offer.
+ *
+ * @param {Error} e error to send
+ * @param {RTCPeerConnection} pc connection on which failure occured.
+ * @param {CallStats} cs callstats instance related to the error (optional)
+ */
+CallStats.sendCreateOfferFailed = _try_catch(function (e, pc, cs) {
+ CallStats._reportError.call(cs, wrtcFuncNames.createOffer, e, pc);
+});
+
+/**
+ * Notifies CallStats that peer connection failed to create answer.
+ *
+ * @param {Error} e error to send
+ * @param {RTCPeerConnection} pc connection on which failure occured.
+ * @param {CallStats} cs callstats instance related to the error (optional)
+ */
+CallStats.sendCreateAnswerFailed = _try_catch(function (e, pc, cs) {
+ CallStats._reportError.call(cs, wrtcFuncNames.createAnswer, e, pc);
+});
+
+/**
+ * Notifies CallStats that peer connection failed to set local description.
+ *
+ * @param {Error} e error to send
+ * @param {RTCPeerConnection} pc connection on which failure occured.
+ * @param {CallStats} cs callstats instance related to the error (optional)
+ */
+CallStats.sendSetLocalDescFailed = _try_catch(function (e, pc, cs) {
+ CallStats._reportError.call(cs, wrtcFuncNames.setLocalDescription, e, pc);
+});
+
+/**
+ * Notifies CallStats that peer connection failed to set remote description.
+ *
+ * @param {Error} e error to send
+ * @param {RTCPeerConnection} pc connection on which failure occured.
+ * @param {CallStats} cs callstats instance related to the error (optional)
+ */
+CallStats.sendSetRemoteDescFailed = _try_catch(function (e, pc, cs) {
+ CallStats._reportError.call(cs, wrtcFuncNames.setRemoteDescription, e, pc);
+});
+
+/**
+ * Notifies CallStats that peer connection failed to add ICE candidate.
+ *
+ * @param {Error} e error to send
+ * @param {RTCPeerConnection} pc connection on which failure occured.
+ * @param {CallStats} cs callstats instance related to the error (optional)
+ */
+CallStats.sendAddIceCandidateFailed = _try_catch(function (e, pc, cs) {
+ CallStats._reportError.call(cs, wrtcFuncNames.addIceCandidate, e, pc);
+});
+
+module.exports = CallStats;
+
+}).call(this,"/modules/statistics/CallStats.js")
+},{"jitsi-meet-logger":49,"jssha":50,"socket.io-client":81}],23:[function(require,module,exports){
/* global config */
/**
* Provides statistics for the local stream.
@@ -5313,7 +5703,7 @@ LocalStatsCollector.prototype.stop = function () {
module.exports = LocalStatsCollector;
-},{"../RTC/RTCBrowserType":17}],23:[function(require,module,exports){
+},{"../RTC/RTCBrowserType":17}],24:[function(require,module,exports){
(function (__filename){
/* global require, ssrc2jid */
/* jshint -W117 */
@@ -6040,35 +6430,57 @@ StatsCollector.prototype.processAudioLevelReport = function () {
};
}).call(this,"/modules/statistics/RTPStatsCollector.js")
-},{"../../service/statistics/Events":79,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":47}],24:[function(require,module,exports){
+},{"../../service/statistics/Events":136,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":49}],25:[function(require,module,exports){
/* global require, APP */
var LocalStats = require("./LocalStatsCollector.js");
var RTPStats = require("./RTPStatsCollector.js");
var EventEmitter = require("events");
var StatisticsEvents = require("../../service/statistics/Events");
-//var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
-//var XMPPEvents = require("../../service/xmpp/XMPPEvents");
-//var CallStats = require("./CallStats");
-//var RTCEvents = require("../../service/RTC/RTCEvents");
-
-//
-//function onDisposeConference(onUnload) {
-// CallStats.sendTerminateEvent();
-// stopRemote();
-// if(onUnload) {
-// stopLocal();
-// eventEmitter.removeAllListeners();
-// }
-//}
+var CallStats = require("./CallStats");
+
+// Since callstats.io is a third party, we cannot guarantee the quality of
+// their service. More specifically, their server may take noticeably long
+// time to respond. Consequently, it is in our best interest (in the sense
+// that the intergration of callstats.io is pretty important to us but not
+// enough to allow it to prevent people from joining a conference) to (1)
+// start downloading their API as soon as possible and (2) do the
+// downloading asynchronously.
+function loadCallStatsAPI() {
+ (function (d, src) {
+ var elementName = 'script';
+ var newScript = d.createElement(elementName);
+ var referenceNode = d.getElementsByTagName(elementName)[0];
+
+ newScript.async = true;
+ newScript.src = src;
+ referenceNode.parentNode.insertBefore(newScript, referenceNode);
+ })(document, 'https://api.callstats.io/static/callstats.min.js');
+ // FIXME At the time of this writing, we hope that the callstats.io API will
+ // have loaded by the time we needed it (i.e. CallStats.init is invoked).
+}
var eventEmitter = new EventEmitter();
-function Statistics() {
+function Statistics(options) {
this.rtpStats = null;
this.eventEmitter = new EventEmitter();
+ this.options = options || {};
+ this.callStatsIntegrationEnabled
+ = this.options.callStatsID && this.options.callStatsSecret
+ // Even though AppID and AppSecret may be specified, the integration of
+ // callstats.io may be disabled because of globally-disallowed requests
+ // to any third parties.
+ && (this.options.disableThirdPartyRequests !== true);
+ if(this.callStatsIntegrationEnabled)
+ loadCallStatsAPI();
+ this.audioLevelsEnabled = !this.disableAudioLevels || true;
+ this.callStats = null;
}
Statistics.prototype.startRemoteStats = function (peerconnection) {
+ if(!this.audioLevelsEnabled)
+ return;
+
if (this.rtpStats) {
this.rtpStats.stop();
}
@@ -6080,6 +6492,8 @@ Statistics.prototype.startRemoteStats = function (peerconnection) {
Statistics.localStats = [];
Statistics.startLocalStats = function (stream, callback) {
+ if(!this.audioLevelsEnabled)
+ return;
var localStats = new LocalStats(stream, 200, callback);
this.localStats.push(localStats);
localStats.start();
@@ -6087,32 +6501,50 @@ Statistics.startLocalStats = function (stream, callback) {
Statistics.prototype.addAudioLevelListener = function(listener)
{
+ if(!this.audioLevelsEnabled)
+ return;
this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
}
Statistics.prototype.removeAudioLevelListener = function(listener)
{
+ if(!this.audioLevelsEnabled)
+ return;
this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
}
Statistics.prototype.dispose = function () {
- Statistics.stopAllLocalStats();
- this.stopRemote();
- if(this.eventEmitter)
- this.eventEmitter.removeAllListeners();
+ if(this.audioLevelsEnabled) {
+ Statistics.stopAllLocalStats();
+ this.stopRemote();
+ if(this.eventEmitter)
+ this.eventEmitter.removeAllListeners();
- if(eventEmitter)
- eventEmitter.removeAllListeners();
+ if(eventEmitter)
+ eventEmitter.removeAllListeners();
+ }
+
+ if(this.callstats)
+ {
+ this.callstats.sendTerminateEvent();
+ this.callstats = null;
+ }
}
Statistics.stopAllLocalStats = function () {
+ if(!this.audioLevelsEnabled)
+ return;
+
for(var i = 0; i < this.localStats.length; i++)
this.localStats[i].stop();
this.localStats = [];
}
Statistics.stopLocalStats = function (stream) {
+ if(!this.audioLevelsEnabled)
+ return;
+
for(var i = 0; i < Statistics.localStats.length; i++)
if(Statistics.localStats[i].stream === stream){
var localStats = Statistics.localStats.splice(i, 1);
@@ -6122,7 +6554,7 @@ Statistics.stopLocalStats = function (stream) {
}
Statistics.prototype.stopRemote = function () {
- if (this.rtpStats) {
+ if (this.rtpStats && this.audioLevelsEnabled) {
this.rtpStats.stop();
this.eventEmitter.emit(StatisticsEvents.STOP);
this.rtpStats = null;
@@ -6140,120 +6572,187 @@ Statistics.prototype.stopRemote = function () {
* at this time.
*/
Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
-
+ if(!this.audioLevelsEnabled)
+ return;
var peerStats = this.rtpStats.jid2stats[peerJid];
return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
};
-Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
-//
-//var statistics = {
-// /**
-// * Indicates that this audio level is for local jid.
-// * @type {string}
-// */
-// LOCAL_JID: 'local',
-//
-// addConnectionStatsListener: function(listener)
-// {
-// eventEmitter.on("statistics.connectionstats", listener);
-// },
-//
-// removeConnectionStatsListener: function(listener)
-// {
-// eventEmitter.removeListener("statistics.connectionstats", listener);
-// },
-//
-//
-// addRemoteStatsStopListener: function(listener)
-// {
-// eventEmitter.on("statistics.stop", listener);
-// },
-//
-// removeRemoteStatsStopListener: function(listener)
-// {
-// eventEmitter.removeListener("statistics.stop", listener);
-// },
-//
-//
-// stopRemoteStatistics: function()
-// {
-// stopRemote();
-// },
-//
-//// Already implemented with the constructor
-// start: function () {
-// APP.RTC.addStreamListener(onStreamCreated,
-// StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
-// APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
-// //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
-// APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
-// startRemoteStats(event.peerconnection);
-//// CallStats.init(event);
-// });
-//// APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
-//// CallStats.init(session);
-//// });
-// //FIXME: that event is changed to TRACK_MUTE_CHANGED
-//// APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
-//// CallStats.sendMuteEvent(mute, "audio");
-//// });
-//// APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
-//// CallStats.sendSetupFailedEvent();
-//// });
-// //FIXME: that event is changed to TRACK_MUTE_CHANGED
-//// APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
-//// CallStats.sendMuteEvent(mute, "video");
-//// });
-// }
-//};
+//CALSTATS METHODS
+/**
+ * Initializes the callstats.io API.
+ * @param peerConnection {JingleSessionPC} the session object
+ * @param Settings {Settings} the settings instance. Declared in
+ * /modules/settings/Settings.js
+ */
+Statistics.prototype.startCallStats = function (session, settings) {
+ if(this.callStatsIntegrationEnabled) {
+ this.callstats = new CallStats(session, settings, this.options);
+ }
+}
+/**
+ * Returns true if the callstats integration is enabled, otherwise returns
+ * false.
+ *
+ * @returns true if the callstats integration is enabled, otherwise returns
+ * false.
+ */
+Statistics.prototype.isCallstatsEnabled = function () {
+ return this.callStatsIntegrationEnabled;
+}
+/**
+ * Notifies CallStats for connection setup errors
+ */
+Statistics.prototype.sendSetupFailedEvent = function () {
+ if(this.callStatsIntegrationEnabled && this.callstats)
+ this.callstats.sendSetupFailedEvent();
+}
-module.exports = Statistics;
+/**
+ * Notifies CallStats for mute events
+ * @param mute {boolean} true for muted and false for not muted
+ * @param type {String} "audio"/"video"
+ */
+Statistics.prototype.sendMuteEvent = function (muted, type) {
+ if(this.callStatsIntegrationEnabled && this.callstats)
+ this.callstats.sendMuteEvent(muted, type);
+}
-},{"../../service/statistics/Events":79,"../../service/statistics/constants":80,"./LocalStatsCollector.js":22,"./RTPStatsCollector.js":23,"events":43}],25:[function(require,module,exports){
/**
+ * Notifies CallStats that getUserMedia failed.
+ *
+ * @param {Error} e error to send
+ */
+Statistics.prototype.sendGetUserMediaFailed = function (e) {
+ if(this.callStatsIntegrationEnabled)
+ CallStats.sendGetUserMediaFailed(e, this.callstats);
+};
+
/**
- * @const
+ * Notifies CallStats that getUserMedia failed.
+ *
+ * @param {Error} e error to send
*/
-var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
+Statistics.sendGetUserMediaFailed = function (e) {
+ CallStats.sendGetUserMediaFailed(e, null);
+};
/**
- * Hexadecimal digits.
- * @const
+ * Notifies CallStats that peer connection failed to create offer.
+ *
+ * @param {Error} e error to send
+ * @param {RTCPeerConnection} pc connection on which failure occured.
*/
-var HEX_DIGITS = '0123456789abcdef';
+Statistics.prototype.sendCreateOfferFailed = function (e, pc) {
+ if(this.callStatsIntegrationEnabled)
+ CallStats.sendCreateOfferFailed(e, pc, this.callstats);
+};
/**
- * Generates random int within the range [min, max]
- * @param min the minimum value for the generated number
- * @param max the maximum value for the generated number
- * @returns random int number
+ * Notifies CallStats that peer connection failed to create answer.
+ *
+ * @param {Error} e error to send
+ * @param {RTCPeerConnection} pc connection on which failure occured.
*/
-function randomInt(min, max) {
- return Math.floor(Math.random() * (max - min + 1)) + min;
+Statistics.prototype.sendCreateAnswerFailed = function (e, pc) {
+ if(this.callStatsIntegrationEnabled)
+ CallStats.sendCreateAnswerFailed(e, pc, this.callstats);
+};
+
+/**
+ * Notifies CallStats that peer connection failed to set local description.
+ *
+ * @param {Error} e error to send
+ * @param {RTCPeerConnection} pc connection on which failure occured.
+ */
+Statistics.prototype.sendSetLocalDescFailed = function (e, pc) {
+ if(this.callStatsIntegrationEnabled)
+ CallStats.sendSetLocalDescFailed(e, pc, this.callstats);
}
/**
- * Get random element from array or string.
- * @param {Array|string} arr source
- * @returns array element or string character
+ * Notifies CallStats that peer connection failed to set remote description.
+ *
+ * @param {Error} e error to send
+ * @param {RTCPeerConnection} pc connection on which failure occured.
*/
-function randomElement(arr) {
- return arr[randomInt(0, arr.length - 1)];
+Statistics.prototype.sendSetRemoteDescFailed = function (e, pc) {
+ if(this.callStatsIntegrationEnabled)
+ CallStats.sendSetRemoteDescFailed(e, pc, this.callstats);
}
/**
- * Generate random alphanumeric string.
- * @param {number} length expected string length
- * @returns {string} random string of specified length
+ * Notifies CallStats that peer connection failed to add ICE candidate.
+ *
+ * @param {Error} e error to send
+ * @param {RTCPeerConnection} pc connection on which failure occured.
*/
-function randomAlphanumStr(length) {
- var result = '';
+Statistics.prototype.sendAddIceCandidateFailed = function (e, pc) {
+ if(this.callStatsIntegrationEnabled)
+ CallStats.sendAddIceCandidateFailed(e, pc, this.callstats);
+}
+
+/**
+ * Sends the given feedback through CallStats.
+ *
+ * @param overallFeedback an integer between 1 and 5 indicating the
+ * user feedback
+ * @param detailedFeedback detailed feedback from the user. Not yet used
+ */
+Statistics.prototype.sendFeedback =
+function(overallFeedback, detailedFeedback){
+ if(this.callStatsIntegrationEnabled && this.callstats)
+ this.callstats.sendFeedback(overallFeedback, detailedFeedback);
+}
+
+Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
+
+module.exports = Statistics;
+
+},{"../../service/statistics/Events":136,"../../service/statistics/constants":137,"./CallStats":22,"./LocalStatsCollector.js":23,"./RTPStatsCollector.js":24,"events":45}],26:[function(require,module,exports){
+/**
+/**
+ * @const
+ */
+var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
+
+/**
+ * Hexadecimal digits.
+ * @const
+ */
+var HEX_DIGITS = '0123456789abcdef';
+
+/**
+ * Generates random int within the range [min, max]
+ * @param min the minimum value for the generated number
+ * @param max the maximum value for the generated number
+ * @returns random int number
+ */
+function randomInt(min, max) {
+ return Math.floor(Math.random() * (max - min + 1)) + min;
+}
+
+/**
+ * Get random element from array or string.
+ * @param {Array|string} arr source
+ * @returns array element or string character
+ */
+function randomElement(arr) {
+ return arr[randomInt(0, arr.length - 1)];
+}
+
+/**
+ * Generate random alphanumeric string.
+ * @param {number} length expected string length
+ * @returns {string} random string of specified length
+ */
+function randomAlphanumStr(length) {
+ var result = '';
for (var i = 0; i < length; i += 1) {
result += randomElement(ALPHANUM);
@@ -6291,7 +6790,438 @@ var RandomUtil = {
module.exports = RandomUtil;
-},{}],26:[function(require,module,exports){
+},{}],27:[function(require,module,exports){
+var RandomUtil = require('./RandomUtil');
+
+/**
+ * from faker.js - Copyright (c) 2014-2015 Matthew Bergman & Marak Squires
+ * MIT License
+ * http://github.com/marak/faker.js/
+ *
+ * @const
+ */
+var names = [
+ "Aaliyah", "Aaron", "Abagail", "Abbey", "Abbie", "Abbigail",
+ "Abby", "Abdiel", "Abdul", "Abdullah", "Abe", "Abel", "Abelardo", "Abigail",
+ "Abigale", "Abigayle", "Abner", "Abraham", "Ada", "Adah", "Adalberto",
+ "Adaline", "Adam", "Adan", "Addie", "Addison", "Adela", "Adelbert", "Adele",
+ "Adelia", "Adeline", "Adell", "Adella", "Adelle", "Aditya", "Adolf", "Adolfo",
+ "Adolph", "Adolphus", "Adonis", "Adrain", "Adrian", "Adriana", "Adrianna",
+ "Adriel", "Adrien", "Adrienne", "Afton", "Aglae", "Agnes", "Agustin",
+ "Agustina", "Ahmad", "Ahmed", "Aida", "Aidan", "Aiden", "Aileen", "Aimee",
+ "Aisha", "Aiyana", "Akeem", "Al", "Alaina", "Alan", "Alana", "Alanis",
+ "Alanna", "Alayna", "Alba", "Albert", "Alberta", "Albertha", "Alberto",
+ "Albin", "Albina", "Alda", "Alden", "Alec", "Aleen", "Alejandra",
+ "Alejandrin", "Alek", "Alena", "Alene", "Alessandra", "Alessandro", "Alessia",
+ "Aletha", "Alex", "Alexa", "Alexander", "Alexandra", "Alexandre",
+ "Alexandrea", "Alexandria", "Alexandrine", "Alexandro", "Alexane", "Alexanne",
+ "Alexie", "Alexis", "Alexys", "Alexzander", "Alf", "Alfonso", "Alfonzo",
+ "Alford", "Alfred", "Alfreda", "Alfredo", "Ali", "Alia", "Alice", "Alicia",
+ "Alisa", "Alisha", "Alison", "Alivia", "Aliya", "Aliyah", "Aliza", "Alize",
+ "Allan", "Allen", "Allene", "Allie", "Allison", "Ally", "Alphonso", "Alta",
+ "Althea", "Alva", "Alvah", "Alvena", "Alvera", "Alverta", "Alvina", "Alvis",
+ "Alyce", "Alycia", "Alysa", "Alysha", "Alyson", "Alysson", "Amalia", "Amanda",
+ "Amani", "Amara", "Amari", "Amaya", "Amber", "Ambrose", "Amelia", "Amelie",
+ "Amely", "America", "Americo", "Amie", "Amina", "Amir", "Amira", "Amiya",
+ "Amos", "Amparo", "Amy", "Amya", "Ana", "Anabel", "Anabelle", "Anahi",
+ "Anais", "Anastacio", "Anastasia", "Anderson", "Andre", "Andreane",
+ "Andreanne", "Andres", "Andrew", "Andy", "Angel", "Angela", "Angelica",
+ "Angelina", "Angeline", "Angelita", "Angelo", "Angie", "Angus", "Anibal",
+ "Anika", "Anissa", "Anita", "Aniya", "Aniyah", "Anjali", "Anna", "Annabel",
+ "Annabell", "Annabelle", "Annalise", "Annamae", "Annamarie", "Anne",
+ "Annetta", "Annette", "Annie", "Ansel", "Ansley", "Anthony", "Antoinette",
+ "Antone", "Antonetta", "Antonette", "Antonia", "Antonietta", "Antonina",
+ "Antonio", "Antwan", "Antwon", "Anya", "April", "Ara", "Araceli", "Aracely",
+ "Arch", "Archibald", "Ardella", "Arden", "Ardith", "Arely", "Ari", "Ariane",
+ "Arianna", "Aric", "Ariel", "Arielle", "Arjun", "Arlene", "Arlie", "Arlo",
+ "Armand", "Armando", "Armani", "Arnaldo", "Arne", "Arno", "Arnold", "Arnoldo",
+ "Arnulfo", "Aron", "Art", "Arthur", "Arturo", "Arvel", "Arvid", "Arvilla",
+ "Aryanna", "Asa", "Asha", "Ashlee", "Ashleigh", "Ashley", "Ashly", "Ashlynn",
+ "Ashton", "Ashtyn", "Asia", "Assunta", "Astrid", "Athena", "Aubree", "Aubrey",
+ "Audie", "Audra", "Audreanne", "Audrey", "August", "Augusta", "Augustine",
+ "Augustus", "Aurelia", "Aurelie", "Aurelio", "Aurore", "Austen", "Austin",
+ "Austyn", "Autumn", "Ava", "Avery", "Avis", "Axel", "Ayana", "Ayden", "Ayla",
+ "Aylin", "Baby", "Bailee", "Bailey", "Barbara", "Barney", "Baron", "Barrett",
+ "Barry", "Bart", "Bartholome", "Barton", "Baylee", "Beatrice", "Beau",
+ "Beaulah", "Bell", "Bella", "Belle", "Ben", "Benedict", "Benjamin", "Bennett",
+ "Bennie", "Benny", "Benton", "Berenice", "Bernadette", "Bernadine", "Bernard",
+ "Bernardo", "Berneice", "Bernhard", "Bernice", "Bernie", "Berniece",
+ "Bernita", "Berry", "Bert", "Berta", "Bertha", "Bertram", "Bertrand", "Beryl",
+ "Bessie", "Beth", "Bethany", "Bethel", "Betsy", "Bette", "Bettie", "Betty",
+ "Bettye", "Beulah", "Beverly", "Bianka", "Bill", "Billie", "Billy", "Birdie",
+ "Blair", "Blaise", "Blake", "Blanca", "Blanche", "Blaze", "Bo", "Bobbie",
+ "Bobby", "Bonita", "Bonnie", "Boris", "Boyd", "Brad", "Braden", "Bradford",
+ "Bradley", "Bradly", "Brady", "Braeden", "Brain", "Brandi", "Brando",
+ "Brandon", "Brandt", "Brandy", "Brandyn", "Brannon", "Branson", "Brant",
+ "Braulio", "Braxton", "Brayan", "Breana", "Breanna", "Breanne", "Brenda",
+ "Brendan", "Brenden", "Brendon", "Brenna", "Brennan", "Brennon", "Brent",
+ "Bret", "Brett", "Bria", "Brian", "Briana", "Brianne", "Brice", "Bridget",
+ "Bridgette", "Bridie", "Brielle", "Brigitte", "Brionna", "Brisa", "Britney",
+ "Brittany", "Brock", "Broderick", "Brody", "Brook", "Brooke", "Brooklyn",
+ "Brooks", "Brown", "Bruce", "Bryana", "Bryce", "Brycen", "Bryon", "Buck",
+ "Bud", "Buddy", "Buford", "Bulah", "Burdette", "Burley", "Burnice", "Buster",
+ "Cade", "Caden", "Caesar", "Caitlyn", "Cale", "Caleb", "Caleigh", "Cali",
+ "Calista", "Callie", "Camden", "Cameron", "Camila", "Camilla", "Camille",
+ "Camren", "Camron", "Camryn", "Camylle", "Candace", "Candelario", "Candice",
+ "Candida", "Candido", "Cara", "Carey", "Carissa", "Carlee", "Carleton",
+ "Carley", "Carli", "Carlie", "Carlo", "Carlos", "Carlotta", "Carmel",
+ "Carmela", "Carmella", "Carmelo", "Carmen", "Carmine", "Carol", "Carolanne",
+ "Carole", "Carolina", "Caroline", "Carolyn", "Carolyne", "Carrie", "Carroll",
+ "Carson", "Carter", "Cary", "Casandra", "Casey", "Casimer", "Casimir",
+ "Casper", "Cassandra", "Cassandre", "Cassidy", "Cassie", "Catalina",
+ "Caterina", "Catharine", "Catherine", "Cathrine", "Cathryn", "Cathy", "Cayla",
+ "Ceasar", "Cecelia", "Cecil", "Cecile", "Cecilia", "Cedrick", "Celestine",
+ "Celestino", "Celia", "Celine", "Cesar", "Chad", "Chadd", "Chadrick", "Chaim",
+ "Chance", "Chandler", "Chanel", "Chanelle", "Charity", "Charlene", "Charles",
+ "Charley", "Charlie", "Charlotte", "Chase", "Chasity", "Chauncey", "Chaya",
+ "Chaz", "Chelsea", "Chelsey", "Chelsie", "Chesley", "Chester", "Chet",
+ "Cheyanne", "Cheyenne", "Chloe", "Chris", "Christ", "Christa", "Christelle",
+ "Christian", "Christiana", "Christina", "Christine", "Christop", "Christophe",
+ "Christopher", "Christy", "Chyna", "Ciara", "Cicero", "Cielo", "Cierra",
+ "Cindy", "Citlalli", "Clair", "Claire", "Clara", "Clarabelle", "Clare",
+ "Clarissa", "Clark", "Claud", "Claude", "Claudia", "Claudie", "Claudine",
+ "Clay", "Clemens", "Clement", "Clementina", "Clementine", "Clemmie", "Cleo",
+ "Cleora", "Cleta", "Cletus", "Cleve", "Cleveland", "Clifford", "Clifton",
+ "Clint", "Clinton", "Clotilde", "Clovis", "Cloyd", "Clyde", "Coby", "Cody",
+ "Colby", "Cole", "Coleman", "Colin", "Colleen", "Collin", "Colt", "Colten",
+ "Colton", "Columbus", "Concepcion", "Conner", "Connie", "Connor", "Conor",
+ "Conrad", "Constance", "Constantin", "Consuelo", "Cooper", "Cora", "Coralie",
+ "Corbin", "Cordelia", "Cordell", "Cordia", "Cordie", "Corene", "Corine",
+ "Cornelius", "Cornell", "Corrine", "Cortez", "Cortney", "Cory", "Coty",
+ "Courtney", "Coy", "Craig", "Crawford", "Creola", "Cristal", "Cristian",
+ "Cristina", "Cristobal", "Cristopher", "Cruz", "Crystal", "Crystel", "Cullen",
+ "Curt", "Curtis", "Cydney", "Cynthia", "Cyril", "Cyrus", "Dagmar", "Dahlia",
+ "Daija", "Daisha", "Daisy", "Dakota", "Dale", "Dallas", "Dallin", "Dalton",
+ "Damaris", "Dameon", "Damian", "Damien", "Damion", "Damon", "Dan", "Dana",
+ "Dandre", "Dane", "D'angelo", "Dangelo", "Danial", "Daniela", "Daniella",
+ "Danielle", "Danika", "Dannie", "Danny", "Dante", "Danyka", "Daphne",
+ "Daphnee", "Daphney", "Darby", "Daren", "Darian", "Dariana", "Darien",
+ "Dario", "Darion", "Darius", "Darlene", "Daron", "Darrel", "Darrell",
+ "Darren", "Darrick", "Darrin", "Darrion", "Darron", "Darryl", "Darwin",
+ "Daryl", "Dashawn", "Dasia", "Dave", "David", "Davin", "Davion", "Davon",
+ "Davonte", "Dawn", "Dawson", "Dax", "Dayana", "Dayna", "Dayne", "Dayton",
+ "Dean", "Deangelo", "Deanna", "Deborah", "Declan", "Dedric", "Dedrick", "Dee",
+ "Deion", "Deja", "Dejah", "Dejon", "Dejuan", "Delaney", "Delbert", "Delfina",
+ "Delia", "Delilah", "Dell", "Della", "Delmer", "Delores", "Delpha", "Delphia",
+ "Delphine", "Delta", "Demarco", "Demarcus", "Demario", "Demetris",
+ "Demetrius", "Demond", "Dena", "Denis", "Dennis", "Deon", "Deondre",
+ "Deontae", "Deonte", "Dereck", "Derek", "Derick", "Deron", "Derrick",
+ "Deshaun", "Deshawn", "Desiree", "Desmond", "Dessie", "Destany", "Destin",
+ "Destinee", "Destiney", "Destini", "Destiny", "Devan", "Devante", "Deven",
+ "Devin", "Devon", "Devonte", "Devyn", "Dewayne", "Dewitt", "Dexter",
+ "Diamond", "Diana", "Dianna", "Diego", "Dillan", "Dillon", "Dimitri", "Dina",
+ "Dino", "Dion", "Dixie", "Dock", "Dolly", "Dolores", "Domenic", "Domenica",
+ "Domenick", "Domenico", "Domingo", "Dominic", "Dominique", "Don", "Donald",
+ "Donato", "Donavon", "Donna", "Donnell", "Donnie", "Donny", "Dora", "Dorcas",
+ "Dorian", "Doris", "Dorothea", "Dorothy", "Dorris", "Dortha", "Dorthy",
+ "Doug", "Douglas", "Dovie", "Doyle", "Drake", "Drew", "Duane", "Dudley",
+ "Dulce", "Duncan", "Durward", "Dustin", "Dusty", "Dwight", "Dylan", "Earl",
+ "Earlene", "Earline", "Earnest", "Earnestine", "Easter", "Easton", "Ebba",
+ "Ebony", "Ed", "Eda", "Edd", "Eddie", "Eden", "Edgar", "Edgardo", "Edison",
+ "Edmond", "Edmund", "Edna", "Eduardo", "Edward", "Edwardo", "Edwin", "Edwina",
+ "Edyth", "Edythe", "Effie", "Efrain", "Efren", "Eileen", "Einar", "Eino",
+ "Eladio", "Elaina", "Elbert", "Elda", "Eldon", "Eldora", "Eldred", "Eldridge",
+ "Eleanora", "Eleanore", "Eleazar", "Electa", "Elena", "Elenor", "Elenora",
+ "Eleonore", "Elfrieda", "Eli", "Elian", "Eliane", "Elias", "Eliezer",
+ "Elijah", "Elinor", "Elinore", "Elisa", "Elisabeth", "Elise", "Eliseo",
+ "Elisha", "Elissa", "Eliza", "Elizabeth", "Ella", "Ellen", "Ellie", "Elliot",
+ "Elliott", "Ellis", "Ellsworth", "Elmer", "Elmira", "Elmo", "Elmore", "Elna",
+ "Elnora", "Elody", "Eloisa", "Eloise", "Elouise", "Eloy", "Elroy", "Elsa",
+ "Else", "Elsie", "Elta", "Elton", "Elva", "Elvera", "Elvie", "Elvis", "Elwin",
+ "Elwyn", "Elyse", "Elyssa", "Elza", "Emanuel", "Emelia", "Emelie", "Emely",
+ "Emerald", "Emerson", "Emery", "Emie", "Emil", "Emile", "Emilia", "Emiliano",
+ "Emilie", "Emilio", "Emily", "Emma", "Emmalee", "Emmanuel", "Emmanuelle",
+ "Emmet", "Emmett", "Emmie", "Emmitt", "Emmy", "Emory", "Ena", "Enid", "Enoch",
+ "Enola", "Enos", "Enrico", "Enrique", "Ephraim", "Era", "Eriberto", "Eric",
+ "Erica", "Erich", "Erick", "Ericka", "Erik", "Erika", "Erin", "Erling",
+ "Erna", "Ernest", "Ernestina", "Ernestine", "Ernesto", "Ernie", "Ervin",
+ "Erwin", "Eryn", "Esmeralda", "Esperanza", "Esta", "Esteban", "Estefania",
+ "Estel", "Estell", "Estella", "Estelle", "Estevan", "Esther", "Estrella",
+ "Etha", "Ethan", "Ethel", "Ethelyn", "Ethyl", "Ettie", "Eudora", "Eugene",
+ "Eugenia", "Eula", "Eulah", "Eulalia", "Euna", "Eunice", "Eusebio", "Eva",
+ "Evalyn", "Evan", "Evangeline", "Evans", "Eve", "Eveline", "Evelyn",
+ "Everardo", "Everett", "Everette", "Evert", "Evie", "Ewald", "Ewell",
+ "Ezekiel", "Ezequiel", "Ezra", "Fabian", "Fabiola", "Fae", "Fannie", "Fanny",
+ "Fatima", "Faustino", "Fausto", "Favian", "Fay", "Faye", "Federico",
+ "Felicia", "Felicita", "Felicity", "Felipa", "Felipe", "Felix", "Felton",
+ "Fermin", "Fern", "Fernando", "Ferne", "Fidel", "Filiberto", "Filomena",
+ "Finn", "Fiona", "Flavie", "Flavio", "Fleta", "Fletcher", "Flo", "Florence",
+ "Florencio", "Florian", "Florida", "Florine", "Flossie", "Floy", "Floyd",
+ "Ford", "Forest", "Forrest", "Foster", "Frances", "Francesca", "Francesco",
+ "Francis", "Francisca", "Francisco", "Franco", "Frank", "Frankie", "Franz",
+ "Fred", "Freda", "Freddie", "Freddy", "Frederic", "Frederick", "Frederik",
+ "Frederique", "Fredrick", "Fredy", "Freeda", "Freeman", "Freida", "Frida",
+ "Frieda", "Friedrich", "Fritz", "Furman", "Gabe", "Gabriel", "Gabriella",
+ "Gabrielle", "Gaetano", "Gage", "Gail", "Gardner", "Garett", "Garfield",
+ "Garland", "Garnet", "Garnett", "Garret", "Garrett", "Garrick", "Garrison",
+ "Garry", "Garth", "Gaston", "Gavin", "Gay", "Gayle", "Gaylord", "Gene",
+ "General", "Genesis", "Genevieve", "Gennaro", "Genoveva", "Geo", "Geoffrey",
+ "George", "Georgette", "Georgiana", "Georgianna", "Geovanni", "Geovanny",
+ "Geovany", "Gerald", "Geraldine", "Gerard", "Gerardo", "Gerda", "Gerhard",
+ "Germaine", "German", "Gerry", "Gerson", "Gertrude", "Gia", "Gianni",
+ "Gideon", "Gilbert", "Gilberto", "Gilda", "Giles", "Gillian", "Gina", "Gino",
+ "Giovani", "Giovanna", "Giovanni", "Giovanny", "Gisselle", "Giuseppe",
+ "Gladyce", "Gladys", "Glen", "Glenda", "Glenna", "Glennie", "Gloria",
+ "Godfrey", "Golda", "Golden", "Gonzalo", "Gordon", "Grace", "Gracie",
+ "Graciela", "Grady", "Graham", "Grant", "Granville", "Grayce", "Grayson",
+ "Green", "Greg", "Gregg", "Gregoria", "Gregorio", "Gregory", "Greta",
+ "Gretchen", "Greyson", "Griffin", "Grover", "Guadalupe", "Gudrun", "Guido",
+ "Guillermo", "Guiseppe", "Gunnar", "Gunner", "Gus", "Gussie", "Gust",
+ "Gustave", "Guy", "Gwen", "Gwendolyn", "Hadley", "Hailee", "Hailey", "Hailie",
+ "Hal", "Haleigh", "Haley", "Halie", "Halle", "Hallie", "Hank", "Hanna",
+ "Hannah", "Hans", "Hardy", "Harley", "Harmon", "Harmony", "Harold",
+ "Harrison", "Harry", "Harvey", "Haskell", "Hassan", "Hassie", "Hattie",
+ "Haven", "Hayden", "Haylee", "Hayley", "Haylie", "Hazel", "Hazle", "Heath",
+ "Heather", "Heaven", "Heber", "Hector", "Heidi", "Helen", "Helena", "Helene",
+ "Helga", "Hellen", "Helmer", "Heloise", "Henderson", "Henri", "Henriette",
+ "Henry", "Herbert", "Herman", "Hermann", "Hermina", "Herminia", "Herminio",
+ "Hershel", "Herta", "Hertha", "Hester", "Hettie", "Hilario", "Hilbert",
+ "Hilda", "Hildegard", "Hillard", "Hillary", "Hilma", "Hilton", "Hipolito",
+ "Hiram", "Hobart", "Holden", "Hollie", "Hollis", "Holly", "Hope", "Horace",
+ "Horacio", "Hortense", "Hosea", "Houston", "Howard", "Howell", "Hoyt",
+ "Hubert", "Hudson", "Hugh", "Hulda", "Humberto", "Hunter", "Hyman", "Ian",
+ "Ibrahim", "Icie", "Ida", "Idell", "Idella", "Ignacio", "Ignatius", "Ike",
+ "Ila", "Ilene", "Iliana", "Ima", "Imani", "Imelda", "Immanuel", "Imogene",
+ "Ines", "Irma", "Irving", "Irwin", "Isaac", "Isabel", "Isabell", "Isabella",
+ "Isabelle", "Isac", "Isadore", "Isai", "Isaiah", "Isaias", "Isidro", "Ismael",
+ "Isobel", "Isom", "Israel", "Issac", "Itzel", "Iva", "Ivah", "Ivory", "Ivy",
+ "Izabella", "Izaiah", "Jabari", "Jace", "Jacey", "Jacinthe", "Jacinto",
+ "Jack", "Jackeline", "Jackie", "Jacklyn", "Jackson", "Jacky", "Jaclyn",
+ "Jacquelyn", "Jacques", "Jacynthe", "Jada", "Jade", "Jaden", "Jadon", "Jadyn",
+ "Jaeden", "Jaida", "Jaiden", "Jailyn", "Jaime", "Jairo", "Jakayla", "Jake",
+ "Jakob", "Jaleel", "Jalen", "Jalon", "Jalyn", "Jamaal", "Jamal", "Jamar",
+ "Jamarcus", "Jamel", "Jameson", "Jamey", "Jamie", "Jamil", "Jamir", "Jamison",
+ "Jammie", "Jan", "Jana", "Janae", "Jane", "Janelle", "Janessa", "Janet",
+ "Janice", "Janick", "Janie", "Janis", "Janiya", "Jannie", "Jany", "Jaquan",
+ "Jaquelin", "Jaqueline", "Jared", "Jaren", "Jarod", "Jaron", "Jarred",
+ "Jarrell", "Jarret", "Jarrett", "Jarrod", "Jarvis", "Jasen", "Jasmin",
+ "Jason", "Jasper", "Jaunita", "Javier", "Javon", "Javonte", "Jay", "Jayce",
+ "Jaycee", "Jayda", "Jayde", "Jayden", "Jaydon", "Jaylan", "Jaylen", "Jaylin",
+ "Jaylon", "Jayme", "Jayne", "Jayson", "Jazlyn", "Jazmin", "Jazmyn", "Jazmyne",
+ "Jean", "Jeanette", "Jeanie", "Jeanne", "Jed", "Jedediah", "Jedidiah", "Jeff",
+ "Jefferey", "Jeffery", "Jeffrey", "Jeffry", "Jena", "Jenifer", "Jennie",
+ "Jennifer", "Jennings", "Jennyfer", "Jensen", "Jerad", "Jerald", "Jeramie",
+ "Jeramy", "Jerel", "Jeremie", "Jeremy", "Jermain", "Jermaine", "Jermey",
+ "Jerod", "Jerome", "Jeromy", "Jerrell", "Jerrod", "Jerrold", "Jerry", "Jess",
+ "Jesse", "Jessica", "Jessie", "Jessika", "Jessy", "Jessyca", "Jesus", "Jett",
+ "Jettie", "Jevon", "Jewel", "Jewell", "Jillian", "Jimmie", "Jimmy", "Jo",
+ "Joan", "Joana", "Joanie", "Joanne", "Joannie", "Joanny", "Joany", "Joaquin",
+ "Jocelyn", "Jodie", "Jody", "Joe", "Joel", "Joelle", "Joesph", "Joey",
+ "Johan", "Johann", "Johanna", "Johathan", "John", "Johnathan", "Johnathon",
+ "Johnnie", "Johnny", "Johnpaul", "Johnson", "Jolie", "Jon", "Jonas",
+ "Jonatan", "Jonathan", "Jonathon", "Jordan", "Jordane", "Jordi", "Jordon",
+ "Jordy", "Jordyn", "Jorge", "Jose", "Josefa", "Josefina", "Joseph",
+ "Josephine", "Josh", "Joshua", "Joshuah", "Josiah", "Josiane", "Josianne",
+ "Josie", "Josue", "Jovan", "Jovani", "Jovanny", "Jovany", "Joy", "Joyce",
+ "Juana", "Juanita", "Judah", "Judd", "Jude", "Judge", "Judson", "Judy",
+ "Jules", "Julia", "Julian", "Juliana", "Julianne", "Julie", "Julien",
+ "Juliet", "Julio", "Julius", "June", "Junior", "Junius", "Justen", "Justice",
+ "Justina", "Justine", "Juston", "Justus", "Justyn", "Juvenal", "Juwan",
+ "Kacey", "Kaci", "Kacie", "Kade", "Kaden", "Kadin", "Kaela", "Kaelyn", "Kaia",
+ "Kailee", "Kailey", "Kailyn", "Kaitlin", "Kaitlyn", "Kale", "Kaleb",
+ "Kaleigh", "Kaley", "Kali", "Kallie", "Kameron", "Kamille", "Kamren",
+ "Kamron", "Kamryn", "Kane", "Kara", "Kareem", "Karelle", "Karen", "Kari",
+ "Kariane", "Karianne", "Karina", "Karine", "Karl", "Karlee", "Karley",
+ "Karli", "Karlie", "Karolann", "Karson", "Kasandra", "Kasey", "Kassandra",
+ "Katarina", "Katelin", "Katelyn", "Katelynn", "Katharina", "Katherine",
+ "Katheryn", "Kathleen", "Kathlyn", "Kathryn", "Kathryne", "Katlyn", "Katlynn",
+ "Katrina", "Katrine", "Kattie", "Kavon", "Kay", "Kaya", "Kaycee", "Kayden",
+ "Kayla", "Kaylah", "Kaylee", "Kayleigh", "Kayley", "Kayli", "Kaylie",
+ "Kaylin", "Keagan", "Keanu", "Keara", "Keaton", "Keegan", "Keeley", "Keely",
+ "Keenan", "Keira", "Keith", "Kellen", "Kelley", "Kelli", "Kellie", "Kelly",
+ "Kelsi", "Kelsie", "Kelton", "Kelvin", "Ken", "Kendall", "Kendra", "Kendrick",
+ "Kenna", "Kennedi", "Kennedy", "Kenneth", "Kennith", "Kenny", "Kenton",
+ "Kenya", "Kenyatta", "Kenyon", "Keon", "Keshaun", "Keshawn", "Keven", "Kevin",
+ "Kevon", "Keyon", "Keyshawn", "Khalid", "Khalil", "Kian", "Kiana", "Kianna",
+ "Kiara", "Kiarra", "Kiel", "Kiera", "Kieran", "Kiley", "Kim", "Kimberly",
+ "King", "Kip", "Kira", "Kirk", "Kirsten", "Kirstin", "Kitty", "Kobe", "Koby",
+ "Kody", "Kolby", "Kole", "Korbin", "Korey", "Kory", "Kraig", "Kris", "Krista",
+ "Kristian", "Kristin", "Kristina", "Kristofer", "Kristoffer", "Kristopher",
+ "Kristy", "Krystal", "Krystel", "Krystina", "Kurt", "Kurtis", "Kyla", "Kyle",
+ "Kylee", "Kyleigh", "Kyler", "Kylie", "Kyra", "Lacey", "Lacy", "Ladarius",
+ "Lafayette", "Laila", "Laisha", "Lamar", "Lambert", "Lamont", "Lance",
+ "Landen", "Lane", "Laney", "Larissa", "Laron", "Larry", "Larue", "Laura",
+ "Laurel", "Lauren", "Laurence", "Lauretta", "Lauriane", "Laurianne", "Laurie",
+ "Laurine", "Laury", "Lauryn", "Lavada", "Lavern", "Laverna", "Laverne",
+ "Lavina", "Lavinia", "Lavon", "Lavonne", "Lawrence", "Lawson", "Layla",
+ "Layne", "Lazaro", "Lea", "Leann", "Leanna", "Leanne", "Leatha", "Leda",
+ "Lee", "Leif", "Leila", "Leilani", "Lela", "Lelah", "Leland", "Lelia",
+ "Lempi", "Lemuel", "Lenna", "Lennie", "Lenny", "Lenora", "Lenore", "Leo",
+ "Leola", "Leon", "Leonard", "Leonardo", "Leone", "Leonel", "Leonie", "Leonor",
+ "Leonora", "Leopold", "Leopoldo", "Leora", "Lera", "Lesley", "Leslie",
+ "Lesly", "Lessie", "Lester", "Leta", "Letha", "Letitia", "Levi", "Lew",
+ "Lewis", "Lexi", "Lexie", "Lexus", "Lia", "Liam", "Liana", "Libbie", "Libby",
+ "Lila", "Lilian", "Liliana", "Liliane", "Lilla", "Lillian", "Lilliana",
+ "Lillie", "Lilly", "Lily", "Lilyan", "Lina", "Lincoln", "Linda", "Lindsay",
+ "Lindsey", "Linnea", "Linnie", "Linwood", "Lionel", "Lisa", "Lisandro",
+ "Lisette", "Litzy", "Liza", "Lizeth", "Lizzie", "Llewellyn", "Lloyd", "Logan",
+ "Lois", "Lola", "Lolita", "Loma", "Lon", "London", "Lonie", "Lonnie", "Lonny",
+ "Lonzo", "Lora", "Loraine", "Loren", "Lorena", "Lorenz", "Lorenza", "Lorenzo",
+ "Lori", "Lorine", "Lorna", "Lottie", "Lou", "Louie", "Louisa", "Lourdes",
+ "Louvenia", "Lowell", "Loy", "Loyal", "Loyce", "Lucas", "Luciano", "Lucie",
+ "Lucienne", "Lucile", "Lucinda", "Lucio", "Lucious", "Lucius", "Lucy",
+ "Ludie", "Ludwig", "Lue", "Luella", "Luigi", "Luis", "Luisa", "Lukas", "Lula",
+ "Lulu", "Luna", "Lupe", "Lura", "Lurline", "Luther", "Luz", "Lyda", "Lydia",
+ "Lyla", "Lynn", "Lyric", "Lysanne", "Mabel", "Mabelle", "Mable", "Mac",
+ "Macey", "Maci", "Macie", "Mack", "Mackenzie", "Macy", "Madaline", "Madalyn",
+ "Maddison", "Madeline", "Madelyn", "Madelynn", "Madge", "Madie", "Madilyn",
+ "Madisen", "Madison", "Madisyn", "Madonna", "Madyson", "Mae", "Maegan",
+ "Maeve", "Mafalda", "Magali", "Magdalen", "Magdalena", "Maggie", "Magnolia",
+ "Magnus", "Maia", "Maida", "Maiya", "Major", "Makayla", "Makenna", "Makenzie",
+ "Malachi", "Malcolm", "Malika", "Malinda", "Mallie", "Mallory", "Malvina",
+ "Mandy", "Manley", "Manuel", "Manuela", "Mara", "Marc", "Marcel", "Marcelina",
+ "Marcelino", "Marcella", "Marcelle", "Marcellus", "Marcelo", "Marcia",
+ "Marco", "Marcos", "Marcus", "Margaret", "Margarete", "Margarett",
+ "Margaretta", "Margarette", "Margarita", "Marge", "Margie", "Margot",
+ "Margret", "Marguerite", "Maria", "Mariah", "Mariam", "Marian", "Mariana",
+ "Mariane", "Marianna", "Marianne", "Mariano", "Maribel", "Marie", "Mariela",
+ "Marielle", "Marietta", "Marilie", "Marilou", "Marilyne", "Marina", "Mario",
+ "Marion", "Marisa", "Marisol", "Maritza", "Marjolaine", "Marjorie", "Marjory",
+ "Mark", "Markus", "Marlee", "Marlen", "Marlene", "Marley", "Marlin", "Marlon",
+ "Marques", "Marquis", "Marquise", "Marshall", "Marta", "Martin", "Martina",
+ "Martine", "Marty", "Marvin", "Mary", "Maryam", "Maryjane", "Maryse", "Mason",
+ "Mateo", "Mathew", "Mathias", "Mathilde", "Matilda", "Matilde", "Matt",
+ "Matteo", "Mattie", "Maud", "Maude", "Maudie", "Maureen", "Maurice",
+ "Mauricio", "Maurine", "Maverick", "Mavis", "Max", "Maxie", "Maxime",
+ "Maximilian", "Maximillia", "Maximillian", "Maximo", "Maximus", "Maxine",
+ "Maxwell", "May", "Maya", "Maybell", "Maybelle", "Maye", "Maymie", "Maynard",
+ "Mayra", "Mazie", "Mckayla", "Mckenna", "Mckenzie", "Meagan", "Meaghan",
+ "Meda", "Megane", "Meggie", "Meghan", "Mekhi", "Melany", "Melba", "Melisa",
+ "Melissa", "Mellie", "Melody", "Melvin", "Melvina", "Melyna", "Melyssa",
+ "Mercedes", "Meredith", "Merl", "Merle", "Merlin", "Merritt", "Mertie",
+ "Mervin", "Meta", "Mia", "Micaela", "Micah", "Michael", "Michaela", "Michale",
+ "Micheal", "Michel", "Michele", "Michelle", "Miguel", "Mikayla", "Mike",
+ "Mikel", "Milan", "Miles", "Milford", "Miller", "Millie", "Milo", "Milton",
+ "Mina", "Minerva", "Minnie", "Miracle", "Mireille", "Mireya", "Misael",
+ "Missouri", "Misty", "Mitchel", "Mitchell", "Mittie", "Modesta", "Modesto",
+ "Mohamed", "Mohammad", "Mohammed", "Moises", "Mollie", "Molly", "Mona",
+ "Monica", "Monique", "Monroe", "Monserrat", "Monserrate", "Montana", "Monte",
+ "Monty", "Morgan", "Moriah", "Morris", "Mortimer", "Morton", "Mose", "Moses",
+ "Moshe", "Mossie", "Mozell", "Mozelle", "Muhammad", "Muriel", "Murl",
+ "Murphy", "Murray", "Mustafa", "Mya", "Myah", "Mylene", "Myles", "Myra",
+ "Myriam", "Myrl", "Myrna", "Myron", "Myrtice", "Myrtie", "Myrtis", "Myrtle",
+ "Nadia", "Nakia", "Name", "Nannie", "Naomi", "Naomie", "Napoleon", "Narciso",
+ "Nash", "Nasir", "Nat", "Natalia", "Natalie", "Natasha", "Nathan",
+ "Nathanael", "Nathanial", "Nathaniel", "Nathen", "Nayeli", "Neal", "Ned",
+ "Nedra", "Neha", "Neil", "Nelda", "Nella", "Nelle", "Nellie", "Nels",
+ "Nelson", "Neoma", "Nestor", "Nettie", "Neva", "Newell", "Newton", "Nia",
+ "Nicholas", "Nicholaus", "Nichole", "Nick", "Nicklaus", "Nickolas", "Nico",
+ "Nicola", "Nicolas", "Nicole", "Nicolette", "Nigel", "Nikita", "Nikki",
+ "Nikko", "Niko", "Nikolas", "Nils", "Nina", "Noah", "Noble", "Noe", "Noel",
+ "Noelia", "Noemi", "Noemie", "Noemy", "Nola", "Nolan", "Nona", "Nora",
+ "Norbert", "Norberto", "Norene", "Norma", "Norris", "Norval", "Norwood",
+ "Nova", "Novella", "Nya", "Nyah", "Nyasia", "Obie", "Oceane", "Ocie",
+ "Octavia", "Oda", "Odell", "Odessa", "Odie", "Ofelia", "Okey", "Ola", "Olaf",
+ "Ole", "Olen", "Oleta", "Olga", "Olin", "Oliver", "Ollie", "Oma", "Omari",
+ "Omer", "Ona", "Onie", "Opal", "Ophelia", "Ora", "Oral", "Oran", "Oren",
+ "Orie", "Orin", "Orion", "Orland", "Orlando", "Orlo", "Orpha", "Orrin",
+ "Orval", "Orville", "Osbaldo", "Osborne", "Oscar", "Osvaldo", "Oswald",
+ "Oswaldo", "Otha", "Otho", "Otilia", "Otis", "Ottilie", "Ottis", "Otto",
+ "Ova", "Owen", "Ozella", "Pablo", "Paige", "Palma", "Pamela", "Pansy",
+ "Paolo", "Paris", "Parker", "Pascale", "Pasquale", "Pat", "Patience",
+ "Patricia", "Patrick", "Patsy", "Pattie", "Paul", "Paula", "Pauline",
+ "Paxton", "Payton", "Pearl", "Pearlie", "Pearline", "Pedro", "Peggie",
+ "Penelope", "Percival", "Percy", "Perry", "Pete", "Peter", "Petra", "Peyton",
+ "Philip", "Phoebe", "Phyllis", "Pierce", "Pierre", "Pietro", "Pink", "Pinkie",
+ "Piper", "Polly", "Porter", "Precious", "Presley", "Preston", "Price",
+ "Prince", "Princess", "Priscilla", "Providenci", "Prudence", "Queen",
+ "Queenie", "Quentin", "Quincy", "Quinn", "Quinten", "Quinton", "Rachael",
+ "Rachel", "Rachelle", "Rae", "Raegan", "Rafael", "Rafaela", "Raheem",
+ "Rahsaan", "Rahul", "Raina", "Raleigh", "Ralph", "Ramiro", "Ramon", "Ramona",
+ "Randal", "Randall", "Randi", "Randy", "Ransom", "Raoul", "Raphael",
+ "Raphaelle", "Raquel", "Rashad", "Rashawn", "Rasheed", "Raul", "Raven", "Ray",
+ "Raymond", "Raymundo", "Reagan", "Reanna", "Reba", "Rebeca", "Rebecca",
+ "Rebeka", "Rebekah", "Reece", "Reed", "Reese", "Regan", "Reggie", "Reginald",
+ "Reid", "Reilly", "Reina", "Reinhold", "Remington", "Rene", "Renee", "Ressie",
+ "Reta", "Retha", "Retta", "Reuben", "Reva", "Rex", "Rey", "Reyes", "Reymundo",
+ "Reyna", "Reynold", "Rhea", "Rhett", "Rhianna", "Rhiannon", "Rhoda",
+ "Ricardo", "Richard", "Richie", "Richmond", "Rick", "Rickey", "Rickie",
+ "Ricky", "Rico", "Rigoberto", "Riley", "Rita", "River", "Robb", "Robbie",
+ "Robert", "Roberta", "Roberto", "Robin", "Robyn", "Rocio", "Rocky", "Rod",
+ "Roderick", "Rodger", "Rodolfo", "Rodrick", "Rodrigo", "Roel", "Rogelio",
+ "Roger", "Rogers", "Rolando", "Rollin", "Roma", "Romaine", "Roman", "Ron",
+ "Ronaldo", "Ronny", "Roosevelt", "Rory", "Rosa", "Rosalee", "Rosalia",
+ "Rosalind", "Rosalinda", "Rosalyn", "Rosamond", "Rosanna", "Rosario",
+ "Roscoe", "Rose", "Rosella", "Roselyn", "Rosemarie", "Rosemary", "Rosendo",
+ "Rosetta", "Rosie", "Rosina", "Roslyn", "Ross", "Rossie", "Rowan", "Rowena",
+ "Rowland", "Roxane", "Roxanne", "Roy", "Royal", "Royce", "Rozella", "Ruben",
+ "Rubie", "Ruby", "Rubye", "Rudolph", "Rudy", "Rupert", "Russ", "Russel",
+ "Russell", "Rusty", "Ruth", "Ruthe", "Ruthie", "Ryan", "Ryann", "Ryder",
+ "Rylan", "Rylee", "Ryleigh", "Ryley", "Sabina", "Sabrina", "Sabryna", "Sadie",
+ "Sadye", "Sage", "Saige", "Sallie", "Sally", "Salma", "Salvador", "Salvatore",
+ "Sam", "Samanta", "Samantha", "Samara", "Samir", "Sammie", "Sammy", "Samson",
+ "Sandra", "Sandrine", "Sandy", "Sanford", "Santa", "Santiago", "Santina",
+ "Santino", "Santos", "Sarah", "Sarai", "Sarina", "Sasha", "Saul", "Savanah",
+ "Savanna", "Savannah", "Savion", "Scarlett", "Schuyler", "Scot", "Scottie",
+ "Scotty", "Seamus", "Sean", "Sebastian", "Sedrick", "Selena", "Selina",
+ "Selmer", "Serena", "Serenity", "Seth", "Shad", "Shaina", "Shakira", "Shana",
+ "Shane", "Shanel", "Shanelle", "Shania", "Shanie", "Shaniya", "Shanna",
+ "Shannon", "Shanny", "Shanon", "Shany", "Sharon", "Shaun", "Shawn", "Shawna",
+ "Shaylee", "Shayna", "Shayne", "Shea", "Sheila", "Sheldon", "Shemar",
+ "Sheridan", "Sherman", "Sherwood", "Shirley", "Shyann", "Shyanne", "Sibyl",
+ "Sid", "Sidney", "Sienna", "Sierra", "Sigmund", "Sigrid", "Sigurd", "Silas",
+ "Sim", "Simeon", "Simone", "Sincere", "Sister", "Skye", "Skyla", "Skylar",
+ "Sofia", "Soledad", "Solon", "Sonia", "Sonny", "Sonya", "Sophia", "Sophie",
+ "Spencer", "Stacey", "Stacy", "Stan", "Stanford", "Stanley", "Stanton",
+ "Stefan", "Stefanie", "Stella", "Stephan", "Stephania", "Stephanie",
+ "Stephany", "Stephen", "Stephon", "Sterling", "Steve", "Stevie", "Stewart",
+ "Stone", "Stuart", "Summer", "Sunny", "Susan", "Susana", "Susanna", "Susie",
+ "Suzanne", "Sven", "Syble", "Sydnee", "Sydney", "Sydni", "Sydnie", "Sylvan",
+ "Sylvester", "Sylvia", "Tabitha", "Tad", "Talia", "Talon", "Tamara", "Tamia",
+ "Tania", "Tanner", "Tanya", "Tara", "Taryn", "Tate", "Tatum", "Tatyana",
+ "Taurean", "Tavares", "Taya", "Taylor", "Teagan", "Ted", "Telly", "Terence",
+ "Teresa", "Terrance", "Terrell", "Terrence", "Terrill", "Terry", "Tess",
+ "Tessie", "Tevin", "Thad", "Thaddeus", "Thalia", "Thea", "Thelma", "Theo",
+ "Theodora", "Theodore", "Theresa", "Therese", "Theresia", "Theron", "Thomas",
+ "Thora", "Thurman", "Tia", "Tiana", "Tianna", "Tiara", "Tierra", "Tiffany",
+ "Tillman", "Timmothy", "Timmy", "Timothy", "Tina", "Tito", "Titus", "Tobin",
+ "Toby", "Tod", "Tom", "Tomas", "Tomasa", "Tommie", "Toney", "Toni", "Tony",
+ "Torey", "Torrance", "Torrey", "Toy", "Trace", "Tracey", "Tracy", "Travis",
+ "Travon", "Tre", "Tremaine", "Tremayne", "Trent", "Trenton", "Tressa",
+ "Tressie", "Treva", "Trever", "Trevion", "Trevor", "Trey", "Trinity",
+ "Trisha", "Tristian", "Tristin", "Triston", "Troy", "Trudie", "Trycia",
+ "Trystan", "Turner", "Twila", "Tyler", "Tyra", "Tyree", "Tyreek", "Tyrel",
+ "Tyrell", "Tyrese", "Tyrique", "Tyshawn", "Tyson", "Ubaldo", "Ulices",
+ "Ulises", "Una", "Unique", "Urban", "Uriah", "Uriel", "Ursula", "Vada",
+ "Valentin", "Valentina", "Valentine", "Valerie", "Vallie", "Van", "Vance",
+ "Vanessa", "Vaughn", "Veda", "Velda", "Vella", "Velma", "Velva", "Vena",
+ "Verda", "Verdie", "Vergie", "Verla", "Verlie", "Vern", "Verna", "Verner",
+ "Vernice", "Vernie", "Vernon", "Verona", "Veronica", "Vesta", "Vicenta",
+ "Vicente", "Vickie", "Vicky", "Victor", "Victoria", "Vida", "Vidal", "Vilma",
+ "Vince", "Vincent", "Vincenza", "Vincenzo", "Vinnie", "Viola", "Violet",
+ "Violette", "Virgie", "Virgil", "Virginia", "Virginie", "Vita", "Vito",
+ "Viva", "Vivian", "Viviane", "Vivianne", "Vivien", "Vivienne", "Vladimir",
+ "Wade", "Waino", "Waldo", "Walker", "Wallace", "Walter", "Walton", "Wanda",
+ "Ward", "Warren", "Watson", "Wava", "Waylon", "Wayne", "Webster", "Weldon",
+ "Wellington", "Wendell", "Wendy", "Werner", "Westley", "Weston", "Whitney",
+ "Wilber", "Wilbert", "Wilburn", "Wiley", "Wilford", "Wilfred", "Wilfredo",
+ "Wilfrid", "Wilhelm", "Wilhelmine", "Will", "Willa", "Willard", "William",
+ "Willie", "Willis", "Willow", "Willy", "Wilma", "Wilmer", "Wilson", "Wilton",
+ "Winfield", "Winifred", "Winnifred", "Winona", "Winston", "Woodrow", "Wyatt",
+ "Wyman", "Xander", "Xavier", "Xzavier", "Yadira", "Yasmeen", "Yasmin",
+ "Yasmine", "Yazmin", "Yesenia", "Yessenia", "Yolanda", "Yoshiko", "Yvette",
+ "Yvonne", "Zachariah", "Zachary", "Zachery", "Zack", "Zackary", "Zackery",
+ "Zakary", "Zander", "Zane", "Zaria", "Zechariah", "Zelda", "Zella", "Zelma",
+ "Zena", "Zetta", "Zion", "Zita", "Zoe", "Zoey", "Zoie", "Zoila", "Zola",
+ "Zora", "Zula"
+];
+
+/**
+ * Generate random username.
+ * @returns {string} random username
+ */
+function generateUsername () {
+ var name = RandomUtil.randomElement(names);
+ var suffix = RandomUtil.randomAlphanumStr(3);
+
+ return name + '-' + suffix;
+}
+
+module.exports = {
+ generateUsername: generateUsername
+};
+
+},{"./RandomUtil":26}],28:[function(require,module,exports){
(function (__filename){
/* global Strophe, $, $pres, $iq, $msg */
/* jshint -W101,-W069 */
@@ -6354,7 +7284,7 @@ function filterNodeFromPresenceJSON(pres, nodeName){
return res;
}
-function ChatRoom(connection, jid, password, XMPP, options) {
+function ChatRoom(connection, jid, password, XMPP, options, settings) {
this.eventEmitter = new EventEmitter();
this.xmpp = XMPP;
this.connection = connection;
@@ -6370,7 +7300,8 @@ function ChatRoom(connection, jid, password, XMPP, options) {
this.focusMucJid = null;
this.bridgeIsDown = false;
this.options = options || {};
- this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter);
+ this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter,
+ settings);
this.initPresenceMap();
this.session = null;
var self = this;
@@ -7103,7 +8034,7 @@ ChatRoom.prototype.onMute = function (iq) {
module.exports = ChatRoom;
}).call(this,"/modules/xmpp/ChatRoom.js")
-},{"../../service/xmpp/XMPPEvents":81,"./moderator":33,"./recording":34,"events":43,"jitsi-meet-logger":47}],27:[function(require,module,exports){
+},{"../../service/xmpp/XMPPEvents":138,"./moderator":35,"./recording":36,"events":45,"jitsi-meet-logger":49}],29:[function(require,module,exports){
(function (__filename){
/*
* JingleSession provides an API to manage a single Jingle session. We will
@@ -7239,7 +8170,7 @@ JingleSession.prototype.setAnswer = function(jingle) {};
module.exports = JingleSession;
}).call(this,"/modules/xmpp/JingleSession.js")
-},{"jitsi-meet-logger":47}],28:[function(require,module,exports){
+},{"jitsi-meet-logger":49}],30:[function(require,module,exports){
(function (__filename){
/* jshint -W117 */
@@ -8902,7 +9833,7 @@ JingleSessionPC.prototype.getIceConnectionState = function () {
module.exports = JingleSessionPC;
}).call(this,"/modules/xmpp/JingleSessionPC.js")
-},{"../../service/xmpp/XMPPEvents":81,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":27,"./SDP":29,"./SDPDiffer":30,"./SDPUtil":31,"./TraceablePeerConnection":32,"async":42,"jitsi-meet-logger":47,"sdp-transform":71}],29:[function(require,module,exports){
+},{"../../service/xmpp/XMPPEvents":138,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":29,"./SDP":31,"./SDPDiffer":32,"./SDPUtil":33,"./TraceablePeerConnection":34,"async":44,"jitsi-meet-logger":49,"sdp-transform":78}],31:[function(require,module,exports){
(function (__filename){
/* jshint -W117 */
@@ -9553,7 +10484,7 @@ SDP.prototype.jingle2media = function (content) {
module.exports = SDP;
}).call(this,"/modules/xmpp/SDP.js")
-},{"./SDPUtil":31,"jitsi-meet-logger":47}],30:[function(require,module,exports){
+},{"./SDPUtil":33,"jitsi-meet-logger":49}],32:[function(require,module,exports){
var SDPUtil = require("./SDPUtil");
function SDPDiffer(mySDP, otherSDP)
@@ -9722,7 +10653,7 @@ SDPDiffer.prototype.toJingle = function(modify) {
};
module.exports = SDPDiffer;
-},{"./SDPUtil":31}],31:[function(require,module,exports){
+},{"./SDPUtil":33}],33:[function(require,module,exports){
(function (__filename){
var logger = require("jitsi-meet-logger").getLogger(__filename);
var RTCBrowserType = require("../RTC/RTCBrowserType");
@@ -10090,7 +11021,7 @@ SDPUtil = {
module.exports = SDPUtil;
}).call(this,"/modules/xmpp/SDPUtil.js")
-},{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":47}],32:[function(require,module,exports){
+},{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":49}],34:[function(require,module,exports){
(function (__filename){
/* global $ */
var RTC = require('../RTC/RTC');
@@ -10117,7 +11048,9 @@ function TraceablePeerConnection(ice_config, constraints, session) {
var Interop = require('sdp-interop').Interop;
this.interop = new Interop();
var Simulcast = require('sdp-simulcast');
- this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
+ this.simulcast = new Simulcast({numOfLayers: 3,
+ explodeRemoteSimulcast: false});
+ this.eventEmitter = this.session.room.eventEmitter;
// override as desired
this.trace = function (what, info) {
@@ -10418,7 +11351,8 @@ TraceablePeerConnection.prototype.setLocalDescription
// if we're running on FF, transform to Plan A first.
if (RTCBrowserType.usesUnifiedPlan()) {
description = this.interop.toUnifiedPlan(description);
- this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
+ this.trace('setLocalDescription::postTransform (Plan A)',
+ dumpSDP(description));
}
var self = this;
@@ -10429,14 +11363,11 @@ TraceablePeerConnection.prototype.setLocalDescription
},
function (err) {
self.trace('setLocalDescriptionOnFailure', err);
+ self.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_FAILED,
+ err, self.peerconnection);
failureCallback(err);
}
);
- /*
- if (this.statsinterval === null && this.maxstats > 0) {
- // start gathering stats
- }
- */
};
TraceablePeerConnection.prototype.setRemoteDescription
@@ -10464,6 +11395,8 @@ TraceablePeerConnection.prototype.setRemoteDescription
},
function (err) {
self.trace('setRemoteDescriptionOnFailure', err);
+ self.eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_FAILED,
+ err, self.peerconnection);
failureCallback(err);
}
);
@@ -10505,14 +11438,18 @@ TraceablePeerConnection.prototype.createOffer
self.trace('createOfferOnSuccess::mungeLocalVideoSSRC', dumpSDP(offer));
}
- if (!self.session.room.options.disableSimulcast && self.simulcast.isSupported()) {
+ if (!self.session.room.options.disableSimulcast
+ && self.simulcast.isSupported()) {
offer = self.simulcast.mungeLocalDescription(offer);
- self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
+ self.trace('createOfferOnSuccess::postTransform (simulcast)',
+ dumpSDP(offer));
}
successCallback(offer);
},
function(err) {
self.trace('createOfferOnFailure', err);
+ self.eventEmitter.emit(XMPPEvents.CREATE_OFFER_FAILED, err,
+ self.peerconnection);
failureCallback(err);
},
constraints
@@ -10529,7 +11466,8 @@ TraceablePeerConnection.prototype.createAnswer
// if we're running on FF, transform to Plan A first.
if (RTCBrowserType.usesUnifiedPlan()) {
answer = self.interop.toPlanB(answer);
- self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
+ self.trace('createAnswerOnSuccess::postTransform (Plan B)',
+ dumpSDP(answer));
}
if (RTCBrowserType.isChrome())
@@ -10538,14 +11476,18 @@ TraceablePeerConnection.prototype.createAnswer
self.trace('createAnswerOnSuccess::mungeLocalVideoSSRC', dumpSDP(answer));
}
- if (!self.session.room.options.disableSimulcast && self.simulcast.isSupported()) {
+ if (!self.session.room.options.disableSimulcast
+ && self.simulcast.isSupported()) {
answer = self.simulcast.mungeLocalDescription(answer);
- self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
+ self.trace('createAnswerOnSuccess::postTransform (simulcast)',
+ dumpSDP(answer));
}
successCallback(answer);
},
function(err) {
self.trace('createAnswerOnFailure', err);
+ self.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_FAILED, err,
+ self.peerconnection);
failureCallback(err);
},
constraints
@@ -10586,13 +11528,12 @@ TraceablePeerConnection.prototype.getStats = function(callback, errback) {
module.exports = TraceablePeerConnection;
}).call(this,"/modules/xmpp/TraceablePeerConnection.js")
-},{"../../service/xmpp/XMPPEvents":81,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"../util/RandomUtil":25,"jitsi-meet-logger":47,"sdp-interop":65,"sdp-simulcast":68,"sdp-transform":71}],33:[function(require,module,exports){
+},{"../../service/xmpp/XMPPEvents":138,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"../util/RandomUtil":26,"jitsi-meet-logger":49,"sdp-interop":68,"sdp-simulcast":75,"sdp-transform":78}],35:[function(require,module,exports){
(function (__filename){
/* global $, $iq, Promise, Strophe */
var logger = require("jitsi-meet-logger").getLogger(__filename);
var XMPPEvents = require("../../service/xmpp/XMPPEvents");
-var Settings = require("../settings/Settings");
var AuthenticationEvents
= require("../../service/authentication/AuthenticationEvents");
@@ -10612,18 +11553,14 @@ function createExpBackoffTimer(step) {
};
}
-
-
-
-
-function Moderator(roomName, xmpp, emitter) {
+function Moderator(roomName, xmpp, emitter, settings) {
this.roomName = roomName;
this.xmppService = xmpp;
this.getNextTimeout = createExpBackoffTimer(1000);
this.getNextErrorTimeout = createExpBackoffTimer(1000);
// External authentication stuff
this.externalAuthEnabled = false;
- this.settings = new Settings(roomName);
+ this.settings = settings;
// Sip gateway can be enabled by configuring Jigasi host in config.js or
// it will be enabled automatically if focus detects the component through
// service discovery.
@@ -11047,7 +11984,7 @@ Moderator.prototype.logout = function (callback) {
module.exports = Moderator;
}).call(this,"/modules/xmpp/moderator.js")
-},{"../../service/authentication/AuthenticationEvents":77,"../../service/xmpp/XMPPEvents":81,"../settings/Settings":21,"jitsi-meet-logger":47}],34:[function(require,module,exports){
+},{"../../service/authentication/AuthenticationEvents":134,"../../service/xmpp/XMPPEvents":138,"jitsi-meet-logger":49}],36:[function(require,module,exports){
(function (__filename){
/* global $, $iq, config, connection, focusMucJid, messageHandler,
Toolbar, Util, Promise */
@@ -11274,7 +12211,7 @@ Recording.prototype.getURL = function () {
module.exports = Recording;
}).call(this,"/modules/xmpp/recording.js")
-},{"../../service/xmpp/XMPPEvents":81,"jitsi-meet-logger":47}],35:[function(require,module,exports){
+},{"../../service/xmpp/XMPPEvents":138,"jitsi-meet-logger":49}],37:[function(require,module,exports){
(function (__filename){
/* jshint -W117 */
/* a simple MUC connection plugin
@@ -11302,13 +12239,14 @@ module.exports = function(XMPP) {
this.connection.addHandler(this.onMute.bind(this),
'http://jitsi.org/jitmeet/audio', 'iq', 'set',null,null);
},
- createRoom: function (jid, password, options) {
+ createRoom: function (jid, password, options, settings) {
var roomJid = Strophe.getBareJidFromJid(jid);
if (this.rooms[roomJid]) {
logger.error("You are already in the room!");
return;
}
- this.rooms[roomJid] = new ChatRoom(this.connection, jid, password, XMPP, options);
+ this.rooms[roomJid] = new ChatRoom(this.connection, jid,
+ password, XMPP, options, settings);
return this.rooms[roomJid];
},
doLeave: function (jid) {
@@ -11386,7 +12324,7 @@ module.exports = function(XMPP) {
};
}).call(this,"/modules/xmpp/strophe.emuc.js")
-},{"./ChatRoom":26,"jitsi-meet-logger":47}],36:[function(require,module,exports){
+},{"./ChatRoom":28,"jitsi-meet-logger":49}],38:[function(require,module,exports){
(function (__filename){
/* jshint -W117 */
@@ -11683,7 +12621,7 @@ module.exports = function(XMPP, eventEmitter) {
}).call(this,"/modules/xmpp/strophe.jingle.js")
-},{"../../service/xmpp/XMPPEvents":81,"../RTC/RTCBrowserType":17,"./JingleSessionPC":28,"jitsi-meet-logger":47}],37:[function(require,module,exports){
+},{"../../service/xmpp/XMPPEvents":138,"../RTC/RTCBrowserType":17,"./JingleSessionPC":30,"jitsi-meet-logger":49}],39:[function(require,module,exports){
/* global Strophe */
module.exports = function () {
@@ -11704,7 +12642,7 @@ module.exports = function () {
}
});
};
-},{}],38:[function(require,module,exports){
+},{}],40:[function(require,module,exports){
(function (__filename){
/* global $, $iq, Strophe */
@@ -11831,7 +12769,7 @@ module.exports = function (XMPP, eventEmitter) {
};
}).call(this,"/modules/xmpp/strophe.ping.js")
-},{"../../service/xmpp/XMPPEvents":81,"jitsi-meet-logger":47}],39:[function(require,module,exports){
+},{"../../service/xmpp/XMPPEvents":138,"jitsi-meet-logger":49}],41:[function(require,module,exports){
(function (__filename){
/* jshint -W117 */
var logger = require("jitsi-meet-logger").getLogger(__filename);
@@ -11948,7 +12886,7 @@ module.exports = function() {
};
}).call(this,"/modules/xmpp/strophe.rayo.js")
-},{"jitsi-meet-logger":47}],40:[function(require,module,exports){
+},{"jitsi-meet-logger":49}],42:[function(require,module,exports){
(function (__filename){
/* global Strophe */
/**
@@ -11997,7 +12935,7 @@ module.exports = function () {
};
}).call(this,"/modules/xmpp/strophe.util.js")
-},{"jitsi-meet-logger":47}],41:[function(require,module,exports){
+},{"jitsi-meet-logger":49}],43:[function(require,module,exports){
(function (__filename){
/* global $, APP, config, Strophe*/
@@ -12187,7 +13125,7 @@ XMPP.prototype.connect = function (jid, password) {
return this._connect(jid, password);
};
-XMPP.prototype.createRoom = function (roomName, options) {
+XMPP.prototype.createRoom = function (roomName, options, settings) {
var roomjid = roomName + '@' + this.options.hosts.muc;
if (options.useNicks) {
@@ -12205,7 +13143,7 @@ XMPP.prototype.createRoom = function (roomName, options) {
roomjid += '/' + tmpJid;
}
- return this.connection.emuc.createRoom(roomjid, null, options);
+ return this.connection.emuc.createRoom(roomjid, null, options, settings);
}
XMPP.prototype.addListener = function(type, listener) {
@@ -12309,7 +13247,7 @@ XMPP.prototype.disconnect = function () {
module.exports = XMPP;
}).call(this,"/modules/xmpp/xmpp.js")
-},{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":75,"../../service/xmpp/XMPPEvents":81,"../RTC/RTC":16,"./strophe.emuc":35,"./strophe.jingle":36,"./strophe.logger":37,"./strophe.ping":38,"./strophe.rayo":39,"./strophe.util":40,"events":43,"jitsi-meet-logger":47,"pako":48}],42:[function(require,module,exports){
+},{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":132,"../../service/xmpp/XMPPEvents":138,"../RTC/RTC":16,"./strophe.emuc":37,"./strophe.jingle":38,"./strophe.logger":39,"./strophe.ping":40,"./strophe.rayo":41,"./strophe.util":42,"events":45,"jitsi-meet-logger":49,"pako":51}],44:[function(require,module,exports){
(function (process){
/*!
* async
@@ -13436,7 +14374,7 @@ module.exports = XMPP;
}());
}).call(this,require('_process'))
-},{"_process":44}],43:[function(require,module,exports){
+},{"_process":46}],45:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
@@ -13739,7 +14677,7 @@ function isUndefined(arg) {
return arg === void 0;
}
-},{}],44:[function(require,module,exports){
+},{}],46:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
@@ -13832,7 +14770,7 @@ process.chdir = function (dir) {
};
process.umask = function() { return 0; };
-},{}],45:[function(require,module,exports){
+},{}],47:[function(require,module,exports){
(function (process,global){
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
@@ -14803,7 +15741,7 @@ process.umask = function() { return 0; };
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"_process":44}],46:[function(require,module,exports){
+},{"_process":46}],48:[function(require,module,exports){
/* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -14947,7 +15885,7 @@ Logger.levels = {
ERROR: "error"
};
-},{}],47:[function(require,module,exports){
+},{}],49:[function(require,module,exports){
/* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -15032,7 +15970,43 @@ module.exports = {
levels: Logger.levels
};
-},{"./Logger":46}],48:[function(require,module,exports){
+},{"./Logger":48}],50:[function(require,module,exports){
+/*
+ A JavaScript implementation of the SHA family of hashes, as
+ defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation
+ as defined in FIPS PUB 198a
+
+ Copyright Brian Turek 2008-2013
+ Distributed under the BSD License
+ See http://caligatio.github.com/jsSHA/ for more information
+
+ Several functions taken from Paul Johnston
+*/
+(function(T){function z(a,c,b){var g=0,f=[0],h="",l=null,h=b||"UTF8";if("UTF8"!==h&&"UTF16"!==h)throw"encoding must be UTF8 or UTF16";if("HEX"===c){if(0!==a.length%2)throw"srcString of HEX type must be in byte increments";l=B(a);g=l.binLen;f=l.value}else if("ASCII"===c||"TEXT"===c)l=J(a,h),g=l.binLen,f=l.value;else if("B64"===c)l=K(a),g=l.binLen,f=l.value;else throw"inputFormat must be HEX, TEXT, ASCII, or B64";this.getHash=function(a,c,b,h){var l=null,d=f.slice(),n=g,p;3===arguments.length?"number"!==
+typeof b&&(h=b,b=1):2===arguments.length&&(b=1);if(b!==parseInt(b,10)||1>b)throw"numRounds must a integer >= 1";switch(c){case "HEX":l=L;break;case "B64":l=M;break;default:throw"format must be HEX or B64";}if("SHA-1"===a)for(p=0;p<b;p++)d=y(d,n),n=160;else if("SHA-224"===a)for(p=0;p<b;p++)d=v(d,n,a),n=224;else if("SHA-256"===a)for(p=0;p<b;p++)d=v(d,n,a),n=256;else if("SHA-384"===a)for(p=0;p<b;p++)d=v(d,n,a),n=384;else if("SHA-512"===a)for(p=0;p<b;p++)d=v(d,n,a),n=512;else throw"Chosen SHA variant is not supported";
+return l(d,N(h))};this.getHMAC=function(a,b,c,l,s){var d,n,p,m,w=[],x=[];d=null;switch(l){case "HEX":l=L;break;case "B64":l=M;break;default:throw"outputFormat must be HEX or B64";}if("SHA-1"===c)n=64,m=160;else if("SHA-224"===c)n=64,m=224;else if("SHA-256"===c)n=64,m=256;else if("SHA-384"===c)n=128,m=384;else if("SHA-512"===c)n=128,m=512;else throw"Chosen SHA variant is not supported";if("HEX"===b)d=B(a),p=d.binLen,d=d.value;else if("ASCII"===b||"TEXT"===b)d=J(a,h),p=d.binLen,d=d.value;else if("B64"===
+b)d=K(a),p=d.binLen,d=d.value;else throw"inputFormat must be HEX, TEXT, ASCII, or B64";a=8*n;b=n/4-1;n<p/8?(d="SHA-1"===c?y(d,p):v(d,p,c),d[b]&=4294967040):n>p/8&&(d[b]&=4294967040);for(n=0;n<=b;n+=1)w[n]=d[n]^909522486,x[n]=d[n]^1549556828;c="SHA-1"===c?y(x.concat(y(w.concat(f),a+g)),a+m):v(x.concat(v(w.concat(f),a+g,c)),a+m,c);return l(c,N(s))}}function s(a,c){this.a=a;this.b=c}function J(a,c){var b=[],g,f=[],h=0,l;if("UTF8"===c)for(l=0;l<a.length;l+=1)for(g=a.charCodeAt(l),f=[],2048<g?(f[0]=224|
+(g&61440)>>>12,f[1]=128|(g&4032)>>>6,f[2]=128|g&63):128<g?(f[0]=192|(g&1984)>>>6,f[1]=128|g&63):f[0]=g,g=0;g<f.length;g+=1)b[h>>>2]|=f[g]<<24-h%4*8,h+=1;else if("UTF16"===c)for(l=0;l<a.length;l+=1)b[h>>>2]|=a.charCodeAt(l)<<16-h%4*8,h+=2;return{value:b,binLen:8*h}}function B(a){var c=[],b=a.length,g,f;if(0!==b%2)throw"String of HEX type must be in byte increments";for(g=0;g<b;g+=2){f=parseInt(a.substr(g,2),16);if(isNaN(f))throw"String of HEX type contains invalid characters";c[g>>>3]|=f<<24-g%8*4}return{value:c,
+binLen:4*b}}function K(a){var c=[],b=0,g,f,h,l,r;if(-1===a.search(/^[a-zA-Z0-9=+\/]+$/))throw"Invalid character in base-64 string";g=a.indexOf("=");a=a.replace(/\=/g,"");if(-1!==g&&g<a.length)throw"Invalid '=' found in base-64 string";for(f=0;f<a.length;f+=4){r=a.substr(f,4);for(h=l=0;h<r.length;h+=1)g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(r[h]),l|=g<<18-6*h;for(h=0;h<r.length-1;h+=1)c[b>>2]|=(l>>>16-8*h&255)<<24-b%4*8,b+=1}return{value:c,binLen:8*b}}function L(a,
+c){var b="",g=4*a.length,f,h;for(f=0;f<g;f+=1)h=a[f>>>2]>>>8*(3-f%4),b+="0123456789abcdef".charAt(h>>>4&15)+"0123456789abcdef".charAt(h&15);return c.outputUpper?b.toUpperCase():b}function M(a,c){var b="",g=4*a.length,f,h,l;for(f=0;f<g;f+=3)for(l=(a[f>>>2]>>>8*(3-f%4)&255)<<16|(a[f+1>>>2]>>>8*(3-(f+1)%4)&255)<<8|a[f+2>>>2]>>>8*(3-(f+2)%4)&255,h=0;4>h;h+=1)b=8*f+6*h<=32*a.length?b+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(l>>>6*(3-h)&63):b+c.b64Pad;return b}function N(a){var c=
+{outputUpper:!1,b64Pad:"="};try{a.hasOwnProperty("outputUpper")&&(c.outputUpper=a.outputUpper),a.hasOwnProperty("b64Pad")&&(c.b64Pad=a.b64Pad)}catch(b){}if("boolean"!==typeof c.outputUpper)throw"Invalid outputUpper formatting option";if("string"!==typeof c.b64Pad)throw"Invalid b64Pad formatting option";return c}function U(a,c){return a<<c|a>>>32-c}function u(a,c){return a>>>c|a<<32-c}function t(a,c){var b=null,b=new s(a.a,a.b);return b=32>=c?new s(b.a>>>c|b.b<<32-c&4294967295,b.b>>>c|b.a<<32-c&4294967295):
+new s(b.b>>>c-32|b.a<<64-c&4294967295,b.a>>>c-32|b.b<<64-c&4294967295)}function O(a,c){var b=null;return b=32>=c?new s(a.a>>>c,a.b>>>c|a.a<<32-c&4294967295):new s(0,a.a>>>c-32)}function V(a,c,b){return a^c^b}function P(a,c,b){return a&c^~a&b}function W(a,c,b){return new s(a.a&c.a^~a.a&b.a,a.b&c.b^~a.b&b.b)}function Q(a,c,b){return a&c^a&b^c&b}function X(a,c,b){return new s(a.a&c.a^a.a&b.a^c.a&b.a,a.b&c.b^a.b&b.b^c.b&b.b)}function Y(a){return u(a,2)^u(a,13)^u(a,22)}function Z(a){var c=t(a,28),b=t(a,
+34);a=t(a,39);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function $(a){return u(a,6)^u(a,11)^u(a,25)}function aa(a){var c=t(a,14),b=t(a,18);a=t(a,41);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function ba(a){return u(a,7)^u(a,18)^a>>>3}function ca(a){var c=t(a,1),b=t(a,8);a=O(a,7);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function da(a){return u(a,17)^u(a,19)^a>>>10}function ea(a){var c=t(a,19),b=t(a,61);a=O(a,6);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function R(a,c){var b=(a&65535)+(c&65535);return((a>>>16)+(c>>>
+16)+(b>>>16)&65535)<<16|b&65535}function fa(a,c,b,g){var f=(a&65535)+(c&65535)+(b&65535)+(g&65535);return((a>>>16)+(c>>>16)+(b>>>16)+(g>>>16)+(f>>>16)&65535)<<16|f&65535}function S(a,c,b,g,f){var h=(a&65535)+(c&65535)+(b&65535)+(g&65535)+(f&65535);return((a>>>16)+(c>>>16)+(b>>>16)+(g>>>16)+(f>>>16)+(h>>>16)&65535)<<16|h&65535}function ga(a,c){var b,g,f;b=(a.b&65535)+(c.b&65535);g=(a.b>>>16)+(c.b>>>16)+(b>>>16);f=(g&65535)<<16|b&65535;b=(a.a&65535)+(c.a&65535)+(g>>>16);g=(a.a>>>16)+(c.a>>>16)+(b>>>
+16);return new s((g&65535)<<16|b&65535,f)}function ha(a,c,b,g){var f,h,l;f=(a.b&65535)+(c.b&65535)+(b.b&65535)+(g.b&65535);h=(a.b>>>16)+(c.b>>>16)+(b.b>>>16)+(g.b>>>16)+(f>>>16);l=(h&65535)<<16|f&65535;f=(a.a&65535)+(c.a&65535)+(b.a&65535)+(g.a&65535)+(h>>>16);h=(a.a>>>16)+(c.a>>>16)+(b.a>>>16)+(g.a>>>16)+(f>>>16);return new s((h&65535)<<16|f&65535,l)}function ia(a,c,b,g,f){var h,l,r;h=(a.b&65535)+(c.b&65535)+(b.b&65535)+(g.b&65535)+(f.b&65535);l=(a.b>>>16)+(c.b>>>16)+(b.b>>>16)+(g.b>>>16)+(f.b>>>
+16)+(h>>>16);r=(l&65535)<<16|h&65535;h=(a.a&65535)+(c.a&65535)+(b.a&65535)+(g.a&65535)+(f.a&65535)+(l>>>16);l=(a.a>>>16)+(c.a>>>16)+(b.a>>>16)+(g.a>>>16)+(f.a>>>16)+(h>>>16);return new s((l&65535)<<16|h&65535,r)}function y(a,c){var b=[],g,f,h,l,r,s,u=P,t=V,v=Q,d=U,n=R,p,m,w=S,x,q=[1732584193,4023233417,2562383102,271733878,3285377520];a[c>>>5]|=128<<24-c%32;a[(c+65>>>9<<4)+15]=c;x=a.length;for(p=0;p<x;p+=16){g=q[0];f=q[1];h=q[2];l=q[3];r=q[4];for(m=0;80>m;m+=1)b[m]=16>m?a[m+p]:d(b[m-3]^b[m-8]^b[m-
+14]^b[m-16],1),s=20>m?w(d(g,5),u(f,h,l),r,1518500249,b[m]):40>m?w(d(g,5),t(f,h,l),r,1859775393,b[m]):60>m?w(d(g,5),v(f,h,l),r,2400959708,b[m]):w(d(g,5),t(f,h,l),r,3395469782,b[m]),r=l,l=h,h=d(f,30),f=g,g=s;q[0]=n(g,q[0]);q[1]=n(f,q[1]);q[2]=n(h,q[2]);q[3]=n(l,q[3]);q[4]=n(r,q[4])}return q}function v(a,c,b){var g,f,h,l,r,t,u,v,z,d,n,p,m,w,x,q,y,C,D,E,F,G,H,I,e,A=[],B,k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,
+1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,
+2361852424,2428436474,2756734187,3204031479,3329325298];d=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428];f=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];if("SHA-224"===b||"SHA-256"===b)n=64,g=(c+65>>>9<<4)+15,w=16,x=1,e=Number,q=R,y=fa,C=S,D=ba,E=da,F=Y,G=$,I=Q,H=P,d="SHA-224"===b?d:f;else if("SHA-384"===b||"SHA-512"===b)n=80,g=(c+128>>>10<<5)+31,w=32,x=2,e=s,q=ga,y=ha,C=ia,D=ca,E=ea,F=Z,G=aa,I=X,H=W,k=[new e(k[0],
+3609767458),new e(k[1],602891725),new e(k[2],3964484399),new e(k[3],2173295548),new e(k[4],4081628472),new e(k[5],3053834265),new e(k[6],2937671579),new e(k[7],3664609560),new e(k[8],2734883394),new e(k[9],1164996542),new e(k[10],1323610764),new e(k[11],3590304994),new e(k[12],4068182383),new e(k[13],991336113),new e(k[14],633803317),new e(k[15],3479774868),new e(k[16],2666613458),new e(k[17],944711139),new e(k[18],2341262773),new e(k[19],2007800933),new e(k[20],1495990901),new e(k[21],1856431235),
+new e(k[22],3175218132),new e(k[23],2198950837),new e(k[24],3999719339),new e(k[25],766784016),new e(k[26],2566594879),new e(k[27],3203337956),new e(k[28],1034457026),new e(k[29],2466948901),new e(k[30],3758326383),new e(k[31],168717936),new e(k[32],1188179964),new e(k[33],1546045734),new e(k[34],1522805485),new e(k[35],2643833823),new e(k[36],2343527390),new e(k[37],1014477480),new e(k[38],1206759142),new e(k[39],344077627),new e(k[40],1290863460),new e(k[41],3158454273),new e(k[42],3505952657),
+new e(k[43],106217008),new e(k[44],3606008344),new e(k[45],1432725776),new e(k[46],1467031594),new e(k[47],851169720),new e(k[48],3100823752),new e(k[49],1363258195),new e(k[50],3750685593),new e(k[51],3785050280),new e(k[52],3318307427),new e(k[53],3812723403),new e(k[54],2003034995),new e(k[55],3602036899),new e(k[56],1575990012),new e(k[57],1125592928),new e(k[58],2716904306),new e(k[59],442776044),new e(k[60],593698344),new e(k[61],3733110249),new e(k[62],2999351573),new e(k[63],3815920427),new e(3391569614,
+3928383900),new e(3515267271,566280711),new e(3940187606,3454069534),new e(4118630271,4000239992),new e(116418474,1914138554),new e(174292421,2731055270),new e(289380356,3203993006),new e(460393269,320620315),new e(685471733,587496836),new e(852142971,1086792851),new e(1017036298,365543100),new e(1126000580,2618297676),new e(1288033470,3409855158),new e(1501505948,4234509866),new e(1607167915,987167468),new e(1816402316,1246189591)],d="SHA-384"===b?[new e(3418070365,d[0]),new e(1654270250,d[1]),new e(2438529370,
+d[2]),new e(355462360,d[3]),new e(1731405415,d[4]),new e(41048885895,d[5]),new e(3675008525,d[6]),new e(1203062813,d[7])]:[new e(f[0],4089235720),new e(f[1],2227873595),new e(f[2],4271175723),new e(f[3],1595750129),new e(f[4],2917565137),new e(f[5],725511199),new e(f[6],4215389547),new e(f[7],327033209)];else throw"Unexpected error in SHA-2 implementation";a[c>>>5]|=128<<24-c%32;a[g]=c;B=a.length;for(p=0;p<B;p+=w){c=d[0];g=d[1];f=d[2];h=d[3];l=d[4];r=d[5];t=d[6];u=d[7];for(m=0;m<n;m+=1)A[m]=16>m?
+new e(a[m*x+p],a[m*x+p+1]):y(E(A[m-2]),A[m-7],D(A[m-15]),A[m-16]),v=C(u,G(l),H(l,r,t),k[m],A[m]),z=q(F(c),I(c,g,f)),u=t,t=r,r=l,l=q(h,v),h=f,f=g,g=c,c=q(v,z);d[0]=q(c,d[0]);d[1]=q(g,d[1]);d[2]=q(f,d[2]);d[3]=q(h,d[3]);d[4]=q(l,d[4]);d[5]=q(r,d[5]);d[6]=q(t,d[6]);d[7]=q(u,d[7])}if("SHA-224"===b)a=[d[0],d[1],d[2],d[3],d[4],d[5],d[6]];else if("SHA-256"===b)a=d;else if("SHA-384"===b)a=[d[0].a,d[0].b,d[1].a,d[1].b,d[2].a,d[2].b,d[3].a,d[3].b,d[4].a,d[4].b,d[5].a,d[5].b];else if("SHA-512"===b)a=[d[0].a,
+d[0].b,d[1].a,d[1].b,d[2].a,d[2].b,d[3].a,d[3].b,d[4].a,d[4].b,d[5].a,d[5].b,d[6].a,d[6].b,d[7].a,d[7].b];else throw"Unexpected error in SHA-2 implementation";return a}"function"===typeof define&&typeof define.amd?define(function(){return z}):"undefined"!==typeof exports?"undefined"!==typeof module&&module.exports?module.exports=exports=z:exports=z:T.jsSHA=z})(this);
+
+},{}],51:[function(require,module,exports){
// Top level file is just a mixin of submodules & constants
'use strict';
@@ -15048,7 +16022,7 @@ assign(pako, deflate, inflate, constants);
module.exports = pako;
-},{"./lib/deflate":49,"./lib/inflate":50,"./lib/utils/common":51,"./lib/zlib/constants":54}],49:[function(require,module,exports){
+},{"./lib/deflate":52,"./lib/inflate":53,"./lib/utils/common":54,"./lib/zlib/constants":57}],52:[function(require,module,exports){
'use strict';
@@ -15426,7 +16400,7 @@ exports.deflate = deflate;
exports.deflateRaw = deflateRaw;
exports.gzip = gzip;
-},{"./utils/common":51,"./utils/strings":52,"./zlib/deflate.js":56,"./zlib/messages":61,"./zlib/zstream":63}],50:[function(require,module,exports){
+},{"./utils/common":54,"./utils/strings":55,"./zlib/deflate.js":59,"./zlib/messages":64,"./zlib/zstream":66}],53:[function(require,module,exports){
'use strict';
@@ -15828,7 +16802,7 @@ exports.inflate = inflate;
exports.inflateRaw = inflateRaw;
exports.ungzip = inflate;
-},{"./utils/common":51,"./utils/strings":52,"./zlib/constants":54,"./zlib/gzheader":57,"./zlib/inflate.js":59,"./zlib/messages":61,"./zlib/zstream":63}],51:[function(require,module,exports){
+},{"./utils/common":54,"./utils/strings":55,"./zlib/constants":57,"./zlib/gzheader":60,"./zlib/inflate.js":62,"./zlib/messages":64,"./zlib/zstream":66}],54:[function(require,module,exports){
'use strict';
@@ -15932,7 +16906,7 @@ exports.setTyped = function (on) {
exports.setTyped(TYPED_OK);
-},{}],52:[function(require,module,exports){
+},{}],55:[function(require,module,exports){
// String encode/decode helpers
'use strict';
@@ -16119,7 +17093,7 @@ exports.utf8border = function(buf, max) {
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
-},{"./common":51}],53:[function(require,module,exports){
+},{"./common":54}],56:[function(require,module,exports){
'use strict';
// Note: adler32 takes 12% for level 0 and 2% for level 6.
@@ -16153,7 +17127,7 @@ function adler32(adler, buf, len, pos) {
module.exports = adler32;
-},{}],54:[function(require,module,exports){
+},{}],57:[function(require,module,exports){
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
@@ -16202,7 +17176,7 @@ module.exports = {
//Z_NULL: null // Use -1 or null inline, depending on var type
};
-},{}],55:[function(require,module,exports){
+},{}],58:[function(require,module,exports){
'use strict';
// Note: we can't get significant speed boost here.
@@ -16245,7 +17219,7 @@ function crc32(crc, buf, len, pos) {
module.exports = crc32;
-},{}],56:[function(require,module,exports){
+},{}],59:[function(require,module,exports){
'use strict';
var utils = require('../utils/common');
@@ -18012,7 +18986,7 @@ exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/
-},{"../utils/common":51,"./adler32":53,"./crc32":55,"./messages":61,"./trees":62}],57:[function(require,module,exports){
+},{"../utils/common":54,"./adler32":56,"./crc32":58,"./messages":64,"./trees":65}],60:[function(require,module,exports){
'use strict';
@@ -18054,7 +19028,7 @@ function GZheader() {
module.exports = GZheader;
-},{}],58:[function(require,module,exports){
+},{}],61:[function(require,module,exports){
'use strict';
// See state defs from inflate.js
@@ -18382,7 +19356,7 @@ module.exports = function inflate_fast(strm, start) {
return;
};
-},{}],59:[function(require,module,exports){
+},{}],62:[function(require,module,exports){
'use strict';
@@ -19887,7 +20861,7 @@ exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/
-},{"../utils/common":51,"./adler32":53,"./crc32":55,"./inffast":58,"./inftrees":60}],60:[function(require,module,exports){
+},{"../utils/common":54,"./adler32":56,"./crc32":58,"./inffast":61,"./inftrees":63}],63:[function(require,module,exports){
'use strict';
@@ -20216,7 +21190,7 @@ module.exports = function inflate_table(type, lens, lens_index, codes, table, ta
return 0;
};
-},{"../utils/common":51}],61:[function(require,module,exports){
+},{"../utils/common":54}],64:[function(require,module,exports){
'use strict';
module.exports = {
@@ -20231,7 +21205,7 @@ module.exports = {
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
-},{}],62:[function(require,module,exports){
+},{}],65:[function(require,module,exports){
'use strict';
@@ -21432,7 +22406,7 @@ exports._tr_flush_block = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;
-},{"../utils/common":51}],63:[function(require,module,exports){
+},{"../utils/common":54}],66:[function(require,module,exports){
'use strict';
@@ -21463,7 +22437,7 @@ function ZStream() {
module.exports = ZStream;
-},{}],64:[function(require,module,exports){
+},{}],67:[function(require,module,exports){
/* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -21504,7 +22478,7 @@ module.exports = function arrayEquals(array) {
};
-},{}],65:[function(require,module,exports){
+},{}],68:[function(require,module,exports){
/* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -21522,7 +22496,7 @@ module.exports = function arrayEquals(array) {
exports.Interop = require('./interop');
-},{"./interop":66}],66:[function(require,module,exports){
+},{"./interop":69}],69:[function(require,module,exports){
/* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -22245,7 +23219,7 @@ Interop.prototype.toUnifiedPlan = function(desc) {
//#endregion
};
-},{"./array-equals":64,"./transform":67}],67:[function(require,module,exports){
+},{"./array-equals":67,"./transform":70}],70:[function(require,module,exports){
/* Copyright @ 2015 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
@@ -22359,984 +23333,7989 @@ exports.parse = function(sdp) {
};
-},{"sdp-transform":71}],68:[function(require,module,exports){
-/* Copyright @ 2015 Atlassian Pty Ltd
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-var transform = require('sdp-transform');
-var transformUtils = require('./transform-utils');
-var parseSsrcs = transformUtils.parseSsrcs;
-var writeSsrcs = transformUtils.writeSsrcs;
-
-//region Constants
-
-var DEFAULT_NUM_OF_LAYERS = 3;
-
-//endregion
-
-//region Ctor
-
-function Simulcast(options) {
-
- this.options = options ? options : {};
-
- if (!this.options.numOfLayers) {
- this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
- }
-
- this.layers = [];
-}
-
-//endregion
-
-//region Stateless private utility functions
-
-/**
- * Returns a random integer between min (included) and max (excluded)
- * Using Math.round() gives a non-uniform distribution!
- * @returns {number}
- */
-function generateSSRC() {
- var min = 0, max = 0xffffffff;
- return Math.floor(Math.random() * (max - min)) + min;
-};
-
-function processVideo(session, action) {
- if (session == null || !Array.isArray(session.media)) {
- return;
- }
-
- session.media.forEach(function (mLine) {
- if (mLine.type === 'video') {
- action(mLine);
- }
- });
-}
-
-function validateDescription(desc)
-{
- return desc && desc != null
- && desc.type && desc.type != ''
- && desc.sdp && desc.sdp != '';
-}
-
-function explodeRemoteSimulcast(mLine) {
-
- if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
- return;
- }
-
- var sources = parseSsrcs(mLine);
- var order = [];
-
- // Find the SIM group and explode its sources.
- var j = mLine.ssrcGroups.length;
- while (j--) {
-
- if (mLine.ssrcGroups[j].semantics !== 'SIM') {
- continue;
- }
-
- var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
-
- for (var i = 0; i < simulcastSsrcs.length; i++) {
-
- var ssrc = simulcastSsrcs[i];
- order.push(ssrc);
-
- var parts = sources[ssrc].msid.split(' ');
- sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
- sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
-
- // Remove all the groups that this SSRC participates in.
- mLine.ssrcGroups.forEach(function (relatedGroup) {
- if (relatedGroup.semantics === 'SIM') {
- return;
- }
-
- var relatedSsrcs = relatedGroup.ssrcs.split(' ');
- if (relatedSsrcs.indexOf(ssrc) === -1) {
- return;
- }
-
- // Nuke all the related SSRCs.
- relatedSsrcs.forEach(function (relatedSSRC) {
- sources[relatedSSRC].msid = sources[ssrc].msid;
- sources[relatedSSRC].cname = sources[ssrc].cname;
- if (relatedSSRC !== ssrc) {
- order.push(relatedSSRC);
- }
- });
-
- // Schedule the related group for nuking.
- })
- }
-
- mLine.ssrcs = writeSsrcs(sources, order);
- mLine.ssrcGroups.splice(j, 1);
- };
-}
-
-function implodeRemoteSimulcast(mLine) {
-
- if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
- console.info('Halt: There are no SSRC groups in the remote ' +
- 'description.');
- return;
- }
-
- var sources = parseSsrcs(mLine);
-
- // Find the SIM group and nuke it.
- mLine.ssrcGroups.forEach(function (simulcastGroup) {
- if (simulcastGroup.semantics !== 'SIM') {
- return;
- }
-
- console.info("Imploding SIM group: " + simulcastGroup.ssrcs);
- // Schedule the SIM group for nuking.
- simulcastGroup.nuke = true;
-
- var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
-
- // Nuke all the higher layer SSRCs.
- for (var i = 1; i < simulcastSsrcs.length; i++) {
-
- var ssrc = simulcastSsrcs[i];
- delete sources[ssrc];
-
- // Remove all the groups that this SSRC participates in.
- mLine.ssrcGroups.forEach(function (relatedGroup) {
- if (relatedGroup.semantics === 'SIM') {
- return;
- }
-
- var relatedSsrcs = relatedGroup.ssrcs.split(' ');
- if (relatedSsrcs.indexOf(ssrc) === -1) {
- return;
- }
-
- // Nuke all the related SSRCs.
+},{"sdp-transform":72}],71:[function(require,module,exports){
+var grammar = module.exports = {
+ v: [{
+ name: 'version',
+ reg: /^(\d*)$/
+ }],
+ o: [{ //o=- 20518 0 IN IP4 203.0.113.1
+ // NB: sessionId will be a String in most cases because it is huge
+ name: 'origin',
+ reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
+ names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
+ format: "%s %s %d %s IP%d %s"
+ }],
+ // default parsing of these only (though some of these feel outdated)
+ s: [{ name: 'name' }],
+ i: [{ name: 'description' }],
+ u: [{ name: 'uri' }],
+ e: [{ name: 'email' }],
+ p: [{ name: 'phone' }],
+ z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
+ r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
+ //k: [{}], // outdated thing ignored
+ t: [{ //t=0 0
+ name: 'timing',
+ reg: /^(\d*) (\d*)/,
+ names: ['start', 'stop'],
+ format: "%d %d"
+ }],
+ c: [{ //c=IN IP4 10.47.197.26
+ name: 'connection',
+ reg: /^IN IP(\d) (\S*)/,
+ names: ['version', 'ip'],
+ format: "IN IP%d %s"
+ }],
+ b: [{ //b=AS:4000
+ push: 'bandwidth',
+ reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
+ names: ['type', 'limit'],
+ format: "%s:%s"
+ }],
+ m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
+ // NB: special - pushes to session
+ // TODO: rtp/fmtp should be filtered by the payloads found here?
+ reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
+ names: ['type', 'port', 'protocol', 'payloads'],
+ format: "%s %d %s %s"
+ }],
+ a: [
+ { //a=rtpmap:110 opus/48000/2
+ push: 'rtp',
+ reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
+ names: ['payload', 'codec', 'rate', 'encoding'],
+ format: function (o) {
+ return (o.encoding) ?
+ "rtpmap:%d %s/%s/%s":
+ o.rate ?
+ "rtpmap:%d %s/%s":
+ "rtpmap:%d %s";
+ }
+ },
+ {
+ //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
+ //a=fmtp:111 minptime=10; useinbandfec=1
+ push: 'fmtp',
+ reg: /^fmtp:(\d*) ([\S| ]*)/,
+ names: ['payload', 'config'],
+ format: "fmtp:%d %s"
+ },
+ { //a=control:streamid=0
+ name: 'control',
+ reg: /^control:(.*)/,
+ format: "control:%s"
+ },
+ { //a=rtcp:65179 IN IP4 193.84.77.194
+ name: 'rtcp',
+ reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
+ names: ['port', 'netType', 'ipVer', 'address'],
+ format: function (o) {
+ return (o.address != null) ?
+ "rtcp:%d %s IP%d %s":
+ "rtcp:%d";
+ }
+ },
+ { //a=rtcp-fb:98 trr-int 100
+ push: 'rtcpFbTrrInt',
+ reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
+ names: ['payload', 'value'],
+ format: "rtcp-fb:%d trr-int %d"
+ },
+ { //a=rtcp-fb:98 nack rpsi
+ push: 'rtcpFb',
+ reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
+ names: ['payload', 'type', 'subtype'],
+ format: function (o) {
+ return (o.subtype != null) ?
+ "rtcp-fb:%s %s %s":
+ "rtcp-fb:%s %s";
+ }
+ },
+ { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
+ //a=extmap:1/recvonly URI-gps-string
+ push: 'ext',
+ reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
+ names: ['value', 'uri', 'config'], // value may include "/direction" suffix
+ format: function (o) {
+ return (o.config != null) ?
+ "extmap:%s %s %s":
+ "extmap:%s %s";
+ }
+ },
+ {
+ //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
+ push: 'crypto',
+ reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
+ names: ['id', 'suite', 'config', 'sessionConfig'],
+ format: function (o) {
+ return (o.sessionConfig != null) ?
+ "crypto:%d %s %s %s":
+ "crypto:%d %s %s";
+ }
+ },
+ { //a=setup:actpass
+ name: 'setup',
+ reg: /^setup:(\w*)/,
+ format: "setup:%s"
+ },
+ { //a=mid:1
+ name: 'mid',
+ reg: /^mid:([^\s]*)/,
+ format: "mid:%s"
+ },
+ { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
+ name: 'msid',
+ reg: /^msid:(.*)/,
+ format: "msid:%s"
+ },
+ { //a=ptime:20
+ name: 'ptime',
+ reg: /^ptime:(\d*)/,
+ format: "ptime:%d"
+ },
+ { //a=maxptime:60
+ name: 'maxptime',
+ reg: /^maxptime:(\d*)/,
+ format: "maxptime:%d"
+ },
+ { //a=sendrecv
+ name: 'direction',
+ reg: /^(sendrecv|recvonly|sendonly|inactive)/
+ },
+ { //a=ice-lite
+ name: 'icelite',
+ reg: /^(ice-lite)/
+ },
+ { //a=ice-ufrag:F7gI
+ name: 'iceUfrag',
+ reg: /^ice-ufrag:(\S*)/,
+ format: "ice-ufrag:%s"
+ },
+ { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
+ name: 'icePwd',
+ reg: /^ice-pwd:(\S*)/,
+ format: "ice-pwd:%s"
+ },
+ { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
+ name: 'fingerprint',
+ reg: /^fingerprint:(\S*) (\S*)/,
+ names: ['type', 'hash'],
+ format: "fingerprint:%s %s"
+ },
+ {
+ //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
+ //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
+ //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
+ //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
+ //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
+ push:'candidates',
+ reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
+ names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
+ format: function (o) {
+ var str = "candidate:%s %d %s %d %s %d typ %s";
+
+ str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
+
+ // NB: candidate has three optional chunks, so %void middles one if it's missing
+ str += (o.tcptype != null) ? " tcptype %s" : "%v";
+
+ if (o.generation != null) {
+ str += " generation %d";
+ }
+ return str;
+ }
+ },
+ { //a=end-of-candidates (keep after the candidates line for readability)
+ name: 'endOfCandidates',
+ reg: /^(end-of-candidates)/
+ },
+ { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
+ name: 'remoteCandidates',
+ reg: /^remote-candidates:(.*)/,
+ format: "remote-candidates:%s"
+ },
+ { //a=ice-options:google-ice
+ name: 'iceOptions',
+ reg: /^ice-options:(\S*)/,
+ format: "ice-options:%s"
+ },
+ { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
+ push: "ssrcs",
+ reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
+ names: ['id', 'attribute', 'value'],
+ format: "ssrc:%d %s:%s"
+ },
+ { //a=ssrc-group:FEC 1 2
+ push: "ssrcGroups",
+ reg: /^ssrc-group:(\w*) (.*)/,
+ names: ['semantics', 'ssrcs'],
+ format: "ssrc-group:%s %s"
+ },
+ { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
+ name: "msidSemantic",
+ reg: /^msid-semantic:\s?(\w*) (\S*)/,
+ names: ['semantic', 'token'],
+ format: "msid-semantic: %s %s" // space after ":" is not accidental
+ },
+ { //a=group:BUNDLE audio video
+ push: 'groups',
+ reg: /^group:(\w*) (.*)/,
+ names: ['type', 'mids'],
+ format: "group:%s %s"
+ },
+ { //a=rtcp-mux
+ name: 'rtcpMux',
+ reg: /^(rtcp-mux)/
+ },
+ { //a=rtcp-rsize
+ name: 'rtcpRsize',
+ reg: /^(rtcp-rsize)/
+ },
+ { // any a= that we don't understand is kepts verbatim on media.invalid
+ push: 'invalid',
+ names: ["value"]
+ }
+ ]
+};
+
+// set sensible defaults to avoid polluting the grammar with boring details
+Object.keys(grammar).forEach(function (key) {
+ var objs = grammar[key];
+ objs.forEach(function (obj) {
+ if (!obj.reg) {
+ obj.reg = /(.*)/;
+ }
+ if (!obj.format) {
+ obj.format = "%s";
+ }
+ });
+});
+
+},{}],72:[function(require,module,exports){
+var parser = require('./parser');
+var writer = require('./writer');
+
+exports.write = writer;
+exports.parse = parser.parse;
+exports.parseFmtpConfig = parser.parseFmtpConfig;
+exports.parsePayloads = parser.parsePayloads;
+exports.parseRemoteCandidates = parser.parseRemoteCandidates;
+
+},{"./parser":73,"./writer":74}],73:[function(require,module,exports){
+var toIntIfInt = function (v) {
+ return String(Number(v)) === v ? Number(v) : v;
+};
+
+var attachProperties = function (match, location, names, rawName) {
+ if (rawName && !names) {
+ location[rawName] = toIntIfInt(match[1]);
+ }
+ else {
+ for (var i = 0; i < names.length; i += 1) {
+ if (match[i+1] != null) {
+ location[names[i]] = toIntIfInt(match[i+1]);
+ }
+ }
+ }
+};
+
+var parseReg = function (obj, location, content) {
+ var needsBlank = obj.name && obj.names;
+ if (obj.push && !location[obj.push]) {
+ location[obj.push] = [];
+ }
+ else if (needsBlank && !location[obj.name]) {
+ location[obj.name] = {};
+ }
+ var keyLocation = obj.push ?
+ {} : // blank object that will be pushed
+ needsBlank ? location[obj.name] : location; // otherwise, named location or root
+
+ attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
+
+ if (obj.push) {
+ location[obj.push].push(keyLocation);
+ }
+};
+
+var grammar = require('./grammar');
+var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
+
+exports.parse = function (sdp) {
+ var session = {}
+ , media = []
+ , location = session; // points at where properties go under (one of the above)
+
+ // parse lines we understand
+ sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
+ var type = l[0];
+ var content = l.slice(2);
+ if (type === 'm') {
+ media.push({rtp: [], fmtp: []});
+ location = media[media.length-1]; // point at latest media line
+ }
+
+ for (var j = 0; j < (grammar[type] || []).length; j += 1) {
+ var obj = grammar[type][j];
+ if (obj.reg.test(content)) {
+ return parseReg(obj, location, content);
+ }
+ }
+ });
+
+ session.media = media; // link it up
+ return session;
+};
+
+var fmtpReducer = function (acc, expr) {
+ var s = expr.split('=');
+ if (s.length === 2) {
+ acc[s[0]] = toIntIfInt(s[1]);
+ }
+ return acc;
+};
+
+exports.parseFmtpConfig = function (str) {
+ return str.split(/\;\s?/).reduce(fmtpReducer, {});
+};
+
+exports.parsePayloads = function (str) {
+ return str.split(' ').map(Number);
+};
+
+exports.parseRemoteCandidates = function (str) {
+ var candidates = [];
+ var parts = str.split(' ').map(toIntIfInt);
+ for (var i = 0; i < parts.length; i += 3) {
+ candidates.push({
+ component: parts[i],
+ ip: parts[i + 1],
+ port: parts[i + 2]
+ });
+ }
+ return candidates;
+};
+
+},{"./grammar":71}],74:[function(require,module,exports){
+var grammar = require('./grammar');
+
+// customized util.format - discards excess arguments and can void middle ones
+var formatRegExp = /%[sdv%]/g;
+var format = function (formatStr) {
+ var i = 1;
+ var args = arguments;
+ var len = args.length;
+ return formatStr.replace(formatRegExp, function (x) {
+ if (i >= len) {
+ return x; // missing argument
+ }
+ var arg = args[i];
+ i += 1;
+ switch (x) {
+ case '%%':
+ return '%';
+ case '%s':
+ return String(arg);
+ case '%d':
+ return Number(arg);
+ case '%v':
+ return '';
+ }
+ });
+ // NB: we discard excess arguments - they are typically undefined from makeLine
+};
+
+var makeLine = function (type, obj, location) {
+ var str = obj.format instanceof Function ?
+ (obj.format(obj.push ? location : location[obj.name])) :
+ obj.format;
+
+ var args = [type + '=' + str];
+ if (obj.names) {
+ for (var i = 0; i < obj.names.length; i += 1) {
+ var n = obj.names[i];
+ if (obj.name) {
+ args.push(location[obj.name][n]);
+ }
+ else { // for mLine and push attributes
+ args.push(location[obj.names[i]]);
+ }
+ }
+ }
+ else {
+ args.push(location[obj.name]);
+ }
+ return format.apply(null, args);
+};
+
+// RFC specified order
+// TODO: extend this with all the rest
+var defaultOuterOrder = [
+ 'v', 'o', 's', 'i',
+ 'u', 'e', 'p', 'c',
+ 'b', 't', 'r', 'z', 'a'
+];
+var defaultInnerOrder = ['i', 'c', 'b', 'a'];
+
+
+module.exports = function (session, opts) {
+ opts = opts || {};
+ // ensure certain properties exist
+ if (session.version == null) {
+ session.version = 0; // "v=0" must be there (only defined version atm)
+ }
+ if (session.name == null) {
+ session.name = " "; // "s= " must be there if no meaningful name set
+ }
+ session.media.forEach(function (mLine) {
+ if (mLine.payloads == null) {
+ mLine.payloads = "";
+ }
+ });
+
+ var outerOrder = opts.outerOrder || defaultOuterOrder;
+ var innerOrder = opts.innerOrder || defaultInnerOrder;
+ var sdp = [];
+
+ // loop through outerOrder for matching properties on session
+ outerOrder.forEach(function (type) {
+ grammar[type].forEach(function (obj) {
+ if (obj.name in session && session[obj.name] != null) {
+ sdp.push(makeLine(type, obj, session));
+ }
+ else if (obj.push in session && session[obj.push] != null) {
+ session[obj.push].forEach(function (el) {
+ sdp.push(makeLine(type, obj, el));
+ });
+ }
+ });
+ });
+
+ // then for each media line, follow the innerOrder
+ session.media.forEach(function (mLine) {
+ sdp.push(makeLine('m', grammar.m[0], mLine));
+
+ innerOrder.forEach(function (type) {
+ grammar[type].forEach(function (obj) {
+ if (obj.name in mLine && mLine[obj.name] != null) {
+ sdp.push(makeLine(type, obj, mLine));
+ }
+ else if (obj.push in mLine && mLine[obj.push] != null) {
+ mLine[obj.push].forEach(function (el) {
+ sdp.push(makeLine(type, obj, el));
+ });
+ }
+ });
+ });
+ });
+
+ return sdp.join('\r\n') + '\r\n';
+};
+
+},{"./grammar":71}],75:[function(require,module,exports){
+/* Copyright @ 2015 Atlassian Pty Ltd
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+var transform = require('sdp-transform');
+var transformUtils = require('./transform-utils');
+var parseSsrcs = transformUtils.parseSsrcs;
+var writeSsrcs = transformUtils.writeSsrcs;
+
+//region Constants
+
+var DEFAULT_NUM_OF_LAYERS = 3;
+
+//endregion
+
+//region Ctor
+
+function Simulcast(options) {
+
+ this.options = options ? options : {};
+
+ if (!this.options.numOfLayers) {
+ this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
+ }
+
+ this.layers = [];
+}
+
+//endregion
+
+//region Stateless private utility functions
+
+/**
+ * Returns a random integer between min (included) and max (excluded)
+ * Using Math.round() gives a non-uniform distribution!
+ * @returns {number}
+ */
+function generateSSRC() {
+ var min = 0, max = 0xffffffff;
+ return Math.floor(Math.random() * (max - min)) + min;
+};
+
+function processVideo(session, action) {
+ if (session == null || !Array.isArray(session.media)) {
+ return;
+ }
+
+ session.media.forEach(function (mLine) {
+ if (mLine.type === 'video') {
+ action(mLine);
+ }
+ });
+}
+
+function validateDescription(desc)
+{
+ return desc && desc != null
+ && desc.type && desc.type != ''
+ && desc.sdp && desc.sdp != '';
+}
+
+function explodeRemoteSimulcast(mLine) {
+
+ if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
+ return;
+ }
+
+ var sources = parseSsrcs(mLine);
+ var order = [];
+
+ // Find the SIM group and explode its sources.
+ var j = mLine.ssrcGroups.length;
+ while (j--) {
+
+ if (mLine.ssrcGroups[j].semantics !== 'SIM') {
+ continue;
+ }
+
+ var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
+
+ for (var i = 0; i < simulcastSsrcs.length; i++) {
+
+ var ssrc = simulcastSsrcs[i];
+ order.push(ssrc);
+
+ var parts = sources[ssrc].msid.split(' ');
+ sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
+ sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
+
+ // Remove all the groups that this SSRC participates in.
+ mLine.ssrcGroups.forEach(function (relatedGroup) {
+ if (relatedGroup.semantics === 'SIM') {
+ return;
+ }
+
+ var relatedSsrcs = relatedGroup.ssrcs.split(' ');
+ if (relatedSsrcs.indexOf(ssrc) === -1) {
+ return;
+ }
+
+ // Nuke all the related SSRCs.
+ relatedSsrcs.forEach(function (relatedSSRC) {
+ sources[relatedSSRC].msid = sources[ssrc].msid;
+ sources[relatedSSRC].cname = sources[ssrc].cname;
+ if (relatedSSRC !== ssrc) {
+ order.push(relatedSSRC);
+ }
+ });
+
+ // Schedule the related group for nuking.
+ })
+ }
+
+ mLine.ssrcs = writeSsrcs(sources, order);
+ mLine.ssrcGroups.splice(j, 1);
+ };
+}
+
+function implodeRemoteSimulcast(mLine) {
+
+ if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
+ console.info('Halt: There are no SSRC groups in the remote ' +
+ 'description.');
+ return;
+ }
+
+ var sources = parseSsrcs(mLine);
+
+ // Find the SIM group and nuke it.
+ mLine.ssrcGroups.forEach(function (simulcastGroup) {
+ if (simulcastGroup.semantics !== 'SIM') {
+ return;
+ }
+
+ console.info("Imploding SIM group: " + simulcastGroup.ssrcs);
+ // Schedule the SIM group for nuking.
+ simulcastGroup.nuke = true;
+
+ var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
+
+ // Nuke all the higher layer SSRCs.
+ for (var i = 1; i < simulcastSsrcs.length; i++) {
+
+ var ssrc = simulcastSsrcs[i];
+ delete sources[ssrc];
+
+ // Remove all the groups that this SSRC participates in.
+ mLine.ssrcGroups.forEach(function (relatedGroup) {
+ if (relatedGroup.semantics === 'SIM') {
+ return;
+ }
+
+ var relatedSsrcs = relatedGroup.ssrcs.split(' ');
+ if (relatedSsrcs.indexOf(ssrc) === -1) {
+ return;
+ }
+
+ // Nuke all the related SSRCs.
relatedSsrcs.forEach(function (relatedSSRC) {
delete sources[relatedSSRC];
});
- // Schedule the related group for nuking.
- relatedGroup.nuke = true;
- })
+ // Schedule the related group for nuking.
+ relatedGroup.nuke = true;
+ })
+ }
+
+ return;
+ });
+
+ mLine.ssrcs = writeSsrcs(sources);
+
+ // Nuke all the scheduled groups.
+ var i = mLine.ssrcGroups.length;
+ while (i--) {
+ if (mLine.ssrcGroups[i].nuke) {
+ mLine.ssrcGroups.splice(i, 1);
+ }
+ }
+}
+
+function removeGoogConference(mLine) {
+ if (!mLine || !Array.isArray(mLine.invalid)) {
+ return;
+ }
+
+ var i = mLine.invalid.length;
+ while (i--) {
+ if (mLine.invalid[i].value == 'x-google-flag:conference') {
+ mLine.invalid.splice(i, 1);
+ }
+ }
+}
+
+function assertGoogConference(mLine) {
+ if (!mLine) {
+ return;
+ }
+
+ if (!Array.isArray(mLine.invalid)) {
+ mLine.invalid = [];
+ }
+
+ if (!mLine.invalid.some(
+ function (i) { return i.value === 'x-google-flag:conference' })) {
+ mLine.invalid.push({'value': 'x-google-flag:conference'});
+ }
+}
+
+//endregion
+
+//region "Private" functions
+
+/**
+ *
+ * @param mLine
+ * @private
+ */
+Simulcast.prototype._maybeInitializeLayers = function(mLine) {
+
+ if (!mLine || mLine.type !== 'video') {
+ return;
+ }
+
+ var sources = parseSsrcs(mLine);
+
+ if (Object.keys(sources).length === 0) {
+
+ // no sources, disable simulcast.
+ if (this.layers.length !== 0) {
+ this.layers = [];
+ }
+
+ return;
+ }
+
+ // find the base layer (we'll reuse its msid and cname).
+ var baseLayerSSRC = Object.keys(sources)[0];
+ var baseLayer = sources[baseLayerSSRC];
+
+ // todo(gp) handle screen sharing.
+
+ // check if base CNAME has changed and reinitialise layers.
+ if (this.layers.length > 0
+ && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
+ this.layers = [];
+ }
+
+ // (re)initialise layers
+ if (this.layers.length < 1) {
+
+ // first push the base layer.
+ this.layers.push({
+ ssrc: baseLayerSSRC,
+ msid: baseLayer.msid,
+ cname: baseLayer.cname
+ });
+
+ var rtx = false; // RFC 4588
+ if (Array.isArray(mLine.rtp)) {
+ rtx = mLine.rtp.some(
+ function (rtpmap) { return rtpmap.codec === 'rtx'; });
+ }
+
+ if (rtx) {
+ this.layers[0].rtx = generateSSRC();
+ }
+
+ // now push additional layers.
+ for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
+
+ var layer = { ssrc: generateSSRC() };
+ if (rtx) {
+ layer.rtx = generateSSRC();
+ }
+
+ this.layers.push(layer);
+ }
+ }
+};
+
+/**
+ *
+ * @param mLine
+ * @private
+ */
+Simulcast.prototype._restoreSimulcastView = function(mLine) {
+ if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
+
+ var sources = {};
+
+ var msid = this.layers[0].msid;
+ var cname = this.layers[0].cname;
+ var simulcastSsrcs = [];
+ var ssrcGroups = [];
+
+ for (var i = 0; i < this.layers.length; i++) {
+ var layer = this.layers[i];
+
+ sources[layer.ssrc] = { msid: msid, cname: cname };
+ simulcastSsrcs.push(layer.ssrc);
+
+ if (layer.rtx) {
+
+ sources[layer.rtx] = {
+ msid: msid,
+ cname: cname
+ }
+
+ ssrcGroups.push({
+ semantics: 'FID',
+ ssrcs: [layer.ssrc, layer.rtx].join(' ')
+ });
+ }
+ }
+
+ ssrcGroups.push({
+ semantics: 'SIM',
+ ssrcs: simulcastSsrcs.join(' ')
+ });
+
+ mLine.ssrcGroups = ssrcGroups;
+ mLine.ssrcs = writeSsrcs(sources);
+ }
+}
+
+//endregion
+
+//region "Public" functions
+
+Simulcast.prototype.isSupported = function () {
+ return window.chrome;
+
+ // TODO this needs improvements. For example I doubt that Chrome in Android
+ // has simulcast support. Also, only recent versions of Chromium have native
+ // simulcast support.
+}
+
+/**
+ *
+ * @param desc
+ * @returns {RTCSessionDescription}
+ */
+Simulcast.prototype.mungeRemoteDescription = function (desc) {
+
+ if (!validateDescription(desc)) {
+ return desc;
+ }
+
+ var session = transform.parse(desc.sdp);
+
+ var self = this;
+ processVideo(session, function (mLine) {
+
+ // Handle simulcast reception.
+ if (self.options.explodeRemoteSimulcast) {
+ explodeRemoteSimulcast(mLine);
+ } else {
+ implodeRemoteSimulcast(mLine);
+ }
+
+ // If native simulcast is enabled, we must append the x-goog-conference
+ // attribute to the SDP.
+ if (self.layers.length < 1) {
+ removeGoogConference(mLine);
+ } else {
+ assertGoogConference(mLine);
+ }
+ });
+
+ return new RTCSessionDescription({
+ type: desc.type,
+ sdp: transform.write(session)
+ });
+};
+
+/**
+ *
+ * @param desc
+ * @returns {RTCSessionDescription}
+ */
+Simulcast.prototype.mungeLocalDescription = function (desc) {
+
+ if (!validateDescription(desc) || !this.isSupported()) {
+ return desc;
+ }
+
+ var session = transform.parse(desc.sdp);
+
+ var self = this;
+ processVideo(session, function (mLine) {
+ if (mLine.direction == 'recvonly' || mLine.direction == 'inactive')
+ {
+ return;
+ }
+ // Initialize native simulcast layers, if not already done.
+ self._maybeInitializeLayers(mLine);
+
+ // Update the SDP with the simulcast layers.
+ self._restoreSimulcastView(mLine);
+ });
+
+ return new RTCSessionDescription({
+ type: desc.type,
+ sdp: transform.write(session)
+ });
+};
+
+//endregion
+
+module.exports = Simulcast;
+
+},{"./transform-utils":76,"sdp-transform":78}],76:[function(require,module,exports){
+/* Copyright @ 2015 Atlassian Pty Ltd
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+exports.writeSsrcs = function(sources, order) {
+ var ssrcs = [];
+
+ // expand sources to ssrcs
+ if (typeof sources !== 'undefined' &&
+ Object.keys(sources).length !== 0) {
+
+ if (Array.isArray(order)) {
+ for (var i = 0; i < order.length; i++) {
+ var ssrc = order[i];
+ var source = sources[ssrc];
+ Object.keys(source).forEach(function (attribute) {
+ ssrcs.push({
+ id: ssrc,
+ attribute: attribute,
+ value: source[attribute]
+ });
+ });
+ }
+ } else {
+ Object.keys(sources).forEach(function (ssrc) {
+ var source = sources[ssrc];
+ Object.keys(source).forEach(function (attribute) {
+ ssrcs.push({
+ id: ssrc,
+ attribute: attribute,
+ value: source[attribute]
+ });
+ });
+ });
+ }
+ }
+
+ return ssrcs;
+};
+
+exports.parseSsrcs = function (mLine) {
+ var sources = {};
+ // group sources attributes by ssrc.
+ if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
+ mLine.ssrcs.forEach(function (ssrc) {
+ if (!sources[ssrc.id])
+ sources[ssrc.id] = {};
+ sources[ssrc.id][ssrc.attribute] = ssrc.value;
+ });
+ }
+ return sources;
+};
+
+
+},{}],77:[function(require,module,exports){
+arguments[4][71][0].apply(exports,arguments)
+},{"dup":71}],78:[function(require,module,exports){
+arguments[4][72][0].apply(exports,arguments)
+},{"./parser":79,"./writer":80,"dup":72}],79:[function(require,module,exports){
+arguments[4][73][0].apply(exports,arguments)
+},{"./grammar":77,"dup":73}],80:[function(require,module,exports){
+arguments[4][74][0].apply(exports,arguments)
+},{"./grammar":77,"dup":74}],81:[function(require,module,exports){
+
+module.exports = require('./lib/');
+
+},{"./lib/":82}],82:[function(require,module,exports){
+
+/**
+ * Module dependencies.
+ */
+
+var url = require('./url');
+var parser = require('socket.io-parser');
+var Manager = require('./manager');
+var debug = require('debug')('socket.io-client');
+
+/**
+ * Module exports.
+ */
+
+module.exports = exports = lookup;
+
+/**
+ * Managers cache.
+ */
+
+var cache = exports.managers = {};
+
+/**
+ * Looks up an existing `Manager` for multiplexing.
+ * If the user summons:
+ *
+ * `io('http://localhost/a');`
+ * `io('http://localhost/b');`
+ *
+ * We reuse the existing instance based on same scheme/port/host,
+ * and we initialize sockets for each namespace.
+ *
+ * @api public
+ */
+
+function lookup(uri, opts) {
+ if (typeof uri == 'object') {
+ opts = uri;
+ uri = undefined;
+ }
+
+ opts = opts || {};
+
+ var parsed = url(uri);
+ var source = parsed.source;
+ var id = parsed.id;
+ var io;
+
+ if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
+ debug('ignoring socket cache for %s', source);
+ io = Manager(source, opts);
+ } else {
+ if (!cache[id]) {
+ debug('new io instance for %s', source);
+ cache[id] = Manager(source, opts);
+ }
+ io = cache[id];
+ }
+
+ return io.socket(parsed.path);
+}
+
+/**
+ * Protocol version.
+ *
+ * @api public
+ */
+
+exports.protocol = parser.protocol;
+
+/**
+ * `connect`.
+ *
+ * @param {String} uri
+ * @api public
+ */
+
+exports.connect = lookup;
+
+/**
+ * Expose constructors for standalone build.
+ *
+ * @api public
+ */
+
+exports.Manager = require('./manager');
+exports.Socket = require('./socket');
+
+},{"./manager":83,"./socket":85,"./url":86,"debug":90,"socket.io-parser":126}],83:[function(require,module,exports){
+
+/**
+ * Module dependencies.
+ */
+
+var url = require('./url');
+var eio = require('engine.io-client');
+var Socket = require('./socket');
+var Emitter = require('component-emitter');
+var parser = require('socket.io-parser');
+var on = require('./on');
+var bind = require('component-bind');
+var object = require('object-component');
+var debug = require('debug')('socket.io-client:manager');
+var indexOf = require('indexof');
+var Backoff = require('backo2');
+
+/**
+ * Module exports
+ */
+
+module.exports = Manager;
+
+/**
+ * `Manager` constructor.
+ *
+ * @param {String} engine instance or engine uri/opts
+ * @param {Object} options
+ * @api public
+ */
+
+function Manager(uri, opts){
+ if (!(this instanceof Manager)) return new Manager(uri, opts);
+ if (uri && ('object' == typeof uri)) {
+ opts = uri;
+ uri = undefined;
+ }
+ opts = opts || {};
+
+ opts.path = opts.path || '/socket.io';
+ this.nsps = {};
+ this.subs = [];
+ this.opts = opts;
+ this.reconnection(opts.reconnection !== false);
+ this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
+ this.reconnectionDelay(opts.reconnectionDelay || 1000);
+ this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
+ this.randomizationFactor(opts.randomizationFactor || 0.5);
+ this.backoff = new Backoff({
+ min: this.reconnectionDelay(),
+ max: this.reconnectionDelayMax(),
+ jitter: this.randomizationFactor()
+ });
+ this.timeout(null == opts.timeout ? 20000 : opts.timeout);
+ this.readyState = 'closed';
+ this.uri = uri;
+ this.connected = [];
+ this.encoding = false;
+ this.packetBuffer = [];
+ this.encoder = new parser.Encoder();
+ this.decoder = new parser.Decoder();
+ this.autoConnect = opts.autoConnect !== false;
+ if (this.autoConnect) this.open();
+}
+
+/**
+ * Propagate given event to sockets and emit on `this`
+ *
+ * @api private
+ */
+
+Manager.prototype.emitAll = function() {
+ this.emit.apply(this, arguments);
+ for (var nsp in this.nsps) {
+ this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
+ }
+};
+
+/**
+ * Update `socket.id` of all sockets
+ *
+ * @api private
+ */
+
+Manager.prototype.updateSocketIds = function(){
+ for (var nsp in this.nsps) {
+ this.nsps[nsp].id = this.engine.id;
+ }
+};
+
+/**
+ * Mix in `Emitter`.
+ */
+
+Emitter(Manager.prototype);
+
+/**
+ * Sets the `reconnection` config.
+ *
+ * @param {Boolean} true/false if it should automatically reconnect
+ * @return {Manager} self or value
+ * @api public
+ */
+
+Manager.prototype.reconnection = function(v){
+ if (!arguments.length) return this._reconnection;
+ this._reconnection = !!v;
+ return this;
+};
+
+/**
+ * Sets the reconnection attempts config.
+ *
+ * @param {Number} max reconnection attempts before giving up
+ * @return {Manager} self or value
+ * @api public
+ */
+
+Manager.prototype.reconnectionAttempts = function(v){
+ if (!arguments.length) return this._reconnectionAttempts;
+ this._reconnectionAttempts = v;
+ return this;
+};
+
+/**
+ * Sets the delay between reconnections.
+ *
+ * @param {Number} delay
+ * @return {Manager} self or value
+ * @api public
+ */
+
+Manager.prototype.reconnectionDelay = function(v){
+ if (!arguments.length) return this._reconnectionDelay;
+ this._reconnectionDelay = v;
+ this.backoff && this.backoff.setMin(v);
+ return this;
+};
+
+Manager.prototype.randomizationFactor = function(v){
+ if (!arguments.length) return this._randomizationFactor;
+ this._randomizationFactor = v;
+ this.backoff && this.backoff.setJitter(v);
+ return this;
+};
+
+/**
+ * Sets the maximum delay between reconnections.
+ *
+ * @param {Number} delay
+ * @return {Manager} self or value
+ * @api public
+ */
+
+Manager.prototype.reconnectionDelayMax = function(v){
+ if (!arguments.length) return this._reconnectionDelayMax;
+ this._reconnectionDelayMax = v;
+ this.backoff && this.backoff.setMax(v);
+ return this;
+};
+
+/**
+ * Sets the connection timeout. `false` to disable
+ *
+ * @return {Manager} self or value
+ * @api public
+ */
+
+Manager.prototype.timeout = function(v){
+ if (!arguments.length) return this._timeout;
+ this._timeout = v;
+ return this;
+};
+
+/**
+ * Starts trying to reconnect if reconnection is enabled and we have not
+ * started reconnecting yet
+ *
+ * @api private
+ */
+
+Manager.prototype.maybeReconnectOnOpen = function() {
+ // Only try to reconnect if it's the first time we're connecting
+ if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
+ // keeps reconnection from firing twice for the same reconnection loop
+ this.reconnect();
+ }
+};
+
+
+/**
+ * Sets the current transport `socket`.
+ *
+ * @param {Function} optional, callback
+ * @return {Manager} self
+ * @api public
+ */
+
+Manager.prototype.open =
+Manager.prototype.connect = function(fn){
+ debug('readyState %s', this.readyState);
+ if (~this.readyState.indexOf('open')) return this;
+
+ debug('opening %s', this.uri);
+ this.engine = eio(this.uri, this.opts);
+ var socket = this.engine;
+ var self = this;
+ this.readyState = 'opening';
+ this.skipReconnect = false;
+
+ // emit `open`
+ var openSub = on(socket, 'open', function() {
+ self.onopen();
+ fn && fn();
+ });
+
+ // emit `connect_error`
+ var errorSub = on(socket, 'error', function(data){
+ debug('connect_error');
+ self.cleanup();
+ self.readyState = 'closed';
+ self.emitAll('connect_error', data);
+ if (fn) {
+ var err = new Error('Connection error');
+ err.data = data;
+ fn(err);
+ } else {
+ // Only do this if there is no fn to handle the error
+ self.maybeReconnectOnOpen();
+ }
+ });
+
+ // emit `connect_timeout`
+ if (false !== this._timeout) {
+ var timeout = this._timeout;
+ debug('connect attempt will timeout after %d', timeout);
+
+ // set timer
+ var timer = setTimeout(function(){
+ debug('connect attempt timed out after %d', timeout);
+ openSub.destroy();
+ socket.close();
+ socket.emit('error', 'timeout');
+ self.emitAll('connect_timeout', timeout);
+ }, timeout);
+
+ this.subs.push({
+ destroy: function(){
+ clearTimeout(timer);
+ }
+ });
+ }
+
+ this.subs.push(openSub);
+ this.subs.push(errorSub);
+
+ return this;
+};
+
+/**
+ * Called upon transport open.
+ *
+ * @api private
+ */
+
+Manager.prototype.onopen = function(){
+ debug('open');
+
+ // clear old subs
+ this.cleanup();
+
+ // mark as open
+ this.readyState = 'open';
+ this.emit('open');
+
+ // add new subs
+ var socket = this.engine;
+ this.subs.push(on(socket, 'data', bind(this, 'ondata')));
+ this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
+ this.subs.push(on(socket, 'error', bind(this, 'onerror')));
+ this.subs.push(on(socket, 'close', bind(this, 'onclose')));
+};
+
+/**
+ * Called with data.
+ *
+ * @api private
+ */
+
+Manager.prototype.ondata = function(data){
+ this.decoder.add(data);
+};
+
+/**
+ * Called when parser fully decodes a packet.
+ *
+ * @api private
+ */
+
+Manager.prototype.ondecoded = function(packet) {
+ this.emit('packet', packet);
+};
+
+/**
+ * Called upon socket error.
+ *
+ * @api private
+ */
+
+Manager.prototype.onerror = function(err){
+ debug('error', err);
+ this.emitAll('error', err);
+};
+
+/**
+ * Creates a new socket for the given `nsp`.
+ *
+ * @return {Socket}
+ * @api public
+ */
+
+Manager.prototype.socket = function(nsp){
+ var socket = this.nsps[nsp];
+ if (!socket) {
+ socket = new Socket(this, nsp);
+ this.nsps[nsp] = socket;
+ var self = this;
+ socket.on('connect', function(){
+ socket.id = self.engine.id;
+ if (!~indexOf(self.connected, socket)) {
+ self.connected.push(socket);
+ }
+ });
+ }
+ return socket;
+};
+
+/**
+ * Called upon a socket close.
+ *
+ * @param {Socket} socket
+ */
+
+Manager.prototype.destroy = function(socket){
+ var index = indexOf(this.connected, socket);
+ if (~index) this.connected.splice(index, 1);
+ if (this.connected.length) return;
+
+ this.close();
+};
+
+/**
+ * Writes a packet.
+ *
+ * @param {Object} packet
+ * @api private
+ */
+
+Manager.prototype.packet = function(packet){
+ debug('writing packet %j', packet);
+ var self = this;
+
+ if (!self.encoding) {
+ // encode, then write to engine with result
+ self.encoding = true;
+ this.encoder.encode(packet, function(encodedPackets) {
+ for (var i = 0; i < encodedPackets.length; i++) {
+ self.engine.write(encodedPackets[i]);
+ }
+ self.encoding = false;
+ self.processPacketQueue();
+ });
+ } else { // add packet to the queue
+ self.packetBuffer.push(packet);
+ }
+};
+
+/**
+ * If packet buffer is non-empty, begins encoding the
+ * next packet in line.
+ *
+ * @api private
+ */
+
+Manager.prototype.processPacketQueue = function() {
+ if (this.packetBuffer.length > 0 && !this.encoding) {
+ var pack = this.packetBuffer.shift();
+ this.packet(pack);
+ }
+};
+
+/**
+ * Clean up transport subscriptions and packet buffer.
+ *
+ * @api private
+ */
+
+Manager.prototype.cleanup = function(){
+ var sub;
+ while (sub = this.subs.shift()) sub.destroy();
+
+ this.packetBuffer = [];
+ this.encoding = false;
+
+ this.decoder.destroy();
+};
+
+/**
+ * Close the current socket.
+ *
+ * @api private
+ */
+
+Manager.prototype.close =
+Manager.prototype.disconnect = function(){
+ this.skipReconnect = true;
+ this.backoff.reset();
+ this.readyState = 'closed';
+ this.engine && this.engine.close();
+};
+
+/**
+ * Called upon engine close.
+ *
+ * @api private
+ */
+
+Manager.prototype.onclose = function(reason){
+ debug('close');
+ this.cleanup();
+ this.backoff.reset();
+ this.readyState = 'closed';
+ this.emit('close', reason);
+ if (this._reconnection && !this.skipReconnect) {
+ this.reconnect();
+ }
+};
+
+/**
+ * Attempt a reconnection.
+ *
+ * @api private
+ */
+
+Manager.prototype.reconnect = function(){
+ if (this.reconnecting || this.skipReconnect) return this;
+
+ var self = this;
+
+ if (this.backoff.attempts >= this._reconnectionAttempts) {
+ debug('reconnect failed');
+ this.backoff.reset();
+ this.emitAll('reconnect_failed');
+ this.reconnecting = false;
+ } else {
+ var delay = this.backoff.duration();
+ debug('will wait %dms before reconnect attempt', delay);
+
+ this.reconnecting = true;
+ var timer = setTimeout(function(){
+ if (self.skipReconnect) return;
+
+ debug('attempting reconnect');
+ self.emitAll('reconnect_attempt', self.backoff.attempts);
+ self.emitAll('reconnecting', self.backoff.attempts);
+
+ // check again for the case socket closed in above events
+ if (self.skipReconnect) return;
+
+ self.open(function(err){
+ if (err) {
+ debug('reconnect attempt error');
+ self.reconnecting = false;
+ self.reconnect();
+ self.emitAll('reconnect_error', err.data);
+ } else {
+ debug('reconnect success');
+ self.onreconnect();
+ }
+ });
+ }, delay);
+
+ this.subs.push({
+ destroy: function(){
+ clearTimeout(timer);
+ }
+ });
+ }
+};
+
+/**
+ * Called upon successful reconnect.
+ *
+ * @api private
+ */
+
+Manager.prototype.onreconnect = function(){
+ var attempt = this.backoff.attempts;
+ this.reconnecting = false;
+ this.backoff.reset();
+ this.updateSocketIds();
+ this.emitAll('reconnect', attempt);
+};
+
+},{"./on":84,"./socket":85,"./url":86,"backo2":87,"component-bind":88,"component-emitter":89,"debug":90,"engine.io-client":91,"indexof":122,"object-component":123,"socket.io-parser":126}],84:[function(require,module,exports){
+
+/**
+ * Module exports.
+ */
+
+module.exports = on;
+
+/**
+ * Helper for subscriptions.
+ *
+ * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
+ * @param {String} event name
+ * @param {Function} callback
+ * @api public
+ */
+
+function on(obj, ev, fn) {
+ obj.on(ev, fn);
+ return {
+ destroy: function(){
+ obj.removeListener(ev, fn);
+ }
+ };
+}
+
+},{}],85:[function(require,module,exports){
+
+/**
+ * Module dependencies.
+ */
+
+var parser = require('socket.io-parser');
+var Emitter = require('component-emitter');
+var toArray = require('to-array');
+var on = require('./on');
+var bind = require('component-bind');
+var debug = require('debug')('socket.io-client:socket');
+var hasBin = require('has-binary');
+
+/**
+ * Module exports.
+ */
+
+module.exports = exports = Socket;
+
+/**
+ * Internal events (blacklisted).
+ * These events can't be emitted by the user.
+ *
+ * @api private
+ */
+
+var events = {
+ connect: 1,
+ connect_error: 1,
+ connect_timeout: 1,
+ disconnect: 1,
+ error: 1,
+ reconnect: 1,
+ reconnect_attempt: 1,
+ reconnect_failed: 1,
+ reconnect_error: 1,
+ reconnecting: 1
+};
+
+/**
+ * Shortcut to `Emitter#emit`.
+ */
+
+var emit = Emitter.prototype.emit;
+
+/**
+ * `Socket` constructor.
+ *
+ * @api public
+ */
+
+function Socket(io, nsp){
+ this.io = io;
+ this.nsp = nsp;
+ this.json = this; // compat
+ this.ids = 0;
+ this.acks = {};
+ if (this.io.autoConnect) this.open();
+ this.receiveBuffer = [];
+ this.sendBuffer = [];
+ this.connected = false;
+ this.disconnected = true;
+}
+
+/**
+ * Mix in `Emitter`.
+ */
+
+Emitter(Socket.prototype);
+
+/**
+ * Subscribe to open, close and packet events
+ *
+ * @api private
+ */
+
+Socket.prototype.subEvents = function() {
+ if (this.subs) return;
+
+ var io = this.io;
+ this.subs = [
+ on(io, 'open', bind(this, 'onopen')),
+ on(io, 'packet', bind(this, 'onpacket')),
+ on(io, 'close', bind(this, 'onclose'))
+ ];
+};
+
+/**
+ * "Opens" the socket.
+ *
+ * @api public
+ */
+
+Socket.prototype.open =
+Socket.prototype.connect = function(){
+ if (this.connected) return this;
+
+ this.subEvents();
+ this.io.open(); // ensure open
+ if ('open' == this.io.readyState) this.onopen();
+ return this;
+};
+
+/**
+ * Sends a `message` event.
+ *
+ * @return {Socket} self
+ * @api public
+ */
+
+Socket.prototype.send = function(){
+ var args = toArray(arguments);
+ args.unshift('message');
+ this.emit.apply(this, args);
+ return this;
+};
+
+/**
+ * Override `emit`.
+ * If the event is in `events`, it's emitted normally.
+ *
+ * @param {String} event name
+ * @return {Socket} self
+ * @api public
+ */
+
+Socket.prototype.emit = function(ev){
+ if (events.hasOwnProperty(ev)) {
+ emit.apply(this, arguments);
+ return this;
+ }
+
+ var args = toArray(arguments);
+ var parserType = parser.EVENT; // default
+ if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
+ var packet = { type: parserType, data: args };
+
+ // event ack callback
+ if ('function' == typeof args[args.length - 1]) {
+ debug('emitting packet with ack id %d', this.ids);
+ this.acks[this.ids] = args.pop();
+ packet.id = this.ids++;
+ }
+
+ if (this.connected) {
+ this.packet(packet);
+ } else {
+ this.sendBuffer.push(packet);
+ }
+
+ return this;
+};
+
+/**
+ * Sends a packet.
+ *
+ * @param {Object} packet
+ * @api private
+ */
+
+Socket.prototype.packet = function(packet){
+ packet.nsp = this.nsp;
+ this.io.packet(packet);
+};
+
+/**
+ * Called upon engine `open`.
+ *
+ * @api private
+ */
+
+Socket.prototype.onopen = function(){
+ debug('transport is open - connecting');
+
+ // write connect packet if necessary
+ if ('/' != this.nsp) {
+ this.packet({ type: parser.CONNECT });
+ }
+};
+
+/**
+ * Called upon engine `close`.
+ *
+ * @param {String} reason
+ * @api private
+ */
+
+Socket.prototype.onclose = function(reason){
+ debug('close (%s)', reason);
+ this.connected = false;
+ this.disconnected = true;
+ delete this.id;
+ this.emit('disconnect', reason);
+};
+
+/**
+ * Called with socket packet.
+ *
+ * @param {Object} packet
+ * @api private
+ */
+
+Socket.prototype.onpacket = function(packet){
+ if (packet.nsp != this.nsp) return;
+
+ switch (packet.type) {
+ case parser.CONNECT:
+ this.onconnect();
+ break;
+
+ case parser.EVENT:
+ this.onevent(packet);
+ break;
+
+ case parser.BINARY_EVENT:
+ this.onevent(packet);
+ break;
+
+ case parser.ACK:
+ this.onack(packet);
+ break;
+
+ case parser.BINARY_ACK:
+ this.onack(packet);
+ break;
+
+ case parser.DISCONNECT:
+ this.ondisconnect();
+ break;
+
+ case parser.ERROR:
+ this.emit('error', packet.data);
+ break;
+ }
+};
+
+/**
+ * Called upon a server event.
+ *
+ * @param {Object} packet
+ * @api private
+ */
+
+Socket.prototype.onevent = function(packet){
+ var args = packet.data || [];
+ debug('emitting event %j', args);
+
+ if (null != packet.id) {
+ debug('attaching ack callback to event');
+ args.push(this.ack(packet.id));
+ }
+
+ if (this.connected) {
+ emit.apply(this, args);
+ } else {
+ this.receiveBuffer.push(args);
+ }
+};
+
+/**
+ * Produces an ack callback to emit with an event.
+ *
+ * @api private
+ */
+
+Socket.prototype.ack = function(id){
+ var self = this;
+ var sent = false;
+ return function(){
+ // prevent double callbacks
+ if (sent) return;
+ sent = true;
+ var args = toArray(arguments);
+ debug('sending ack %j', args);
+
+ var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
+ self.packet({
+ type: type,
+ id: id,
+ data: args
+ });
+ };
+};
+
+/**
+ * Called upon a server acknowlegement.
+ *
+ * @param {Object} packet
+ * @api private
+ */
+
+Socket.prototype.onack = function(packet){
+ debug('calling ack %s with %j', packet.id, packet.data);
+ var fn = this.acks[packet.id];
+ fn.apply(this, packet.data);
+ delete this.acks[packet.id];
+};
+
+/**
+ * Called upon server connect.
+ *
+ * @api private
+ */
+
+Socket.prototype.onconnect = function(){
+ this.connected = true;
+ this.disconnected = false;
+ this.emit('connect');
+ this.emitBuffered();
+};
+
+/**
+ * Emit buffered events (received and emitted).
+ *
+ * @api private
+ */
+
+Socket.prototype.emitBuffered = function(){
+ var i;
+ for (i = 0; i < this.receiveBuffer.length; i++) {
+ emit.apply(this, this.receiveBuffer[i]);
+ }
+ this.receiveBuffer = [];
+
+ for (i = 0; i < this.sendBuffer.length; i++) {
+ this.packet(this.sendBuffer[i]);
+ }
+ this.sendBuffer = [];
+};
+
+/**
+ * Called upon server disconnect.
+ *
+ * @api private
+ */
+
+Socket.prototype.ondisconnect = function(){
+ debug('server disconnect (%s)', this.nsp);
+ this.destroy();
+ this.onclose('io server disconnect');
+};
+
+/**
+ * Called upon forced client/server side disconnections,
+ * this method ensures the manager stops tracking us and
+ * that reconnections don't get triggered for this.
+ *
+ * @api private.
+ */
+
+Socket.prototype.destroy = function(){
+ if (this.subs) {
+ // clean subscriptions to avoid reconnections
+ for (var i = 0; i < this.subs.length; i++) {
+ this.subs[i].destroy();
+ }
+ this.subs = null;
+ }
+
+ this.io.destroy(this);
+};
+
+/**
+ * Disconnects the socket manually.
+ *
+ * @return {Socket} self
+ * @api public
+ */
+
+Socket.prototype.close =
+Socket.prototype.disconnect = function(){
+ if (this.connected) {
+ debug('performing disconnect (%s)', this.nsp);
+ this.packet({ type: parser.DISCONNECT });
+ }
+
+ // remove socket from pool
+ this.destroy();
+
+ if (this.connected) {
+ // fire events
+ this.onclose('io client disconnect');
+ }
+ return this;
+};
+
+},{"./on":84,"component-bind":88,"component-emitter":89,"debug":90,"has-binary":120,"socket.io-parser":126,"to-array":130}],86:[function(require,module,exports){
+(function (global){
+
+/**
+ * Module dependencies.
+ */
+
+var parseuri = require('parseuri');
+var debug = require('debug')('socket.io-client:url');
+
+/**
+ * Module exports.
+ */
+
+module.exports = url;
+
+/**
+ * URL parser.
+ *
+ * @param {String} url
+ * @param {Object} An object meant to mimic window.location.
+ * Defaults to window.location.
+ * @api public
+ */
+
+function url(uri, loc){
+ var obj = uri;
+
+ // default to window.location
+ var loc = loc || global.location;
+ if (null == uri) uri = loc.protocol + '//' + loc.host;
+
+ // relative path support
+ if ('string' == typeof uri) {
+ if ('/' == uri.charAt(0)) {
+ if ('/' == uri.charAt(1)) {
+ uri = loc.protocol + uri;
+ } else {
+ uri = loc.hostname + uri;
+ }
+ }
+
+ if (!/^(https?|wss?):\/\//.test(uri)) {
+ debug('protocol-less url %s', uri);
+ if ('undefined' != typeof loc) {
+ uri = loc.protocol + '//' + uri;
+ } else {
+ uri = 'https://' + uri;
+ }
+ }
+
+ // parse
+ debug('parse %s', uri);
+ obj = parseuri(uri);
+ }
+
+ // make sure we treat `localhost:80` and `localhost` equally
+ if (!obj.port) {
+ if (/^(http|ws)$/.test(obj.protocol)) {
+ obj.port = '80';
+ }
+ else if (/^(http|ws)s$/.test(obj.protocol)) {
+ obj.port = '443';
+ }
+ }
+
+ obj.path = obj.path || '/';
+
+ // define unique id
+ obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
+ // define href
+ obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
+
+ return obj;
+}
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"debug":90,"parseuri":124}],87:[function(require,module,exports){
+
+/**
+ * Expose `Backoff`.
+ */
+
+module.exports = Backoff;
+
+/**
+ * Initialize backoff timer with `opts`.
+ *
+ * - `min` initial timeout in milliseconds [100]
+ * - `max` max timeout [10000]
+ * - `jitter` [0]
+ * - `factor` [2]
+ *
+ * @param {Object} opts
+ * @api public
+ */
+
+function Backoff(opts) {
+ opts = opts || {};
+ this.ms = opts.min || 100;
+ this.max = opts.max || 10000;
+ this.factor = opts.factor || 2;
+ this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
+ this.attempts = 0;
+}
+
+/**
+ * Return the backoff duration.
+ *
+ * @return {Number}
+ * @api public
+ */
+
+Backoff.prototype.duration = function(){
+ var ms = this.ms * Math.pow(this.factor, this.attempts++);
+ if (this.jitter) {
+ var rand = Math.random();
+ var deviation = Math.floor(rand * this.jitter * ms);
+ ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
+ }
+ return Math.min(ms, this.max) | 0;
+};
+
+/**
+ * Reset the number of attempts.
+ *
+ * @api public
+ */
+
+Backoff.prototype.reset = function(){
+ this.attempts = 0;
+};
+
+/**
+ * Set the minimum duration
+ *
+ * @api public
+ */
+
+Backoff.prototype.setMin = function(min){
+ this.ms = min;
+};
+
+/**
+ * Set the maximum duration
+ *
+ * @api public
+ */
+
+Backoff.prototype.setMax = function(max){
+ this.max = max;
+};
+
+/**
+ * Set the jitter
+ *
+ * @api public
+ */
+
+Backoff.prototype.setJitter = function(jitter){
+ this.jitter = jitter;
+};
+
+
+},{}],88:[function(require,module,exports){
+/**
+ * Slice reference.
+ */
+
+var slice = [].slice;
+
+/**
+ * Bind `obj` to `fn`.
+ *
+ * @param {Object} obj
+ * @param {Function|String} fn or string
+ * @return {Function}
+ * @api public
+ */
+
+module.exports = function(obj, fn){
+ if ('string' == typeof fn) fn = obj[fn];
+ if ('function' != typeof fn) throw new Error('bind() requires a function');
+ var args = slice.call(arguments, 2);
+ return function(){
+ return fn.apply(obj, args.concat(slice.call(arguments)));
+ }
+};
+
+},{}],89:[function(require,module,exports){
+
+/**
+ * Expose `Emitter`.
+ */
+
+module.exports = Emitter;
+
+/**
+ * Initialize a new `Emitter`.
+ *
+ * @api public
+ */
+
+function Emitter(obj) {
+ if (obj) return mixin(obj);
+};
+
+/**
+ * Mixin the emitter properties.
+ *
+ * @param {Object} obj
+ * @return {Object}
+ * @api private
+ */
+
+function mixin(obj) {
+ for (var key in Emitter.prototype) {
+ obj[key] = Emitter.prototype[key];
+ }
+ return obj;
+}
+
+/**
+ * Listen on the given `event` with `fn`.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.on =
+Emitter.prototype.addEventListener = function(event, fn){
+ this._callbacks = this._callbacks || {};
+ (this._callbacks[event] = this._callbacks[event] || [])
+ .push(fn);
+ return this;
+};
+
+/**
+ * Adds an `event` listener that will be invoked a single
+ * time then automatically removed.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.once = function(event, fn){
+ var self = this;
+ this._callbacks = this._callbacks || {};
+
+ function on() {
+ self.off(event, on);
+ fn.apply(this, arguments);
+ }
+
+ on.fn = fn;
+ this.on(event, on);
+ return this;
+};
+
+/**
+ * Remove the given callback for `event` or all
+ * registered callbacks.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.off =
+Emitter.prototype.removeListener =
+Emitter.prototype.removeAllListeners =
+Emitter.prototype.removeEventListener = function(event, fn){
+ this._callbacks = this._callbacks || {};
+
+ // all
+ if (0 == arguments.length) {
+ this._callbacks = {};
+ return this;
+ }
+
+ // specific event
+ var callbacks = this._callbacks[event];
+ if (!callbacks) return this;
+
+ // remove all handlers
+ if (1 == arguments.length) {
+ delete this._callbacks[event];
+ return this;
+ }
+
+ // remove specific handler
+ var cb;
+ for (var i = 0; i < callbacks.length; i++) {
+ cb = callbacks[i];
+ if (cb === fn || cb.fn === fn) {
+ callbacks.splice(i, 1);
+ break;
+ }
+ }
+ return this;
+};
+
+/**
+ * Emit `event` with the given args.
+ *
+ * @param {String} event
+ * @param {Mixed} ...
+ * @return {Emitter}
+ */
+
+Emitter.prototype.emit = function(event){
+ this._callbacks = this._callbacks || {};
+ var args = [].slice.call(arguments, 1)
+ , callbacks = this._callbacks[event];
+
+ if (callbacks) {
+ callbacks = callbacks.slice(0);
+ for (var i = 0, len = callbacks.length; i < len; ++i) {
+ callbacks[i].apply(this, args);
+ }
+ }
+
+ return this;
+};
+
+/**
+ * Return array of callbacks for `event`.
+ *
+ * @param {String} event
+ * @return {Array}
+ * @api public
+ */
+
+Emitter.prototype.listeners = function(event){
+ this._callbacks = this._callbacks || {};
+ return this._callbacks[event] || [];
+};
+
+/**
+ * Check if this emitter has `event` handlers.
+ *
+ * @param {String} event
+ * @return {Boolean}
+ * @api public
+ */
+
+Emitter.prototype.hasListeners = function(event){
+ return !! this.listeners(event).length;
+};
+
+},{}],90:[function(require,module,exports){
+
+/**
+ * Expose `debug()` as the module.
+ */
+
+module.exports = debug;
+
+/**
+ * Create a debugger with the given `name`.
+ *
+ * @param {String} name
+ * @return {Type}
+ * @api public
+ */
+
+function debug(name) {
+ if (!debug.enabled(name)) return function(){};
+
+ return function(fmt){
+ fmt = coerce(fmt);
+
+ var curr = new Date;
+ var ms = curr - (debug[name] || curr);
+ debug[name] = curr;
+
+ fmt = name
+ + ' '
+ + fmt
+ + ' +' + debug.humanize(ms);
+
+ // This hackery is required for IE8
+ // where `console.log` doesn't have 'apply'
+ window.console
+ && console.log
+ && Function.prototype.apply.call(console.log, console, arguments);
+ }
+}
+
+/**
+ * The currently active debug mode names.
+ */
+
+debug.names = [];
+debug.skips = [];
+
+/**
+ * Enables a debug mode by name. This can include modes
+ * separated by a colon and wildcards.
+ *
+ * @param {String} name
+ * @api public
+ */
+
+debug.enable = function(name) {
+ try {
+ localStorage.debug = name;
+ } catch(e){}
+
+ var split = (name || '').split(/[\s,]+/)
+ , len = split.length;
+
+ for (var i = 0; i < len; i++) {
+ name = split[i].replace('*', '.*?');
+ if (name[0] === '-') {
+ debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
+ }
+ else {
+ debug.names.push(new RegExp('^' + name + '$'));
+ }
+ }
+};
+
+/**
+ * Disable debug output.
+ *
+ * @api public
+ */
+
+debug.disable = function(){
+ debug.enable('');
+};
+
+/**
+ * Humanize the given `ms`.
+ *
+ * @param {Number} m
+ * @return {String}
+ * @api private
+ */
+
+debug.humanize = function(ms) {
+ var sec = 1000
+ , min = 60 * 1000
+ , hour = 60 * min;
+
+ if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
+ if (ms >= min) return (ms / min).toFixed(1) + 'm';
+ if (ms >= sec) return (ms / sec | 0) + 's';
+ return ms + 'ms';
+};
+
+/**
+ * Returns true if the given mode name is enabled, false otherwise.
+ *
+ * @param {String} name
+ * @return {Boolean}
+ * @api public
+ */
+
+debug.enabled = function(name) {
+ for (var i = 0, len = debug.skips.length; i < len; i++) {
+ if (debug.skips[i].test(name)) {
+ return false;
+ }
+ }
+ for (var i = 0, len = debug.names.length; i < len; i++) {
+ if (debug.names[i].test(name)) {
+ return true;
+ }
+ }
+ return false;
+};
+
+/**
+ * Coerce `val`.
+ */
+
+function coerce(val) {
+ if (val instanceof Error) return val.stack || val.message;
+ return val;
+}
+
+// persist
+
+try {
+ if (window.localStorage) debug.enable(localStorage.debug);
+} catch(e){}
+
+},{}],91:[function(require,module,exports){
+
+module.exports = require('./lib/');
+
+},{"./lib/":92}],92:[function(require,module,exports){
+
+module.exports = require('./socket');
+
+/**
+ * Exports parser
+ *
+ * @api public
+ *
+ */
+module.exports.parser = require('engine.io-parser');
+
+},{"./socket":93,"engine.io-parser":105}],93:[function(require,module,exports){
+(function (global){
+/**
+ * Module dependencies.
+ */
+
+var transports = require('./transports');
+var Emitter = require('component-emitter');
+var debug = require('debug')('engine.io-client:socket');
+var index = require('indexof');
+var parser = require('engine.io-parser');
+var parseuri = require('parseuri');
+var parsejson = require('parsejson');
+var parseqs = require('parseqs');
+
+/**
+ * Module exports.
+ */
+
+module.exports = Socket;
+
+/**
+ * Noop function.
+ *
+ * @api private
+ */
+
+function noop(){}
+
+/**
+ * Socket constructor.
+ *
+ * @param {String|Object} uri or options
+ * @param {Object} options
+ * @api public
+ */
+
+function Socket(uri, opts){
+ if (!(this instanceof Socket)) return new Socket(uri, opts);
+
+ opts = opts || {};
+
+ if (uri && 'object' == typeof uri) {
+ opts = uri;
+ uri = null;
+ }
+
+ if (uri) {
+ uri = parseuri(uri);
+ opts.host = uri.host;
+ opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
+ opts.port = uri.port;
+ if (uri.query) opts.query = uri.query;
+ }
+
+ this.secure = null != opts.secure ? opts.secure :
+ (global.location && 'https:' == location.protocol);
+
+ if (opts.host) {
+ var pieces = opts.host.split(':');
+ opts.hostname = pieces.shift();
+ if (pieces.length) {
+ opts.port = pieces.pop();
+ } else if (!opts.port) {
+ // if no port is specified manually, use the protocol default
+ opts.port = this.secure ? '443' : '80';
+ }
+ }
+
+ this.agent = opts.agent || false;
+ this.hostname = opts.hostname ||
+ (global.location ? location.hostname : 'localhost');
+ this.port = opts.port || (global.location && location.port ?
+ location.port :
+ (this.secure ? 443 : 80));
+ this.query = opts.query || {};
+ if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
+ this.upgrade = false !== opts.upgrade;
+ this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
+ this.forceJSONP = !!opts.forceJSONP;
+ this.jsonp = false !== opts.jsonp;
+ this.forceBase64 = !!opts.forceBase64;
+ this.enablesXDR = !!opts.enablesXDR;
+ this.timestampParam = opts.timestampParam || 't';
+ this.timestampRequests = opts.timestampRequests;
+ this.transports = opts.transports || ['polling', 'websocket'];
+ this.readyState = '';
+ this.writeBuffer = [];
+ this.callbackBuffer = [];
+ this.policyPort = opts.policyPort || 843;
+ this.rememberUpgrade = opts.rememberUpgrade || false;
+ this.binaryType = null;
+ this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
+
+ // SSL options for Node.js client
+ this.pfx = opts.pfx || null;
+ this.key = opts.key || null;
+ this.passphrase = opts.passphrase || null;
+ this.cert = opts.cert || null;
+ this.ca = opts.ca || null;
+ this.ciphers = opts.ciphers || null;
+ this.rejectUnauthorized = opts.rejectUnauthorized || null;
+
+ this.open();
+}
+
+Socket.priorWebsocketSuccess = false;
+
+/**
+ * Mix in `Emitter`.
+ */
+
+Emitter(Socket.prototype);
+
+/**
+ * Protocol version.
+ *
+ * @api public
+ */
+
+Socket.protocol = parser.protocol; // this is an int
+
+/**
+ * Expose deps for legacy compatibility
+ * and standalone browser access.
+ */
+
+Socket.Socket = Socket;
+Socket.Transport = require('./transport');
+Socket.transports = require('./transports');
+Socket.parser = require('engine.io-parser');
+
+/**
+ * Creates transport of the given type.
+ *
+ * @param {String} transport name
+ * @return {Transport}
+ * @api private
+ */
+
+Socket.prototype.createTransport = function (name) {
+ debug('creating transport "%s"', name);
+ var query = clone(this.query);
+
+ // append engine.io protocol identifier
+ query.EIO = parser.protocol;
+
+ // transport name
+ query.transport = name;
+
+ // session id if we already have one
+ if (this.id) query.sid = this.id;
+
+ var transport = new transports[name]({
+ agent: this.agent,
+ hostname: this.hostname,
+ port: this.port,
+ secure: this.secure,
+ path: this.path,
+ query: query,
+ forceJSONP: this.forceJSONP,
+ jsonp: this.jsonp,
+ forceBase64: this.forceBase64,
+ enablesXDR: this.enablesXDR,
+ timestampRequests: this.timestampRequests,
+ timestampParam: this.timestampParam,
+ policyPort: this.policyPort,
+ socket: this,
+ pfx: this.pfx,
+ key: this.key,
+ passphrase: this.passphrase,
+ cert: this.cert,
+ ca: this.ca,
+ ciphers: this.ciphers,
+ rejectUnauthorized: this.rejectUnauthorized
+ });
+
+ return transport;
+};
+
+function clone (obj) {
+ var o = {};
+ for (var i in obj) {
+ if (obj.hasOwnProperty(i)) {
+ o[i] = obj[i];
+ }
+ }
+ return o;
+}
+
+/**
+ * Initializes transport to use and starts probe.
+ *
+ * @api private
+ */
+Socket.prototype.open = function () {
+ var transport;
+ if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
+ transport = 'websocket';
+ } else if (0 == this.transports.length) {
+ // Emit error on next tick so it can be listened to
+ var self = this;
+ setTimeout(function() {
+ self.emit('error', 'No transports available');
+ }, 0);
+ return;
+ } else {
+ transport = this.transports[0];
+ }
+ this.readyState = 'opening';
+
+ // Retry with the next transport if the transport is disabled (jsonp: false)
+ var transport;
+ try {
+ transport = this.createTransport(transport);
+ } catch (e) {
+ this.transports.shift();
+ this.open();
+ return;
+ }
+
+ transport.open();
+ this.setTransport(transport);
+};
+
+/**
+ * Sets the current transport. Disables the existing one (if any).
+ *
+ * @api private
+ */
+
+Socket.prototype.setTransport = function(transport){
+ debug('setting transport %s', transport.name);
+ var self = this;
+
+ if (this.transport) {
+ debug('clearing existing transport %s', this.transport.name);
+ this.transport.removeAllListeners();
+ }
+
+ // set up transport
+ this.transport = transport;
+
+ // set up transport listeners
+ transport
+ .on('drain', function(){
+ self.onDrain();
+ })
+ .on('packet', function(packet){
+ self.onPacket(packet);
+ })
+ .on('error', function(e){
+ self.onError(e);
+ })
+ .on('close', function(){
+ self.onClose('transport close');
+ });
+};
+
+/**
+ * Probes a transport.
+ *
+ * @param {String} transport name
+ * @api private
+ */
+
+Socket.prototype.probe = function (name) {
+ debug('probing transport "%s"', name);
+ var transport = this.createTransport(name, { probe: 1 })
+ , failed = false
+ , self = this;
+
+ Socket.priorWebsocketSuccess = false;
+
+ function onTransportOpen(){
+ if (self.onlyBinaryUpgrades) {
+ var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
+ failed = failed || upgradeLosesBinary;
+ }
+ if (failed) return;
+
+ debug('probe transport "%s" opened', name);
+ transport.send([{ type: 'ping', data: 'probe' }]);
+ transport.once('packet', function (msg) {
+ if (failed) return;
+ if ('pong' == msg.type && 'probe' == msg.data) {
+ debug('probe transport "%s" pong', name);
+ self.upgrading = true;
+ self.emit('upgrading', transport);
+ if (!transport) return;
+ Socket.priorWebsocketSuccess = 'websocket' == transport.name;
+
+ debug('pausing current transport "%s"', self.transport.name);
+ self.transport.pause(function () {
+ if (failed) return;
+ if ('closed' == self.readyState) return;
+ debug('changing transport and sending upgrade packet');
+
+ cleanup();
+
+ self.setTransport(transport);
+ transport.send([{ type: 'upgrade' }]);
+ self.emit('upgrade', transport);
+ transport = null;
+ self.upgrading = false;
+ self.flush();
+ });
+ } else {
+ debug('probe transport "%s" failed', name);
+ var err = new Error('probe error');
+ err.transport = transport.name;
+ self.emit('upgradeError', err);
+ }
+ });
+ }
+
+ function freezeTransport() {
+ if (failed) return;
+
+ // Any callback called by transport should be ignored since now
+ failed = true;
+
+ cleanup();
+
+ transport.close();
+ transport = null;
+ }
+
+ //Handle any error that happens while probing
+ function onerror(err) {
+ var error = new Error('probe error: ' + err);
+ error.transport = transport.name;
+
+ freezeTransport();
+
+ debug('probe transport "%s" failed because of error: %s', name, err);
+
+ self.emit('upgradeError', error);
+ }
+
+ function onTransportClose(){
+ onerror("transport closed");
+ }
+
+ //When the socket is closed while we're probing
+ function onclose(){
+ onerror("socket closed");
+ }
+
+ //When the socket is upgraded while we're probing
+ function onupgrade(to){
+ if (transport && to.name != transport.name) {
+ debug('"%s" works - aborting "%s"', to.name, transport.name);
+ freezeTransport();
+ }
+ }
+
+ //Remove all listeners on the transport and on self
+ function cleanup(){
+ transport.removeListener('open', onTransportOpen);
+ transport.removeListener('error', onerror);
+ transport.removeListener('close', onTransportClose);
+ self.removeListener('close', onclose);
+ self.removeListener('upgrading', onupgrade);
+ }
+
+ transport.once('open', onTransportOpen);
+ transport.once('error', onerror);
+ transport.once('close', onTransportClose);
+
+ this.once('close', onclose);
+ this.once('upgrading', onupgrade);
+
+ transport.open();
+
+};
+
+/**
+ * Called when connection is deemed open.
+ *
+ * @api public
+ */
+
+Socket.prototype.onOpen = function () {
+ debug('socket open');
+ this.readyState = 'open';
+ Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
+ this.emit('open');
+ this.flush();
+
+ // we check for `readyState` in case an `open`
+ // listener already closed the socket
+ if ('open' == this.readyState && this.upgrade && this.transport.pause) {
+ debug('starting upgrade probes');
+ for (var i = 0, l = this.upgrades.length; i < l; i++) {
+ this.probe(this.upgrades[i]);
+ }
+ }
+};
+
+/**
+ * Handles a packet.
+ *
+ * @api private
+ */
+
+Socket.prototype.onPacket = function (packet) {
+ if ('opening' == this.readyState || 'open' == this.readyState) {
+ debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
+
+ this.emit('packet', packet);
+
+ // Socket is live - any packet counts
+ this.emit('heartbeat');
+
+ switch (packet.type) {
+ case 'open':
+ this.onHandshake(parsejson(packet.data));
+ break;
+
+ case 'pong':
+ this.setPing();
+ break;
+
+ case 'error':
+ var err = new Error('server error');
+ err.code = packet.data;
+ this.emit('error', err);
+ break;
+
+ case 'message':
+ this.emit('data', packet.data);
+ this.emit('message', packet.data);
+ break;
+ }
+ } else {
+ debug('packet received with socket readyState "%s"', this.readyState);
+ }
+};
+
+/**
+ * Called upon handshake completion.
+ *
+ * @param {Object} handshake obj
+ * @api private
+ */
+
+Socket.prototype.onHandshake = function (data) {
+ this.emit('handshake', data);
+ this.id = data.sid;
+ this.transport.query.sid = data.sid;
+ this.upgrades = this.filterUpgrades(data.upgrades);
+ this.pingInterval = data.pingInterval;
+ this.pingTimeout = data.pingTimeout;
+ this.onOpen();
+ // In case open handler closes socket
+ if ('closed' == this.readyState) return;
+ this.setPing();
+
+ // Prolong liveness of socket on heartbeat
+ this.removeListener('heartbeat', this.onHeartbeat);
+ this.on('heartbeat', this.onHeartbeat);
+};
+
+/**
+ * Resets ping timeout.
+ *
+ * @api private
+ */
+
+Socket.prototype.onHeartbeat = function (timeout) {
+ clearTimeout(this.pingTimeoutTimer);
+ var self = this;
+ self.pingTimeoutTimer = setTimeout(function () {
+ if ('closed' == self.readyState) return;
+ self.onClose('ping timeout');
+ }, timeout || (self.pingInterval + self.pingTimeout));
+};
+
+/**
+ * Pings server every `this.pingInterval` and expects response
+ * within `this.pingTimeout` or closes connection.
+ *
+ * @api private
+ */
+
+Socket.prototype.setPing = function () {
+ var self = this;
+ clearTimeout(self.pingIntervalTimer);
+ self.pingIntervalTimer = setTimeout(function () {
+ debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
+ self.ping();
+ self.onHeartbeat(self.pingTimeout);
+ }, self.pingInterval);
+};
+
+/**
+* Sends a ping packet.
+*
+* @api public
+*/
+
+Socket.prototype.ping = function () {
+ this.sendPacket('ping');
+};
+
+/**
+ * Called on `drain` event
+ *
+ * @api private
+ */
+
+Socket.prototype.onDrain = function() {
+ for (var i = 0; i < this.prevBufferLen; i++) {
+ if (this.callbackBuffer[i]) {
+ this.callbackBuffer[i]();
+ }
+ }
+
+ this.writeBuffer.splice(0, this.prevBufferLen);
+ this.callbackBuffer.splice(0, this.prevBufferLen);
+
+ // setting prevBufferLen = 0 is very important
+ // for example, when upgrading, upgrade packet is sent over,
+ // and a nonzero prevBufferLen could cause problems on `drain`
+ this.prevBufferLen = 0;
+
+ if (this.writeBuffer.length == 0) {
+ this.emit('drain');
+ } else {
+ this.flush();
+ }
+};
+
+/**
+ * Flush write buffers.
+ *
+ * @api private
+ */
+
+Socket.prototype.flush = function () {
+ if ('closed' != this.readyState && this.transport.writable &&
+ !this.upgrading && this.writeBuffer.length) {
+ debug('flushing %d packets in socket', this.writeBuffer.length);
+ this.transport.send(this.writeBuffer);
+ // keep track of current length of writeBuffer
+ // splice writeBuffer and callbackBuffer on `drain`
+ this.prevBufferLen = this.writeBuffer.length;
+ this.emit('flush');
+ }
+};
+
+/**
+ * Sends a message.
+ *
+ * @param {String} message.
+ * @param {Function} callback function.
+ * @return {Socket} for chaining.
+ * @api public
+ */
+
+Socket.prototype.write =
+Socket.prototype.send = function (msg, fn) {
+ this.sendPacket('message', msg, fn);
+ return this;
+};
+
+/**
+ * Sends a packet.
+ *
+ * @param {String} packet type.
+ * @param {String} data.
+ * @param {Function} callback function.
+ * @api private
+ */
+
+Socket.prototype.sendPacket = function (type, data, fn) {
+ if ('closing' == this.readyState || 'closed' == this.readyState) {
+ return;
+ }
+
+ var packet = { type: type, data: data };
+ this.emit('packetCreate', packet);
+ this.writeBuffer.push(packet);
+ this.callbackBuffer.push(fn);
+ this.flush();
+};
+
+/**
+ * Closes the connection.
+ *
+ * @api private
+ */
+
+Socket.prototype.close = function () {
+ if ('opening' == this.readyState || 'open' == this.readyState) {
+ this.readyState = 'closing';
+
+ var self = this;
+
+ function close() {
+ self.onClose('forced close');
+ debug('socket closing - telling transport to close');
+ self.transport.close();
+ }
+
+ function cleanupAndClose() {
+ self.removeListener('upgrade', cleanupAndClose);
+ self.removeListener('upgradeError', cleanupAndClose);
+ close();
+ }
+
+ function waitForUpgrade() {
+ // wait for upgrade to finish since we can't send packets while pausing a transport
+ self.once('upgrade', cleanupAndClose);
+ self.once('upgradeError', cleanupAndClose);
+ }
+
+ if (this.writeBuffer.length) {
+ this.once('drain', function() {
+ if (this.upgrading) {
+ waitForUpgrade();
+ } else {
+ close();
+ }
+ });
+ } else if (this.upgrading) {
+ waitForUpgrade();
+ } else {
+ close();
+ }
+ }
+
+ return this;
+};
+
+/**
+ * Called upon transport error
+ *
+ * @api private
+ */
+
+Socket.prototype.onError = function (err) {
+ debug('socket error %j', err);
+ Socket.priorWebsocketSuccess = false;
+ this.emit('error', err);
+ this.onClose('transport error', err);
+};
+
+/**
+ * Called upon transport close.
+ *
+ * @api private
+ */
+
+Socket.prototype.onClose = function (reason, desc) {
+ if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
+ debug('socket close with reason: "%s"', reason);
+ var self = this;
+
+ // clear timers
+ clearTimeout(this.pingIntervalTimer);
+ clearTimeout(this.pingTimeoutTimer);
+
+ // clean buffers in next tick, so developers can still
+ // grab the buffers on `close` event
+ setTimeout(function() {
+ self.writeBuffer = [];
+ self.callbackBuffer = [];
+ self.prevBufferLen = 0;
+ }, 0);
+
+ // stop event from firing again for transport
+ this.transport.removeAllListeners('close');
+
+ // ensure transport won't stay open
+ this.transport.close();
+
+ // ignore further transport communication
+ this.transport.removeAllListeners();
+
+ // set ready state
+ this.readyState = 'closed';
+
+ // clear session id
+ this.id = null;
+
+ // emit close event
+ this.emit('close', reason, desc);
+ }
+};
+
+/**
+ * Filters upgrades, returning only those matching client transports.
+ *
+ * @param {Array} server upgrades
+ * @api private
+ *
+ */
+
+Socket.prototype.filterUpgrades = function (upgrades) {
+ var filteredUpgrades = [];
+ for (var i = 0, j = upgrades.length; i<j; i++) {
+ if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
+ }
+ return filteredUpgrades;
+};
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"./transport":94,"./transports":95,"component-emitter":89,"debug":102,"engine.io-parser":105,"indexof":122,"parsejson":116,"parseqs":117,"parseuri":118}],94:[function(require,module,exports){
+/**
+ * Module dependencies.
+ */
+
+var parser = require('engine.io-parser');
+var Emitter = require('component-emitter');
+
+/**
+ * Module exports.
+ */
+
+module.exports = Transport;
+
+/**
+ * Transport abstract constructor.
+ *
+ * @param {Object} options.
+ * @api private
+ */
+
+function Transport (opts) {
+ this.path = opts.path;
+ this.hostname = opts.hostname;
+ this.port = opts.port;
+ this.secure = opts.secure;
+ this.query = opts.query;
+ this.timestampParam = opts.timestampParam;
+ this.timestampRequests = opts.timestampRequests;
+ this.readyState = '';
+ this.agent = opts.agent || false;
+ this.socket = opts.socket;
+ this.enablesXDR = opts.enablesXDR;
+
+ // SSL options for Node.js client
+ this.pfx = opts.pfx;
+ this.key = opts.key;
+ this.passphrase = opts.passphrase;
+ this.cert = opts.cert;
+ this.ca = opts.ca;
+ this.ciphers = opts.ciphers;
+ this.rejectUnauthorized = opts.rejectUnauthorized;
+}
+
+/**
+ * Mix in `Emitter`.
+ */
+
+Emitter(Transport.prototype);
+
+/**
+ * A counter used to prevent collisions in the timestamps used
+ * for cache busting.
+ */
+
+Transport.timestamps = 0;
+
+/**
+ * Emits an error.
+ *
+ * @param {String} str
+ * @return {Transport} for chaining
+ * @api public
+ */
+
+Transport.prototype.onError = function (msg, desc) {
+ var err = new Error(msg);
+ err.type = 'TransportError';
+ err.description = desc;
+ this.emit('error', err);
+ return this;
+};
+
+/**
+ * Opens the transport.
+ *
+ * @api public
+ */
+
+Transport.prototype.open = function () {
+ if ('closed' == this.readyState || '' == this.readyState) {
+ this.readyState = 'opening';
+ this.doOpen();
+ }
+
+ return this;
+};
+
+/**
+ * Closes the transport.
+ *
+ * @api private
+ */
+
+Transport.prototype.close = function () {
+ if ('opening' == this.readyState || 'open' == this.readyState) {
+ this.doClose();
+ this.onClose();
+ }
+
+ return this;
+};
+
+/**
+ * Sends multiple packets.
+ *
+ * @param {Array} packets
+ * @api private
+ */
+
+Transport.prototype.send = function(packets){
+ if ('open' == this.readyState) {
+ this.write(packets);
+ } else {
+ throw new Error('Transport not open');
+ }
+};
+
+/**
+ * Called upon open
+ *
+ * @api private
+ */
+
+Transport.prototype.onOpen = function () {
+ this.readyState = 'open';
+ this.writable = true;
+ this.emit('open');
+};
+
+/**
+ * Called with data.
+ *
+ * @param {String} data
+ * @api private
+ */
+
+Transport.prototype.onData = function(data){
+ var packet = parser.decodePacket(data, this.socket.binaryType);
+ this.onPacket(packet);
+};
+
+/**
+ * Called with a decoded packet.
+ */
+
+Transport.prototype.onPacket = function (packet) {
+ this.emit('packet', packet);
+};
+
+/**
+ * Called upon close.
+ *
+ * @api private
+ */
+
+Transport.prototype.onClose = function () {
+ this.readyState = 'closed';
+ this.emit('close');
+};
+
+},{"component-emitter":89,"engine.io-parser":105}],95:[function(require,module,exports){
+(function (global){
+/**
+ * Module dependencies
+ */
+
+var XMLHttpRequest = require('xmlhttprequest');
+var XHR = require('./polling-xhr');
+var JSONP = require('./polling-jsonp');
+var websocket = require('./websocket');
+
+/**
+ * Export transports.
+ */
+
+exports.polling = polling;
+exports.websocket = websocket;
+
+/**
+ * Polling transport polymorphic constructor.
+ * Decides on xhr vs jsonp based on feature detection.
+ *
+ * @api private
+ */
+
+function polling(opts){
+ var xhr;
+ var xd = false;
+ var xs = false;
+ var jsonp = false !== opts.jsonp;
+
+ if (global.location) {
+ var isSSL = 'https:' == location.protocol;
+ var port = location.port;
+
+ // some user agents have empty `location.port`
+ if (!port) {
+ port = isSSL ? 443 : 80;
+ }
+
+ xd = opts.hostname != location.hostname || port != opts.port;
+ xs = opts.secure != isSSL;
+ }
+
+ opts.xdomain = xd;
+ opts.xscheme = xs;
+ xhr = new XMLHttpRequest(opts);
+
+ if ('open' in xhr && !opts.forceJSONP) {
+ return new XHR(opts);
+ } else {
+ if (!jsonp) throw new Error('JSONP disabled');
+ return new JSONP(opts);
+ }
+}
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"./polling-jsonp":96,"./polling-xhr":97,"./websocket":99,"xmlhttprequest":100}],96:[function(require,module,exports){
+(function (global){
+
+/**
+ * Module requirements.
+ */
+
+var Polling = require('./polling');
+var inherit = require('component-inherit');
+
+/**
+ * Module exports.
+ */
+
+module.exports = JSONPPolling;
+
+/**
+ * Cached regular expressions.
+ */
+
+var rNewline = /\n/g;
+var rEscapedNewline = /\\n/g;
+
+/**
+ * Global JSONP callbacks.
+ */
+
+var callbacks;
+
+/**
+ * Callbacks count.
+ */
+
+var index = 0;
+
+/**
+ * Noop.
+ */
+
+function empty () { }
+
+/**
+ * JSONP Polling constructor.
+ *
+ * @param {Object} opts.
+ * @api public
+ */
+
+function JSONPPolling (opts) {
+ Polling.call(this, opts);
+
+ this.query = this.query || {};
+
+ // define global callbacks array if not present
+ // we do this here (lazily) to avoid unneeded global pollution
+ if (!callbacks) {
+ // we need to consider multiple engines in the same page
+ if (!global.___eio) global.___eio = [];
+ callbacks = global.___eio;
+ }
+
+ // callback identifier
+ this.index = callbacks.length;
+
+ // add callback to jsonp global
+ var self = this;
+ callbacks.push(function (msg) {
+ self.onData(msg);
+ });
+
+ // append to query string
+ this.query.j = this.index;
+
+ // prevent spurious errors from being emitted when the window is unloaded
+ if (global.document && global.addEventListener) {
+ global.addEventListener('beforeunload', function () {
+ if (self.script) self.script.onerror = empty;
+ }, false);
+ }
+}
+
+/**
+ * Inherits from Polling.
+ */
+
+inherit(JSONPPolling, Polling);
+
+/*
+ * JSONP only supports binary as base64 encoded strings
+ */
+
+JSONPPolling.prototype.supportsBinary = false;
+
+/**
+ * Closes the socket.
+ *
+ * @api private
+ */
+
+JSONPPolling.prototype.doClose = function () {
+ if (this.script) {
+ this.script.parentNode.removeChild(this.script);
+ this.script = null;
+ }
+
+ if (this.form) {
+ this.form.parentNode.removeChild(this.form);
+ this.form = null;
+ this.iframe = null;
+ }
+
+ Polling.prototype.doClose.call(this);
+};
+
+/**
+ * Starts a poll cycle.
+ *
+ * @api private
+ */
+
+JSONPPolling.prototype.doPoll = function () {
+ var self = this;
+ var script = document.createElement('script');
+
+ if (this.script) {
+ this.script.parentNode.removeChild(this.script);
+ this.script = null;
+ }
+
+ script.async = true;
+ script.src = this.uri();
+ script.onerror = function(e){
+ self.onError('jsonp poll error',e);
+ };
+
+ var insertAt = document.getElementsByTagName('script')[0];
+ insertAt.parentNode.insertBefore(script, insertAt);
+ this.script = script;
+
+ var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
+
+ if (isUAgecko) {
+ setTimeout(function () {
+ var iframe = document.createElement('iframe');
+ document.body.appendChild(iframe);
+ document.body.removeChild(iframe);
+ }, 100);
+ }
+};
+
+/**
+ * Writes with a hidden iframe.
+ *
+ * @param {String} data to send
+ * @param {Function} called upon flush.
+ * @api private
+ */
+
+JSONPPolling.prototype.doWrite = function (data, fn) {
+ var self = this;
+
+ if (!this.form) {
+ var form = document.createElement('form');
+ var area = document.createElement('textarea');
+ var id = this.iframeId = 'eio_iframe_' + this.index;
+ var iframe;
+
+ form.className = 'socketio';
+ form.style.position = 'absolute';
+ form.style.top = '-1000px';
+ form.style.left = '-1000px';
+ form.target = id;
+ form.method = 'POST';
+ form.setAttribute('accept-charset', 'utf-8');
+ area.name = 'd';
+ form.appendChild(area);
+ document.body.appendChild(form);
+
+ this.form = form;
+ this.area = area;
+ }
+
+ this.form.action = this.uri();
+
+ function complete () {
+ initIframe();
+ fn();
+ }
+
+ function initIframe () {
+ if (self.iframe) {
+ try {
+ self.form.removeChild(self.iframe);
+ } catch (e) {
+ self.onError('jsonp polling iframe removal error', e);
+ }
+ }
+
+ try {
+ // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
+ var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
+ iframe = document.createElement(html);
+ } catch (e) {
+ iframe = document.createElement('iframe');
+ iframe.name = self.iframeId;
+ iframe.src = 'javascript:0';
+ }
+
+ iframe.id = self.iframeId;
+
+ self.form.appendChild(iframe);
+ self.iframe = iframe;
+ }
+
+ initIframe();
+
+ // escape \n to prevent it from being converted into \r\n by some UAs
+ // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
+ data = data.replace(rEscapedNewline, '\\\n');
+ this.area.value = data.replace(rNewline, '\\n');
+
+ try {
+ this.form.submit();
+ } catch(e) {}
+
+ if (this.iframe.attachEvent) {
+ this.iframe.onreadystatechange = function(){
+ if (self.iframe.readyState == 'complete') {
+ complete();
+ }
+ };
+ } else {
+ this.iframe.onload = complete;
+ }
+};
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"./polling":98,"component-inherit":101}],97:[function(require,module,exports){
+(function (global){
+/**
+ * Module requirements.
+ */
+
+var XMLHttpRequest = require('xmlhttprequest');
+var Polling = require('./polling');
+var Emitter = require('component-emitter');
+var inherit = require('component-inherit');
+var debug = require('debug')('engine.io-client:polling-xhr');
+
+/**
+ * Module exports.
+ */
+
+module.exports = XHR;
+module.exports.Request = Request;
+
+/**
+ * Empty function
+ */
+
+function empty(){}
+
+/**
+ * XHR Polling constructor.
+ *
+ * @param {Object} opts
+ * @api public
+ */
+
+function XHR(opts){
+ Polling.call(this, opts);
+
+ if (global.location) {
+ var isSSL = 'https:' == location.protocol;
+ var port = location.port;
+
+ // some user agents have empty `location.port`
+ if (!port) {
+ port = isSSL ? 443 : 80;
+ }
+
+ this.xd = opts.hostname != global.location.hostname ||
+ port != opts.port;
+ this.xs = opts.secure != isSSL;
+ }
+}
+
+/**
+ * Inherits from Polling.
+ */
+
+inherit(XHR, Polling);
+
+/**
+ * XHR supports binary
+ */
+
+XHR.prototype.supportsBinary = true;
+
+/**
+ * Creates a request.
+ *
+ * @param {String} method
+ * @api private
+ */
+
+XHR.prototype.request = function(opts){
+ opts = opts || {};
+ opts.uri = this.uri();
+ opts.xd = this.xd;
+ opts.xs = this.xs;
+ opts.agent = this.agent || false;
+ opts.supportsBinary = this.supportsBinary;
+ opts.enablesXDR = this.enablesXDR;
+
+ // SSL options for Node.js client
+ opts.pfx = this.pfx;
+ opts.key = this.key;
+ opts.passphrase = this.passphrase;
+ opts.cert = this.cert;
+ opts.ca = this.ca;
+ opts.ciphers = this.ciphers;
+ opts.rejectUnauthorized = this.rejectUnauthorized;
+
+ return new Request(opts);
+};
+
+/**
+ * Sends data.
+ *
+ * @param {String} data to send.
+ * @param {Function} called upon flush.
+ * @api private
+ */
+
+XHR.prototype.doWrite = function(data, fn){
+ var isBinary = typeof data !== 'string' && data !== undefined;
+ var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
+ var self = this;
+ req.on('success', fn);
+ req.on('error', function(err){
+ self.onError('xhr post error', err);
+ });
+ this.sendXhr = req;
+};
+
+/**
+ * Starts a poll cycle.
+ *
+ * @api private
+ */
+
+XHR.prototype.doPoll = function(){
+ debug('xhr poll');
+ var req = this.request();
+ var self = this;
+ req.on('data', function(data){
+ self.onData(data);
+ });
+ req.on('error', function(err){
+ self.onError('xhr poll error', err);
+ });
+ this.pollXhr = req;
+};
+
+/**
+ * Request constructor
+ *
+ * @param {Object} options
+ * @api public
+ */
+
+function Request(opts){
+ this.method = opts.method || 'GET';
+ this.uri = opts.uri;
+ this.xd = !!opts.xd;
+ this.xs = !!opts.xs;
+ this.async = false !== opts.async;
+ this.data = undefined != opts.data ? opts.data : null;
+ this.agent = opts.agent;
+ this.isBinary = opts.isBinary;
+ this.supportsBinary = opts.supportsBinary;
+ this.enablesXDR = opts.enablesXDR;
+
+ // SSL options for Node.js client
+ this.pfx = opts.pfx;
+ this.key = opts.key;
+ this.passphrase = opts.passphrase;
+ this.cert = opts.cert;
+ this.ca = opts.ca;
+ this.ciphers = opts.ciphers;
+ this.rejectUnauthorized = opts.rejectUnauthorized;
+
+ this.create();
+}
+
+/**
+ * Mix in `Emitter`.
+ */
+
+Emitter(Request.prototype);
+
+/**
+ * Creates the XHR object and sends the request.
+ *
+ * @api private
+ */
+
+Request.prototype.create = function(){
+ var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
+
+ // SSL options for Node.js client
+ opts.pfx = this.pfx;
+ opts.key = this.key;
+ opts.passphrase = this.passphrase;
+ opts.cert = this.cert;
+ opts.ca = this.ca;
+ opts.ciphers = this.ciphers;
+ opts.rejectUnauthorized = this.rejectUnauthorized;
+
+ var xhr = this.xhr = new XMLHttpRequest(opts);
+ var self = this;
+
+ try {
+ debug('xhr open %s: %s', this.method, this.uri);
+ xhr.open(this.method, this.uri, this.async);
+ if (this.supportsBinary) {
+ // This has to be done after open because Firefox is stupid
+ // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
+ xhr.responseType = 'arraybuffer';
+ }
+
+ if ('POST' == this.method) {
+ try {
+ if (this.isBinary) {
+ xhr.setRequestHeader('Content-type', 'application/octet-stream');
+ } else {
+ xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
+ }
+ } catch (e) {}
+ }
+
+ // ie6 check
+ if ('withCredentials' in xhr) {
+ xhr.withCredentials = true;
+ }
+
+ if (this.hasXDR()) {
+ xhr.onload = function(){
+ self.onLoad();
+ };
+ xhr.onerror = function(){
+ self.onError(xhr.responseText);
+ };
+ } else {
+ xhr.onreadystatechange = function(){
+ if (4 != xhr.readyState) return;
+ if (200 == xhr.status || 1223 == xhr.status) {
+ self.onLoad();
+ } else {
+ // make sure the `error` event handler that's user-set
+ // does not throw in the same tick and gets caught here
+ setTimeout(function(){
+ self.onError(xhr.status);
+ }, 0);
+ }
+ };
+ }
+
+ debug('xhr data %s', this.data);
+ xhr.send(this.data);
+ } catch (e) {
+ // Need to defer since .create() is called directly fhrom the constructor
+ // and thus the 'error' event can only be only bound *after* this exception
+ // occurs. Therefore, also, we cannot throw here at all.
+ setTimeout(function() {
+ self.onError(e);
+ }, 0);
+ return;
+ }
+
+ if (global.document) {
+ this.index = Request.requestsCount++;
+ Request.requests[this.index] = this;
+ }
+};
+
+/**
+ * Called upon successful response.
+ *
+ * @api private
+ */
+
+Request.prototype.onSuccess = function(){
+ this.emit('success');
+ this.cleanup();
+};
+
+/**
+ * Called if we have data.
+ *
+ * @api private
+ */
+
+Request.prototype.onData = function(data){
+ this.emit('data', data);
+ this.onSuccess();
+};
+
+/**
+ * Called upon error.
+ *
+ * @api private
+ */
+
+Request.prototype.onError = function(err){
+ this.emit('error', err);
+ this.cleanup(true);
+};
+
+/**
+ * Cleans up house.
+ *
+ * @api private
+ */
+
+Request.prototype.cleanup = function(fromError){
+ if ('undefined' == typeof this.xhr || null === this.xhr) {
+ return;
+ }
+ // xmlhttprequest
+ if (this.hasXDR()) {
+ this.xhr.onload = this.xhr.onerror = empty;
+ } else {
+ this.xhr.onreadystatechange = empty;
+ }
+
+ if (fromError) {
+ try {
+ this.xhr.abort();
+ } catch(e) {}
+ }
+
+ if (global.document) {
+ delete Request.requests[this.index];
+ }
+
+ this.xhr = null;
+};
+
+/**
+ * Called upon load.
+ *
+ * @api private
+ */
+
+Request.prototype.onLoad = function(){
+ var data;
+ try {
+ var contentType;
+ try {
+ contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
+ } catch (e) {}
+ if (contentType === 'application/octet-stream') {
+ data = this.xhr.response;
+ } else {
+ if (!this.supportsBinary) {
+ data = this.xhr.responseText;
+ } else {
+ data = 'ok';
+ }
+ }
+ } catch (e) {
+ this.onError(e);
+ }
+ if (null != data) {
+ this.onData(data);
+ }
+};
+
+/**
+ * Check if it has XDomainRequest.
+ *
+ * @api private
+ */
+
+Request.prototype.hasXDR = function(){
+ return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
+};
+
+/**
+ * Aborts the request.
+ *
+ * @api public
+ */
+
+Request.prototype.abort = function(){
+ this.cleanup();
+};
+
+/**
+ * Aborts pending requests when unloading the window. This is needed to prevent
+ * memory leaks (e.g. when using IE) and to ensure that no spurious error is
+ * emitted.
+ */
+
+if (global.document) {
+ Request.requestsCount = 0;
+ Request.requests = {};
+ if (global.attachEvent) {
+ global.attachEvent('onunload', unloadHandler);
+ } else if (global.addEventListener) {
+ global.addEventListener('beforeunload', unloadHandler, false);
+ }
+}
+
+function unloadHandler() {
+ for (var i in Request.requests) {
+ if (Request.requests.hasOwnProperty(i)) {
+ Request.requests[i].abort();
+ }
+ }
+}
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"./polling":98,"component-emitter":89,"component-inherit":101,"debug":102,"xmlhttprequest":100}],98:[function(require,module,exports){
+/**
+ * Module dependencies.
+ */
+
+var Transport = require('../transport');
+var parseqs = require('parseqs');
+var parser = require('engine.io-parser');
+var inherit = require('component-inherit');
+var debug = require('debug')('engine.io-client:polling');
+
+/**
+ * Module exports.
+ */
+
+module.exports = Polling;
+
+/**
+ * Is XHR2 supported?
+ */
+
+var hasXHR2 = (function() {
+ var XMLHttpRequest = require('xmlhttprequest');
+ var xhr = new XMLHttpRequest({ xdomain: false });
+ return null != xhr.responseType;
+})();
+
+/**
+ * Polling interface.
+ *
+ * @param {Object} opts
+ * @api private
+ */
+
+function Polling(opts){
+ var forceBase64 = (opts && opts.forceBase64);
+ if (!hasXHR2 || forceBase64) {
+ this.supportsBinary = false;
+ }
+ Transport.call(this, opts);
+}
+
+/**
+ * Inherits from Transport.
+ */
+
+inherit(Polling, Transport);
+
+/**
+ * Transport name.
+ */
+
+Polling.prototype.name = 'polling';
+
+/**
+ * Opens the socket (triggers polling). We write a PING message to determine
+ * when the transport is open.
+ *
+ * @api private
+ */
+
+Polling.prototype.doOpen = function(){
+ this.poll();
+};
+
+/**
+ * Pauses polling.
+ *
+ * @param {Function} callback upon buffers are flushed and transport is paused
+ * @api private
+ */
+
+Polling.prototype.pause = function(onPause){
+ var pending = 0;
+ var self = this;
+
+ this.readyState = 'pausing';
+
+ function pause(){
+ debug('paused');
+ self.readyState = 'paused';
+ onPause();
+ }
+
+ if (this.polling || !this.writable) {
+ var total = 0;
+
+ if (this.polling) {
+ debug('we are currently polling - waiting to pause');
+ total++;
+ this.once('pollComplete', function(){
+ debug('pre-pause polling complete');
+ --total || pause();
+ });
+ }
+
+ if (!this.writable) {
+ debug('we are currently writing - waiting to pause');
+ total++;
+ this.once('drain', function(){
+ debug('pre-pause writing complete');
+ --total || pause();
+ });
+ }
+ } else {
+ pause();
+ }
+};
+
+/**
+ * Starts polling cycle.
+ *
+ * @api public
+ */
+
+Polling.prototype.poll = function(){
+ debug('polling');
+ this.polling = true;
+ this.doPoll();
+ this.emit('poll');
+};
+
+/**
+ * Overloads onData to detect payloads.
+ *
+ * @api private
+ */
+
+Polling.prototype.onData = function(data){
+ var self = this;
+ debug('polling got data %s', data);
+ var callback = function(packet, index, total) {
+ // if its the first message we consider the transport open
+ if ('opening' == self.readyState) {
+ self.onOpen();
+ }
+
+ // if its a close packet, we close the ongoing requests
+ if ('close' == packet.type) {
+ self.onClose();
+ return false;
+ }
+
+ // otherwise bypass onData and handle the message
+ self.onPacket(packet);
+ };
+
+ // decode payload
+ parser.decodePayload(data, this.socket.binaryType, callback);
+
+ // if an event did not trigger closing
+ if ('closed' != this.readyState) {
+ // if we got data we're not polling
+ this.polling = false;
+ this.emit('pollComplete');
+
+ if ('open' == this.readyState) {
+ this.poll();
+ } else {
+ debug('ignoring poll - transport state "%s"', this.readyState);
+ }
+ }
+};
+
+/**
+ * For polling, send a close packet.
+ *
+ * @api private
+ */
+
+Polling.prototype.doClose = function(){
+ var self = this;
+
+ function close(){
+ debug('writing close packet');
+ self.write([{ type: 'close' }]);
+ }
+
+ if ('open' == this.readyState) {
+ debug('transport open - closing');
+ close();
+ } else {
+ // in case we're trying to close while
+ // handshaking is in progress (GH-164)
+ debug('transport not open - deferring close');
+ this.once('open', close);
+ }
+};
+
+/**
+ * Writes a packets payload.
+ *
+ * @param {Array} data packets
+ * @param {Function} drain callback
+ * @api private
+ */
+
+Polling.prototype.write = function(packets){
+ var self = this;
+ this.writable = false;
+ var callbackfn = function() {
+ self.writable = true;
+ self.emit('drain');
+ };
+
+ var self = this;
+ parser.encodePayload(packets, this.supportsBinary, function(data) {
+ self.doWrite(data, callbackfn);
+ });
+};
+
+/**
+ * Generates uri for connection.
+ *
+ * @api private
+ */
+
+Polling.prototype.uri = function(){
+ var query = this.query || {};
+ var schema = this.secure ? 'https' : 'http';
+ var port = '';
+
+ // cache busting is forced
+ if (false !== this.timestampRequests) {
+ query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
+ }
+
+ if (!this.supportsBinary && !query.sid) {
+ query.b64 = 1;
+ }
+
+ query = parseqs.encode(query);
+
+ // avoid port if default for schema
+ if (this.port && (('https' == schema && this.port != 443) ||
+ ('http' == schema && this.port != 80))) {
+ port = ':' + this.port;
+ }
+
+ // prepend ? to query
+ if (query.length) {
+ query = '?' + query;
+ }
+
+ return schema + '://' + this.hostname + port + this.path + query;
+};
+
+},{"../transport":94,"component-inherit":101,"debug":102,"engine.io-parser":105,"parseqs":117,"xmlhttprequest":100}],99:[function(require,module,exports){
+/**
+ * Module dependencies.
+ */
+
+var Transport = require('../transport');
+var parser = require('engine.io-parser');
+var parseqs = require('parseqs');
+var inherit = require('component-inherit');
+var debug = require('debug')('engine.io-client:websocket');
+
+/**
+ * `ws` exposes a WebSocket-compatible interface in
+ * Node, or the `WebSocket` or `MozWebSocket` globals
+ * in the browser.
+ */
+
+var WebSocket = require('ws');
+
+/**
+ * Module exports.
+ */
+
+module.exports = WS;
+
+/**
+ * WebSocket transport constructor.
+ *
+ * @api {Object} connection options
+ * @api public
+ */
+
+function WS(opts){
+ var forceBase64 = (opts && opts.forceBase64);
+ if (forceBase64) {
+ this.supportsBinary = false;
+ }
+ Transport.call(this, opts);
+}
+
+/**
+ * Inherits from Transport.
+ */
+
+inherit(WS, Transport);
+
+/**
+ * Transport name.
+ *
+ * @api public
+ */
+
+WS.prototype.name = 'websocket';
+
+/*
+ * WebSockets support binary
+ */
+
+WS.prototype.supportsBinary = true;
+
+/**
+ * Opens socket.
+ *
+ * @api private
+ */
+
+WS.prototype.doOpen = function(){
+ if (!this.check()) {
+ // let probe timeout
+ return;
+ }
+
+ var self = this;
+ var uri = this.uri();
+ var protocols = void(0);
+ var opts = { agent: this.agent };
+
+ // SSL options for Node.js client
+ opts.pfx = this.pfx;
+ opts.key = this.key;
+ opts.passphrase = this.passphrase;
+ opts.cert = this.cert;
+ opts.ca = this.ca;
+ opts.ciphers = this.ciphers;
+ opts.rejectUnauthorized = this.rejectUnauthorized;
+
+ this.ws = new WebSocket(uri, protocols, opts);
+
+ if (this.ws.binaryType === undefined) {
+ this.supportsBinary = false;
+ }
+
+ this.ws.binaryType = 'arraybuffer';
+ this.addEventListeners();
+};
+
+/**
+ * Adds event listeners to the socket
+ *
+ * @api private
+ */
+
+WS.prototype.addEventListeners = function(){
+ var self = this;
+
+ this.ws.onopen = function(){
+ self.onOpen();
+ };
+ this.ws.onclose = function(){
+ self.onClose();
+ };
+ this.ws.onmessage = function(ev){
+ self.onData(ev.data);
+ };
+ this.ws.onerror = function(e){
+ self.onError('websocket error', e);
+ };
+};
+
+/**
+ * Override `onData` to use a timer on iOS.
+ * See: https://gist.github.com/mloughran/2052006
+ *
+ * @api private
+ */
+
+if ('undefined' != typeof navigator
+ && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
+ WS.prototype.onData = function(data){
+ var self = this;
+ setTimeout(function(){
+ Transport.prototype.onData.call(self, data);
+ }, 0);
+ };
+}
+
+/**
+ * Writes data to socket.
+ *
+ * @param {Array} array of packets.
+ * @api private
+ */
+
+WS.prototype.write = function(packets){
+ var self = this;
+ this.writable = false;
+ // encodePacket efficient as it uses WS framing
+ // no need for encodePayload
+ for (var i = 0, l = packets.length; i < l; i++) {
+ parser.encodePacket(packets[i], this.supportsBinary, function(data) {
+ //Sometimes the websocket has already been closed but the browser didn't
+ //have a chance of informing us about it yet, in that case send will
+ //throw an error
+ try {
+ self.ws.send(data);
+ } catch (e){
+ debug('websocket closed before onclose event');
+ }
+ });
+ }
+
+ function ondrain() {
+ self.writable = true;
+ self.emit('drain');
+ }
+ // fake drain
+ // defer to next tick to allow Socket to clear writeBuffer
+ setTimeout(ondrain, 0);
+};
+
+/**
+ * Called upon close
+ *
+ * @api private
+ */
+
+WS.prototype.onClose = function(){
+ Transport.prototype.onClose.call(this);
+};
+
+/**
+ * Closes socket.
+ *
+ * @api private
+ */
+
+WS.prototype.doClose = function(){
+ if (typeof this.ws !== 'undefined') {
+ this.ws.close();
+ }
+};
+
+/**
+ * Generates uri for connection.
+ *
+ * @api private
+ */
+
+WS.prototype.uri = function(){
+ var query = this.query || {};
+ var schema = this.secure ? 'wss' : 'ws';
+ var port = '';
+
+ // avoid port if default for schema
+ if (this.port && (('wss' == schema && this.port != 443)
+ || ('ws' == schema && this.port != 80))) {
+ port = ':' + this.port;
+ }
+
+ // append timestamp to URI
+ if (this.timestampRequests) {
+ query[this.timestampParam] = +new Date;
+ }
+
+ // communicate binary support capabilities
+ if (!this.supportsBinary) {
+ query.b64 = 1;
+ }
+
+ query = parseqs.encode(query);
+
+ // prepend ? to query
+ if (query.length) {
+ query = '?' + query;
+ }
+
+ return schema + '://' + this.hostname + port + this.path + query;
+};
+
+/**
+ * Feature detection for WebSocket.
+ *
+ * @return {Boolean} whether this transport is available.
+ * @api public
+ */
+
+WS.prototype.check = function(){
+ return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
+};
+
+},{"../transport":94,"component-inherit":101,"debug":102,"engine.io-parser":105,"parseqs":117,"ws":119}],100:[function(require,module,exports){
+// browser shim for xmlhttprequest module
+var hasCORS = require('has-cors');
+
+module.exports = function(opts) {
+ var xdomain = opts.xdomain;
+
+ // scheme must be same when usign XDomainRequest
+ // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
+ var xscheme = opts.xscheme;
+
+ // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
+ // https://github.com/Automattic/engine.io-client/pull/217
+ var enablesXDR = opts.enablesXDR;
+
+ // XMLHttpRequest can be disabled on IE
+ try {
+ if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
+ return new XMLHttpRequest();
+ }
+ } catch (e) { }
+
+ // Use XDomainRequest for IE8 if enablesXDR is true
+ // because loading bar keeps flashing when using jsonp-polling
+ // https://github.com/yujiosaka/socke.io-ie8-loading-example
+ try {
+ if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
+ return new XDomainRequest();
+ }
+ } catch (e) { }
+
+ if (!xdomain) {
+ try {
+ return new ActiveXObject('Microsoft.XMLHTTP');
+ } catch(e) { }
+ }
+}
+
+},{"has-cors":114}],101:[function(require,module,exports){
+
+module.exports = function(a, b){
+ var fn = function(){};
+ fn.prototype = b.prototype;
+ a.prototype = new fn;
+ a.prototype.constructor = a;
+};
+},{}],102:[function(require,module,exports){
+
+/**
+ * This is the web browser implementation of `debug()`.
+ *
+ * Expose `debug()` as the module.
+ */
+
+exports = module.exports = require('./debug');
+exports.log = log;
+exports.formatArgs = formatArgs;
+exports.save = save;
+exports.load = load;
+exports.useColors = useColors;
+
+/**
+ * Colors.
+ */
+
+exports.colors = [
+ 'lightseagreen',
+ 'forestgreen',
+ 'goldenrod',
+ 'dodgerblue',
+ 'darkorchid',
+ 'crimson'
+];
+
+/**
+ * Currently only WebKit-based Web Inspectors, Firefox >= v31,
+ * and the Firebug extension (any Firefox version) are known
+ * to support "%c" CSS customizations.
+ *
+ * TODO: add a `localStorage` variable to explicitly enable/disable colors
+ */
+
+function useColors() {
+ // is webkit? http://stackoverflow.com/a/16459606/376773
+ return ('WebkitAppearance' in document.documentElement.style) ||
+ // is firebug? http://stackoverflow.com/a/398120/376773
+ (window.console && (console.firebug || (console.exception && console.table))) ||
+ // is firefox >= v31?
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
+ (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
+}
+
+/**
+ * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
+ */
+
+exports.formatters.j = function(v) {
+ return JSON.stringify(v);
+};
+
+
+/**
+ * Colorize log arguments if enabled.
+ *
+ * @api public
+ */
+
+function formatArgs() {
+ var args = arguments;
+ var useColors = this.useColors;
+
+ args[0] = (useColors ? '%c' : '')
+ + this.namespace
+ + (useColors ? ' %c' : ' ')
+ + args[0]
+ + (useColors ? '%c ' : ' ')
+ + '+' + exports.humanize(this.diff);
+
+ if (!useColors) return args;
+
+ var c = 'color: ' + this.color;
+ args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
+
+ // the final "%c" is somewhat tricky, because there could be other
+ // arguments passed either before or after the %c, so we need to
+ // figure out the correct index to insert the CSS into
+ var index = 0;
+ var lastC = 0;
+ args[0].replace(/%[a-z%]/g, function(match) {
+ if ('%%' === match) return;
+ index++;
+ if ('%c' === match) {
+ // we only are interested in the *last* %c
+ // (the user may have provided their own)
+ lastC = index;
+ }
+ });
+
+ args.splice(lastC, 0, c);
+ return args;
+}
+
+/**
+ * Invokes `console.log()` when available.
+ * No-op when `console.log` is not a "function".
+ *
+ * @api public
+ */
+
+function log() {
+ // This hackery is required for IE8,
+ // where the `console.log` function doesn't have 'apply'
+ return 'object' == typeof console
+ && 'function' == typeof console.log
+ && Function.prototype.apply.call(console.log, console, arguments);
+}
+
+/**
+ * Save `namespaces`.
+ *
+ * @param {String} namespaces
+ * @api private
+ */
+
+function save(namespaces) {
+ try {
+ if (null == namespaces) {
+ localStorage.removeItem('debug');
+ } else {
+ localStorage.debug = namespaces;
+ }
+ } catch(e) {}
+}
+
+/**
+ * Load `namespaces`.
+ *
+ * @return {String} returns the previously persisted debug modes
+ * @api private
+ */
+
+function load() {
+ var r;
+ try {
+ r = localStorage.debug;
+ } catch(e) {}
+ return r;
+}
+
+/**
+ * Enable namespaces listed in `localStorage.debug` initially.
+ */
+
+exports.enable(load());
+
+},{"./debug":103}],103:[function(require,module,exports){
+
+/**
+ * This is the common logic for both the Node.js and web browser
+ * implementations of `debug()`.
+ *
+ * Expose `debug()` as the module.
+ */
+
+exports = module.exports = debug;
+exports.coerce = coerce;
+exports.disable = disable;
+exports.enable = enable;
+exports.enabled = enabled;
+exports.humanize = require('ms');
+
+/**
+ * The currently active debug mode names, and names to skip.
+ */
+
+exports.names = [];
+exports.skips = [];
+
+/**
+ * Map of special "%n" handling functions, for the debug "format" argument.
+ *
+ * Valid key names are a single, lowercased letter, i.e. "n".
+ */
+
+exports.formatters = {};
+
+/**
+ * Previously assigned color.
+ */
+
+var prevColor = 0;
+
+/**
+ * Previous log timestamp.
+ */
+
+var prevTime;
+
+/**
+ * Select a color.
+ *
+ * @return {Number}
+ * @api private
+ */
+
+function selectColor() {
+ return exports.colors[prevColor++ % exports.colors.length];
+}
+
+/**
+ * Create a debugger with the given `namespace`.
+ *
+ * @param {String} namespace
+ * @return {Function}
+ * @api public
+ */
+
+function debug(namespace) {
+
+ // define the `disabled` version
+ function disabled() {
+ }
+ disabled.enabled = false;
+
+ // define the `enabled` version
+ function enabled() {
+
+ var self = enabled;
+
+ // set `diff` timestamp
+ var curr = +new Date();
+ var ms = curr - (prevTime || curr);
+ self.diff = ms;
+ self.prev = prevTime;
+ self.curr = curr;
+ prevTime = curr;
+
+ // add the `color` if not set
+ if (null == self.useColors) self.useColors = exports.useColors();
+ if (null == self.color && self.useColors) self.color = selectColor();
+
+ var args = Array.prototype.slice.call(arguments);
+
+ args[0] = exports.coerce(args[0]);
+
+ if ('string' !== typeof args[0]) {
+ // anything else let's inspect with %o
+ args = ['%o'].concat(args);
+ }
+
+ // apply any `formatters` transformations
+ var index = 0;
+ args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
+ // if we encounter an escaped % then don't increase the array index
+ if (match === '%%') return match;
+ index++;
+ var formatter = exports.formatters[format];
+ if ('function' === typeof formatter) {
+ var val = args[index];
+ match = formatter.call(self, val);
+
+ // now we need to remove `args[index]` since it's inlined in the `format`
+ args.splice(index, 1);
+ index--;
+ }
+ return match;
+ });
+
+ if ('function' === typeof exports.formatArgs) {
+ args = exports.formatArgs.apply(self, args);
+ }
+ var logFn = enabled.log || exports.log || console.log.bind(console);
+ logFn.apply(self, args);
+ }
+ enabled.enabled = true;
+
+ var fn = exports.enabled(namespace) ? enabled : disabled;
+
+ fn.namespace = namespace;
+
+ return fn;
+}
+
+/**
+ * Enables a debug mode by namespaces. This can include modes
+ * separated by a colon and wildcards.
+ *
+ * @param {String} namespaces
+ * @api public
+ */
+
+function enable(namespaces) {
+ exports.save(namespaces);
+
+ var split = (namespaces || '').split(/[\s,]+/);
+ var len = split.length;
+
+ for (var i = 0; i < len; i++) {
+ if (!split[i]) continue; // ignore empty strings
+ namespaces = split[i].replace(/\*/g, '.*?');
+ if (namespaces[0] === '-') {
+ exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
+ } else {
+ exports.names.push(new RegExp('^' + namespaces + '$'));
+ }
+ }
+}
+
+/**
+ * Disable debug output.
+ *
+ * @api public
+ */
+
+function disable() {
+ exports.enable('');
+}
+
+/**
+ * Returns true if the given mode name is enabled, false otherwise.
+ *
+ * @param {String} name
+ * @return {Boolean}
+ * @api public
+ */
+
+function enabled(name) {
+ var i, len;
+ for (i = 0, len = exports.skips.length; i < len; i++) {
+ if (exports.skips[i].test(name)) {
+ return false;
+ }
+ }
+ for (i = 0, len = exports.names.length; i < len; i++) {
+ if (exports.names[i].test(name)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * Coerce `val`.
+ *
+ * @param {Mixed} val
+ * @return {Mixed}
+ * @api private
+ */
+
+function coerce(val) {
+ if (val instanceof Error) return val.stack || val.message;
+ return val;
+}
+
+},{"ms":104}],104:[function(require,module,exports){
+/**
+ * Helpers.
+ */
+
+var s = 1000;
+var m = s * 60;
+var h = m * 60;
+var d = h * 24;
+var y = d * 365.25;
+
+/**
+ * Parse or format the given `val`.
+ *
+ * Options:
+ *
+ * - `long` verbose formatting [false]
+ *
+ * @param {String|Number} val
+ * @param {Object} options
+ * @return {String|Number}
+ * @api public
+ */
+
+module.exports = function(val, options){
+ options = options || {};
+ if ('string' == typeof val) return parse(val);
+ return options.long
+ ? long(val)
+ : short(val);
+};
+
+/**
+ * Parse the given `str` and return milliseconds.
+ *
+ * @param {String} str
+ * @return {Number}
+ * @api private
+ */
+
+function parse(str) {
+ var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
+ if (!match) return;
+ var n = parseFloat(match[1]);
+ var type = (match[2] || 'ms').toLowerCase();
+ switch (type) {
+ case 'years':
+ case 'year':
+ case 'y':
+ return n * y;
+ case 'days':
+ case 'day':
+ case 'd':
+ return n * d;
+ case 'hours':
+ case 'hour':
+ case 'h':
+ return n * h;
+ case 'minutes':
+ case 'minute':
+ case 'm':
+ return n * m;
+ case 'seconds':
+ case 'second':
+ case 's':
+ return n * s;
+ case 'ms':
+ return n;
+ }
+}
+
+/**
+ * Short format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function short(ms) {
+ if (ms >= d) return Math.round(ms / d) + 'd';
+ if (ms >= h) return Math.round(ms / h) + 'h';
+ if (ms >= m) return Math.round(ms / m) + 'm';
+ if (ms >= s) return Math.round(ms / s) + 's';
+ return ms + 'ms';
+}
+
+/**
+ * Long format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function long(ms) {
+ return plural(ms, d, 'day')
+ || plural(ms, h, 'hour')
+ || plural(ms, m, 'minute')
+ || plural(ms, s, 'second')
+ || ms + ' ms';
+}
+
+/**
+ * Pluralization helper.
+ */
+
+function plural(ms, n, name) {
+ if (ms < n) return;
+ if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
+ return Math.ceil(ms / n) + ' ' + name + 's';
+}
+
+},{}],105:[function(require,module,exports){
+(function (global){
+/**
+ * Module dependencies.
+ */
+
+var keys = require('./keys');
+var hasBinary = require('has-binary');
+var sliceBuffer = require('arraybuffer.slice');
+var base64encoder = require('base64-arraybuffer');
+var after = require('after');
+var utf8 = require('utf8');
+
+/**
+ * Check if we are running an android browser. That requires us to use
+ * ArrayBuffer with polling transports...
+ *
+ * http://ghinda.net/jpeg-blob-ajax-android/
+ */
+
+var isAndroid = navigator.userAgent.match(/Android/i);
+
+/**
+ * Check if we are running in PhantomJS.
+ * Uploading a Blob with PhantomJS does not work correctly, as reported here:
+ * https://github.com/ariya/phantomjs/issues/11395
+ * @type boolean
+ */
+var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
+
+/**
+ * When true, avoids using Blobs to encode payloads.
+ * @type boolean
+ */
+var dontSendBlobs = isAndroid || isPhantomJS;
+
+/**
+ * Current protocol version.
+ */
+
+exports.protocol = 3;
+
+/**
+ * Packet types.
+ */
+
+var packets = exports.packets = {
+ open: 0 // non-ws
+ , close: 1 // non-ws
+ , ping: 2
+ , pong: 3
+ , message: 4
+ , upgrade: 5
+ , noop: 6
+};
+
+var packetslist = keys(packets);
+
+/**
+ * Premade error packet.
+ */
+
+var err = { type: 'error', data: 'parser error' };
+
+/**
+ * Create a blob api even for blob builder when vendor prefixes exist
+ */
+
+var Blob = require('blob');
+
+/**
+ * Encodes a packet.
+ *
+ * <packet type id> [ <data> ]
+ *
+ * Example:
+ *
+ * 5hello world
+ * 3
+ * 4
+ *
+ * Binary is encoded in an identical principle
+ *
+ * @api private
+ */
+
+exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
+ if ('function' == typeof supportsBinary) {
+ callback = supportsBinary;
+ supportsBinary = false;
+ }
+
+ if ('function' == typeof utf8encode) {
+ callback = utf8encode;
+ utf8encode = null;
+ }
+
+ var data = (packet.data === undefined)
+ ? undefined
+ : packet.data.buffer || packet.data;
+
+ if (global.ArrayBuffer && data instanceof ArrayBuffer) {
+ return encodeArrayBuffer(packet, supportsBinary, callback);
+ } else if (Blob && data instanceof global.Blob) {
+ return encodeBlob(packet, supportsBinary, callback);
+ }
+
+ // might be an object with { base64: true, data: dataAsBase64String }
+ if (data && data.base64) {
+ return encodeBase64Object(packet, callback);
+ }
+
+ // Sending data as a utf-8 string
+ var encoded = packets[packet.type];
+
+ // data fragment is optional
+ if (undefined !== packet.data) {
+ encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
+ }
+
+ return callback('' + encoded);
+
+};
+
+function encodeBase64Object(packet, callback) {
+ // packet data is an object { base64: true, data: dataAsBase64String }
+ var message = 'b' + exports.packets[packet.type] + packet.data.data;
+ return callback(message);
+}
+
+/**
+ * Encode packet helpers for binary types
+ */
+
+function encodeArrayBuffer(packet, supportsBinary, callback) {
+ if (!supportsBinary) {
+ return exports.encodeBase64Packet(packet, callback);
+ }
+
+ var data = packet.data;
+ var contentArray = new Uint8Array(data);
+ var resultBuffer = new Uint8Array(1 + data.byteLength);
+
+ resultBuffer[0] = packets[packet.type];
+ for (var i = 0; i < contentArray.length; i++) {
+ resultBuffer[i+1] = contentArray[i];
+ }
+
+ return callback(resultBuffer.buffer);
+}
+
+function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
+ if (!supportsBinary) {
+ return exports.encodeBase64Packet(packet, callback);
+ }
+
+ var fr = new FileReader();
+ fr.onload = function() {
+ packet.data = fr.result;
+ exports.encodePacket(packet, supportsBinary, true, callback);
+ };
+ return fr.readAsArrayBuffer(packet.data);
+}
+
+function encodeBlob(packet, supportsBinary, callback) {
+ if (!supportsBinary) {
+ return exports.encodeBase64Packet(packet, callback);
+ }
+
+ if (dontSendBlobs) {
+ return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
+ }
+
+ var length = new Uint8Array(1);
+ length[0] = packets[packet.type];
+ var blob = new Blob([length.buffer, packet.data]);
+
+ return callback(blob);
+}
+
+/**
+ * Encodes a packet with binary data in a base64 string
+ *
+ * @param {Object} packet, has `type` and `data`
+ * @return {String} base64 encoded message
+ */
+
+exports.encodeBase64Packet = function(packet, callback) {
+ var message = 'b' + exports.packets[packet.type];
+ if (Blob && packet.data instanceof Blob) {
+ var fr = new FileReader();
+ fr.onload = function() {
+ var b64 = fr.result.split(',')[1];
+ callback(message + b64);
+ };
+ return fr.readAsDataURL(packet.data);
+ }
+
+ var b64data;
+ try {
+ b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
+ } catch (e) {
+ // iPhone Safari doesn't let you apply with typed arrays
+ var typed = new Uint8Array(packet.data);
+ var basic = new Array(typed.length);
+ for (var i = 0; i < typed.length; i++) {
+ basic[i] = typed[i];
+ }
+ b64data = String.fromCharCode.apply(null, basic);
+ }
+ message += global.btoa(b64data);
+ return callback(message);
+};
+
+/**
+ * Decodes a packet. Changes format to Blob if requested.
+ *
+ * @return {Object} with `type` and `data` (if any)
+ * @api private
+ */
+
+exports.decodePacket = function (data, binaryType, utf8decode) {
+ // String data
+ if (typeof data == 'string' || data === undefined) {
+ if (data.charAt(0) == 'b') {
+ return exports.decodeBase64Packet(data.substr(1), binaryType);
+ }
+
+ if (utf8decode) {
+ try {
+ data = utf8.decode(data);
+ } catch (e) {
+ return err;
+ }
+ }
+ var type = data.charAt(0);
+
+ if (Number(type) != type || !packetslist[type]) {
+ return err;
+ }
+
+ if (data.length > 1) {
+ return { type: packetslist[type], data: data.substring(1) };
+ } else {
+ return { type: packetslist[type] };
+ }
+ }
+
+ var asArray = new Uint8Array(data);
+ var type = asArray[0];
+ var rest = sliceBuffer(data, 1);
+ if (Blob && binaryType === 'blob') {
+ rest = new Blob([rest]);
+ }
+ return { type: packetslist[type], data: rest };
+};
+
+/**
+ * Decodes a packet encoded in a base64 string
+ *
+ * @param {String} base64 encoded message
+ * @return {Object} with `type` and `data` (if any)
+ */
+
+exports.decodeBase64Packet = function(msg, binaryType) {
+ var type = packetslist[msg.charAt(0)];
+ if (!global.ArrayBuffer) {
+ return { type: type, data: { base64: true, data: msg.substr(1) } };
+ }
+
+ var data = base64encoder.decode(msg.substr(1));
+
+ if (binaryType === 'blob' && Blob) {
+ data = new Blob([data]);
+ }
+
+ return { type: type, data: data };
+};
+
+/**
+ * Encodes multiple messages (payload).
+ *
+ * <length>:data
+ *
+ * Example:
+ *
+ * 11:hello world2:hi
+ *
+ * If any contents are binary, they will be encoded as base64 strings. Base64
+ * encoded strings are marked with a b before the length specifier
+ *
+ * @param {Array} packets
+ * @api private
+ */
+
+exports.encodePayload = function (packets, supportsBinary, callback) {
+ if (typeof supportsBinary == 'function') {
+ callback = supportsBinary;
+ supportsBinary = null;
+ }
+
+ var isBinary = hasBinary(packets);
+
+ if (supportsBinary && isBinary) {
+ if (Blob && !dontSendBlobs) {
+ return exports.encodePayloadAsBlob(packets, callback);
+ }
+
+ return exports.encodePayloadAsArrayBuffer(packets, callback);
+ }
+
+ if (!packets.length) {
+ return callback('0:');
+ }
+
+ function setLengthHeader(message) {
+ return message.length + ':' + message;
+ }
+
+ function encodeOne(packet, doneCallback) {
+ exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
+ doneCallback(null, setLengthHeader(message));
+ });
+ }
+
+ map(packets, encodeOne, function(err, results) {
+ return callback(results.join(''));
+ });
+};
+
+/**
+ * Async array map using after
+ */
+
+function map(ary, each, done) {
+ var result = new Array(ary.length);
+ var next = after(ary.length, done);
+
+ var eachWithIndex = function(i, el, cb) {
+ each(el, function(error, msg) {
+ result[i] = msg;
+ cb(error, result);
+ });
+ };
+
+ for (var i = 0; i < ary.length; i++) {
+ eachWithIndex(i, ary[i], next);
+ }
+}
+
+/*
+ * Decodes data when a payload is maybe expected. Possible binary contents are
+ * decoded from their base64 representation
+ *
+ * @param {String} data, callback method
+ * @api public
+ */
+
+exports.decodePayload = function (data, binaryType, callback) {
+ if (typeof data != 'string') {
+ return exports.decodePayloadAsBinary(data, binaryType, callback);
+ }
+
+ if (typeof binaryType === 'function') {
+ callback = binaryType;
+ binaryType = null;
+ }
+
+ var packet;
+ if (data == '') {
+ // parser error - ignoring payload
+ return callback(err, 0, 1);
+ }
+
+ var length = ''
+ , n, msg;
+
+ for (var i = 0, l = data.length; i < l; i++) {
+ var chr = data.charAt(i);
+
+ if (':' != chr) {
+ length += chr;
+ } else {
+ if ('' == length || (length != (n = Number(length)))) {
+ // parser error - ignoring payload
+ return callback(err, 0, 1);
+ }
+
+ msg = data.substr(i + 1, n);
+
+ if (length != msg.length) {
+ // parser error - ignoring payload
+ return callback(err, 0, 1);
+ }
+
+ if (msg.length) {
+ packet = exports.decodePacket(msg, binaryType, true);
+
+ if (err.type == packet.type && err.data == packet.data) {
+ // parser error in individual packet - ignoring payload
+ return callback(err, 0, 1);
+ }
+
+ var ret = callback(packet, i + n, l);
+ if (false === ret) return;
+ }
+
+ // advance cursor
+ i += n;
+ length = '';
+ }
+ }
+
+ if (length != '') {
+ // parser error - ignoring payload
+ return callback(err, 0, 1);
+ }
+
+};
+
+/**
+ * Encodes multiple messages (payload) as binary.
+ *
+ * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
+ * 255><data>
+ *
+ * Example:
+ * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
+ *
+ * @param {Array} packets
+ * @return {ArrayBuffer} encoded payload
+ * @api private
+ */
+
+exports.encodePayloadAsArrayBuffer = function(packets, callback) {
+ if (!packets.length) {
+ return callback(new ArrayBuffer(0));
+ }
+
+ function encodeOne(packet, doneCallback) {
+ exports.encodePacket(packet, true, true, function(data) {
+ return doneCallback(null, data);
+ });
+ }
+
+ map(packets, encodeOne, function(err, encodedPackets) {
+ var totalLength = encodedPackets.reduce(function(acc, p) {
+ var len;
+ if (typeof p === 'string'){
+ len = p.length;
+ } else {
+ len = p.byteLength;
+ }
+ return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
+ }, 0);
+
+ var resultArray = new Uint8Array(totalLength);
+
+ var bufferIndex = 0;
+ encodedPackets.forEach(function(p) {
+ var isString = typeof p === 'string';
+ var ab = p;
+ if (isString) {
+ var view = new Uint8Array(p.length);
+ for (var i = 0; i < p.length; i++) {
+ view[i] = p.charCodeAt(i);
}
+ ab = view.buffer;
+ }
- return;
+ if (isString) { // not true binary
+ resultArray[bufferIndex++] = 0;
+ } else { // true binary
+ resultArray[bufferIndex++] = 1;
+ }
+
+ var lenStr = ab.byteLength.toString();
+ for (var i = 0; i < lenStr.length; i++) {
+ resultArray[bufferIndex++] = parseInt(lenStr[i]);
+ }
+ resultArray[bufferIndex++] = 255;
+
+ var view = new Uint8Array(ab);
+ for (var i = 0; i < view.length; i++) {
+ resultArray[bufferIndex++] = view[i];
+ }
});
- mLine.ssrcs = writeSsrcs(sources);
+ return callback(resultArray.buffer);
+ });
+};
- // Nuke all the scheduled groups.
- var i = mLine.ssrcGroups.length;
- while (i--) {
- if (mLine.ssrcGroups[i].nuke) {
- mLine.ssrcGroups.splice(i, 1);
+/**
+ * Encode as Blob
+ */
+
+exports.encodePayloadAsBlob = function(packets, callback) {
+ function encodeOne(packet, doneCallback) {
+ exports.encodePacket(packet, true, true, function(encoded) {
+ var binaryIdentifier = new Uint8Array(1);
+ binaryIdentifier[0] = 1;
+ if (typeof encoded === 'string') {
+ var view = new Uint8Array(encoded.length);
+ for (var i = 0; i < encoded.length; i++) {
+ view[i] = encoded.charCodeAt(i);
+ }
+ encoded = view.buffer;
+ binaryIdentifier[0] = 0;
+ }
+
+ var len = (encoded instanceof ArrayBuffer)
+ ? encoded.byteLength
+ : encoded.size;
+
+ var lenStr = len.toString();
+ var lengthAry = new Uint8Array(lenStr.length + 1);
+ for (var i = 0; i < lenStr.length; i++) {
+ lengthAry[i] = parseInt(lenStr[i]);
+ }
+ lengthAry[lenStr.length] = 255;
+
+ if (Blob) {
+ var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
+ doneCallback(null, blob);
+ }
+ });
+ }
+
+ map(packets, encodeOne, function(err, results) {
+ return callback(new Blob(results));
+ });
+};
+
+/*
+ * Decodes data when a payload is maybe expected. Strings are decoded by
+ * interpreting each byte as a key code for entries marked to start with 0. See
+ * description of encodePayloadAsBinary
+ *
+ * @param {ArrayBuffer} data, callback method
+ * @api public
+ */
+
+exports.decodePayloadAsBinary = function (data, binaryType, callback) {
+ if (typeof binaryType === 'function') {
+ callback = binaryType;
+ binaryType = null;
+ }
+
+ var bufferTail = data;
+ var buffers = [];
+
+ var numberTooLong = false;
+ while (bufferTail.byteLength > 0) {
+ var tailArray = new Uint8Array(bufferTail);
+ var isString = tailArray[0] === 0;
+ var msgLength = '';
+
+ for (var i = 1; ; i++) {
+ if (tailArray[i] == 255) break;
+
+ if (msgLength.length > 310) {
+ numberTooLong = true;
+ break;
+ }
+
+ msgLength += tailArray[i];
+ }
+
+ if(numberTooLong) return callback(err, 0, 1);
+
+ bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
+ msgLength = parseInt(msgLength);
+
+ var msg = sliceBuffer(bufferTail, 0, msgLength);
+ if (isString) {
+ try {
+ msg = String.fromCharCode.apply(null, new Uint8Array(msg));
+ } catch (e) {
+ // iPhone Safari doesn't let you apply to typed arrays
+ var typed = new Uint8Array(msg);
+ msg = '';
+ for (var i = 0; i < typed.length; i++) {
+ msg += String.fromCharCode(typed[i]);
+ }
+ }
+ }
+
+ buffers.push(msg);
+ bufferTail = sliceBuffer(bufferTail, msgLength);
+ }
+
+ var total = buffers.length;
+ buffers.forEach(function(buffer, i) {
+ callback(exports.decodePacket(buffer, binaryType, true), i, total);
+ });
+};
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"./keys":106,"after":107,"arraybuffer.slice":108,"base64-arraybuffer":109,"blob":110,"has-binary":111,"utf8":113}],106:[function(require,module,exports){
+
+/**
+ * Gets the keys for an object.
+ *
+ * @return {Array} keys
+ * @api private
+ */
+
+module.exports = Object.keys || function keys (obj){
+ var arr = [];
+ var has = Object.prototype.hasOwnProperty;
+
+ for (var i in obj) {
+ if (has.call(obj, i)) {
+ arr.push(i);
+ }
+ }
+ return arr;
+};
+
+},{}],107:[function(require,module,exports){
+module.exports = after
+
+function after(count, callback, err_cb) {
+ var bail = false
+ err_cb = err_cb || noop
+ proxy.count = count
+
+ return (count === 0) ? callback() : proxy
+
+ function proxy(err, result) {
+ if (proxy.count <= 0) {
+ throw new Error('after called too many times')
+ }
+ --proxy.count
+
+ // after first error, rest are passed to err_cb
+ if (err) {
+ bail = true
+ callback(err)
+ // future error callbacks will go to error handler
+ callback = err_cb
+ } else if (proxy.count === 0 && !bail) {
+ callback(null, result)
}
}
}
-function removeGoogConference(mLine) {
- if (!mLine || !Array.isArray(mLine.invalid)) {
- return;
+function noop() {}
+
+},{}],108:[function(require,module,exports){
+/**
+ * An abstraction for slicing an arraybuffer even when
+ * ArrayBuffer.prototype.slice is not supported
+ *
+ * @api public
+ */
+
+module.exports = function(arraybuffer, start, end) {
+ var bytes = arraybuffer.byteLength;
+ start = start || 0;
+ end = end || bytes;
+
+ if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
+
+ if (start < 0) { start += bytes; }
+ if (end < 0) { end += bytes; }
+ if (end > bytes) { end = bytes; }
+
+ if (start >= bytes || start >= end || bytes === 0) {
+ return new ArrayBuffer(0);
+ }
+
+ var abv = new Uint8Array(arraybuffer);
+ var result = new Uint8Array(end - start);
+ for (var i = start, ii = 0; i < end; i++, ii++) {
+ result[ii] = abv[i];
+ }
+ return result.buffer;
+};
+
+},{}],109:[function(require,module,exports){
+/*
+ * base64-arraybuffer
+ * https://github.com/niklasvh/base64-arraybuffer
+ *
+ * Copyright (c) 2012 Niklas von Hertzen
+ * Licensed under the MIT license.
+ */
+(function(chars){
+ "use strict";
+
+ exports.encode = function(arraybuffer) {
+ var bytes = new Uint8Array(arraybuffer),
+ i, len = bytes.length, base64 = "";
+
+ for (i = 0; i < len; i+=3) {
+ base64 += chars[bytes[i] >> 2];
+ base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
+ base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
+ base64 += chars[bytes[i + 2] & 63];
+ }
+
+ if ((len % 3) === 2) {
+ base64 = base64.substring(0, base64.length - 1) + "=";
+ } else if (len % 3 === 1) {
+ base64 = base64.substring(0, base64.length - 2) + "==";
+ }
+
+ return base64;
+ };
+
+ exports.decode = function(base64) {
+ var bufferLength = base64.length * 0.75,
+ len = base64.length, i, p = 0,
+ encoded1, encoded2, encoded3, encoded4;
+
+ if (base64[base64.length - 1] === "=") {
+ bufferLength--;
+ if (base64[base64.length - 2] === "=") {
+ bufferLength--;
+ }
+ }
+
+ var arraybuffer = new ArrayBuffer(bufferLength),
+ bytes = new Uint8Array(arraybuffer);
+
+ for (i = 0; i < len; i+=4) {
+ encoded1 = chars.indexOf(base64[i]);
+ encoded2 = chars.indexOf(base64[i+1]);
+ encoded3 = chars.indexOf(base64[i+2]);
+ encoded4 = chars.indexOf(base64[i+3]);
+
+ bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
+ bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
+ bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
+ }
+
+ return arraybuffer;
+ };
+})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
+
+},{}],110:[function(require,module,exports){
+(function (global){
+/**
+ * Create a blob builder even when vendor prefixes exist
+ */
+
+var BlobBuilder = global.BlobBuilder
+ || global.WebKitBlobBuilder
+ || global.MSBlobBuilder
+ || global.MozBlobBuilder;
+
+/**
+ * Check if Blob constructor is supported
+ */
+
+var blobSupported = (function() {
+ try {
+ var b = new Blob(['hi']);
+ return b.size == 2;
+ } catch(e) {
+ return false;
+ }
+})();
+
+/**
+ * Check if BlobBuilder is supported
+ */
+
+var blobBuilderSupported = BlobBuilder
+ && BlobBuilder.prototype.append
+ && BlobBuilder.prototype.getBlob;
+
+function BlobBuilderConstructor(ary, options) {
+ options = options || {};
+
+ var bb = new BlobBuilder();
+ for (var i = 0; i < ary.length; i++) {
+ bb.append(ary[i]);
+ }
+ return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
+};
+
+module.exports = (function() {
+ if (blobSupported) {
+ return global.Blob;
+ } else if (blobBuilderSupported) {
+ return BlobBuilderConstructor;
+ } else {
+ return undefined;
+ }
+})();
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],111:[function(require,module,exports){
+(function (global){
+
+/*
+ * Module requirements.
+ */
+
+var isArray = require('isarray');
+
+/**
+ * Module exports.
+ */
+
+module.exports = hasBinary;
+
+/**
+ * Checks for binary data.
+ *
+ * Right now only Buffer and ArrayBuffer are supported..
+ *
+ * @param {Object} anything
+ * @api public
+ */
+
+function hasBinary(data) {
+
+ function _hasBinary(obj) {
+ if (!obj) return false;
+
+ if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
+ (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
+ (global.Blob && obj instanceof Blob) ||
+ (global.File && obj instanceof File)
+ ) {
+ return true;
+ }
+
+ if (isArray(obj)) {
+ for (var i = 0; i < obj.length; i++) {
+ if (_hasBinary(obj[i])) {
+ return true;
+ }
+ }
+ } else if (obj && 'object' == typeof obj) {
+ if (obj.toJSON) {
+ obj = obj.toJSON();
+ }
+
+ for (var key in obj) {
+ if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+
+ return _hasBinary(data);
+}
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"isarray":112}],112:[function(require,module,exports){
+module.exports = Array.isArray || function (arr) {
+ return Object.prototype.toString.call(arr) == '[object Array]';
+};
+
+},{}],113:[function(require,module,exports){
+(function (global){
+/*! http://mths.be/utf8js v2.0.0 by @mathias */
+;(function(root) {
+
+ // Detect free variables `exports`
+ var freeExports = typeof exports == 'object' && exports;
+
+ // Detect free variable `module`
+ var freeModule = typeof module == 'object' && module &&
+ module.exports == freeExports && module;
+
+ // Detect free variable `global`, from Node.js or Browserified code,
+ // and use it as `root`
+ var freeGlobal = typeof global == 'object' && global;
+ if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
+ root = freeGlobal;
+ }
+
+ /*--------------------------------------------------------------------------*/
+
+ var stringFromCharCode = String.fromCharCode;
+
+ // Taken from http://mths.be/punycode
+ function ucs2decode(string) {
+ var output = [];
+ var counter = 0;
+ var length = string.length;
+ var value;
+ var extra;
+ while (counter < length) {
+ value = string.charCodeAt(counter++);
+ if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
+ // high surrogate, and there is a next character
+ extra = string.charCodeAt(counter++);
+ if ((extra & 0xFC00) == 0xDC00) { // low surrogate
+ output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
+ } else {
+ // unmatched surrogate; only append this code unit, in case the next
+ // code unit is the high surrogate of a surrogate pair
+ output.push(value);
+ counter--;
+ }
+ } else {
+ output.push(value);
+ }
+ }
+ return output;
+ }
+
+ // Taken from http://mths.be/punycode
+ function ucs2encode(array) {
+ var length = array.length;
+ var index = -1;
+ var value;
+ var output = '';
+ while (++index < length) {
+ value = array[index];
+ if (value > 0xFFFF) {
+ value -= 0x10000;
+ output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
+ value = 0xDC00 | value & 0x3FF;
+ }
+ output += stringFromCharCode(value);
+ }
+ return output;
+ }
+
+ /*--------------------------------------------------------------------------*/
+
+ function createByte(codePoint, shift) {
+ return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
+ }
+
+ function encodeCodePoint(codePoint) {
+ if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
+ return stringFromCharCode(codePoint);
+ }
+ var symbol = '';
+ if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
+ symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
+ }
+ else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
+ symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
+ symbol += createByte(codePoint, 6);
+ }
+ else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
+ symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
+ symbol += createByte(codePoint, 12);
+ symbol += createByte(codePoint, 6);
+ }
+ symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
+ return symbol;
+ }
+
+ function utf8encode(string) {
+ var codePoints = ucs2decode(string);
+
+ // console.log(JSON.stringify(codePoints.map(function(x) {
+ // return 'U+' + x.toString(16).toUpperCase();
+ // })));
+
+ var length = codePoints.length;
+ var index = -1;
+ var codePoint;
+ var byteString = '';
+ while (++index < length) {
+ codePoint = codePoints[index];
+ byteString += encodeCodePoint(codePoint);
+ }
+ return byteString;
+ }
+
+ /*--------------------------------------------------------------------------*/
+
+ function readContinuationByte() {
+ if (byteIndex >= byteCount) {
+ throw Error('Invalid byte index');
+ }
+
+ var continuationByte = byteArray[byteIndex] & 0xFF;
+ byteIndex++;
+
+ if ((continuationByte & 0xC0) == 0x80) {
+ return continuationByte & 0x3F;
+ }
+
+ // If we end up here, it’s not a continuation byte
+ throw Error('Invalid continuation byte');
+ }
+
+ function decodeSymbol() {
+ var byte1;
+ var byte2;
+ var byte3;
+ var byte4;
+ var codePoint;
+
+ if (byteIndex > byteCount) {
+ throw Error('Invalid byte index');
+ }
+
+ if (byteIndex == byteCount) {
+ return false;
+ }
+
+ // Read first byte
+ byte1 = byteArray[byteIndex] & 0xFF;
+ byteIndex++;
+
+ // 1-byte sequence (no continuation bytes)
+ if ((byte1 & 0x80) == 0) {
+ return byte1;
+ }
+
+ // 2-byte sequence
+ if ((byte1 & 0xE0) == 0xC0) {
+ var byte2 = readContinuationByte();
+ codePoint = ((byte1 & 0x1F) << 6) | byte2;
+ if (codePoint >= 0x80) {
+ return codePoint;
+ } else {
+ throw Error('Invalid continuation byte');
+ }
+ }
+
+ // 3-byte sequence (may include unpaired surrogates)
+ if ((byte1 & 0xF0) == 0xE0) {
+ byte2 = readContinuationByte();
+ byte3 = readContinuationByte();
+ codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
+ if (codePoint >= 0x0800) {
+ return codePoint;
+ } else {
+ throw Error('Invalid continuation byte');
+ }
+ }
+
+ // 4-byte sequence
+ if ((byte1 & 0xF8) == 0xF0) {
+ byte2 = readContinuationByte();
+ byte3 = readContinuationByte();
+ byte4 = readContinuationByte();
+ codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
+ (byte3 << 0x06) | byte4;
+ if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
+ return codePoint;
+ }
+ }
+
+ throw Error('Invalid UTF-8 detected');
+ }
+
+ var byteArray;
+ var byteCount;
+ var byteIndex;
+ function utf8decode(byteString) {
+ byteArray = ucs2decode(byteString);
+ byteCount = byteArray.length;
+ byteIndex = 0;
+ var codePoints = [];
+ var tmp;
+ while ((tmp = decodeSymbol()) !== false) {
+ codePoints.push(tmp);
+ }
+ return ucs2encode(codePoints);
+ }
+
+ /*--------------------------------------------------------------------------*/
+
+ var utf8 = {
+ 'version': '2.0.0',
+ 'encode': utf8encode,
+ 'decode': utf8decode
+ };
+
+ // Some AMD build optimizers, like r.js, check for specific condition patterns
+ // like the following:
+ if (
+ typeof define == 'function' &&
+ typeof define.amd == 'object' &&
+ define.amd
+ ) {
+ define(function() {
+ return utf8;
+ });
+ } else if (freeExports && !freeExports.nodeType) {
+ if (freeModule) { // in Node.js or RingoJS v0.8.0+
+ freeModule.exports = utf8;
+ } else { // in Narwhal or RingoJS v0.7.0-
+ var object = {};
+ var hasOwnProperty = object.hasOwnProperty;
+ for (var key in utf8) {
+ hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
+ }
+ }
+ } else { // in Rhino or a web browser
+ root.utf8 = utf8;
+ }
+
+}(this));
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],114:[function(require,module,exports){
+
+/**
+ * Module dependencies.
+ */
+
+var global = require('global');
+
+/**
+ * Module exports.
+ *
+ * Logic borrowed from Modernizr:
+ *
+ * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
+ */
+
+try {
+ module.exports = 'XMLHttpRequest' in global &&
+ 'withCredentials' in new global.XMLHttpRequest();
+} catch (err) {
+ // if XMLHttp support is disabled in IE then it will throw
+ // when trying to create
+ module.exports = false;
+}
+
+},{"global":115}],115:[function(require,module,exports){
+
+/**
+ * Returns `this`. Execute this without a "context" (i.e. without it being
+ * attached to an object of the left-hand side), and `this` points to the
+ * "global" scope of the current JS execution.
+ */
+
+module.exports = (function () { return this; })();
+
+},{}],116:[function(require,module,exports){
+(function (global){
+/**
+ * JSON parse.
+ *
+ * @see Based on jQuery#parseJSON (MIT) and JSON2
+ * @api private
+ */
+
+var rvalidchars = /^[\],:{}\s]*$/;
+var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
+var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
+var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
+var rtrimLeft = /^\s+/;
+var rtrimRight = /\s+$/;
+
+module.exports = function parsejson(data) {
+ if ('string' != typeof data || !data) {
+ return null;
+ }
+
+ data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
+
+ // Attempt to parse using the native JSON parser first
+ if (global.JSON && JSON.parse) {
+ return JSON.parse(data);
+ }
+
+ if (rvalidchars.test(data.replace(rvalidescape, '@')
+ .replace(rvalidtokens, ']')
+ .replace(rvalidbraces, ''))) {
+ return (new Function('return ' + data))();
+ }
+};
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],117:[function(require,module,exports){
+/**
+ * Compiles a querystring
+ * Returns string representation of the object
+ *
+ * @param {Object}
+ * @api private
+ */
+
+exports.encode = function (obj) {
+ var str = '';
+
+ for (var i in obj) {
+ if (obj.hasOwnProperty(i)) {
+ if (str.length) str += '&';
+ str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
+ }
+ }
+
+ return str;
+};
+
+/**
+ * Parses a simple querystring into an object
+ *
+ * @param {String} qs
+ * @api private
+ */
+
+exports.decode = function(qs){
+ var qry = {};
+ var pairs = qs.split('&');
+ for (var i = 0, l = pairs.length; i < l; i++) {
+ var pair = pairs[i].split('=');
+ qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
+ }
+ return qry;
+};
+
+},{}],118:[function(require,module,exports){
+/**
+ * Parses an URI
+ *
+ * @author Steven Levithan <stevenlevithan.com> (MIT license)
+ * @api private
+ */
+
+var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
+
+var parts = [
+ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
+];
+
+module.exports = function parseuri(str) {
+ var src = str,
+ b = str.indexOf('['),
+ e = str.indexOf(']');
+
+ if (b != -1 && e != -1) {
+ str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
+ }
+
+ var m = re.exec(str || ''),
+ uri = {},
+ i = 14;
+
+ while (i--) {
+ uri[parts[i]] = m[i] || '';
+ }
+
+ if (b != -1 && e != -1) {
+ uri.source = src;
+ uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
+ uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
+ uri.ipv6uri = true;
}
- var i = mLine.invalid.length;
- while (i--) {
- if (mLine.invalid[i].value == 'x-google-flag:conference') {
- mLine.invalid.splice(i, 1);
- }
- }
+ return uri;
+};
+
+},{}],119:[function(require,module,exports){
+
+/**
+ * Module dependencies.
+ */
+
+var global = (function() { return this; })();
+
+/**
+ * WebSocket constructor.
+ */
+
+var WebSocket = global.WebSocket || global.MozWebSocket;
+
+/**
+ * Module exports.
+ */
+
+module.exports = WebSocket ? ws : null;
+
+/**
+ * WebSocket constructor.
+ *
+ * The third `opts` options object gets ignored in web browsers, since it's
+ * non-standard, and throws a TypeError if passed to the constructor.
+ * See: https://github.com/einaros/ws/issues/227
+ *
+ * @param {String} uri
+ * @param {Array} protocols (optional)
+ * @param {Object) opts (optional)
+ * @api public
+ */
+
+function ws(uri, protocols, opts) {
+ var instance;
+ if (protocols) {
+ instance = new WebSocket(uri, protocols);
+ } else {
+ instance = new WebSocket(uri);
+ }
+ return instance;
}
-function assertGoogConference(mLine) {
- if (!mLine) {
- return;
- }
+if (WebSocket) ws.prototype = WebSocket.prototype;
- if (!Array.isArray(mLine.invalid)) {
- mLine.invalid = [];
- }
+},{}],120:[function(require,module,exports){
+(function (global){
- if (!mLine.invalid.some(
- function (i) { return i.value === 'x-google-flag:conference' })) {
- mLine.invalid.push({'value': 'x-google-flag:conference'});
- }
-}
+/*
+ * Module requirements.
+ */
-//endregion
+var isArray = require('isarray');
-//region "Private" functions
+/**
+ * Module exports.
+ */
+
+module.exports = hasBinary;
/**
+ * Checks for binary data.
*
- * @param mLine
- * @private
+ * Right now only Buffer and ArrayBuffer are supported..
+ *
+ * @param {Object} anything
+ * @api public
*/
-Simulcast.prototype._maybeInitializeLayers = function(mLine) {
- if (!mLine || mLine.type !== 'video') {
- return;
- }
+function hasBinary(data) {
- var sources = parseSsrcs(mLine);
+ function _hasBinary(obj) {
+ if (!obj) return false;
- if (Object.keys(sources).length === 0) {
+ if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
+ (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
+ (global.Blob && obj instanceof Blob) ||
+ (global.File && obj instanceof File)
+ ) {
+ return true;
+ }
- // no sources, disable simulcast.
- if (this.layers.length !== 0) {
- this.layers = [];
- }
+ if (isArray(obj)) {
+ for (var i = 0; i < obj.length; i++) {
+ if (_hasBinary(obj[i])) {
+ return true;
+ }
+ }
+ } else if (obj && 'object' == typeof obj) {
+ if (obj.toJSON) {
+ obj = obj.toJSON();
+ }
- return;
+ for (var key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
+ return true;
+ }
+ }
}
- // find the base layer (we'll reuse its msid and cname).
- var baseLayerSSRC = Object.keys(sources)[0];
- var baseLayer = sources[baseLayerSSRC];
+ return false;
+ }
- // todo(gp) handle screen sharing.
+ return _hasBinary(data);
+}
- // check if base CNAME has changed and reinitialise layers.
- if (this.layers.length > 0
- && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
- this.layers = [];
- }
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"isarray":121}],121:[function(require,module,exports){
+arguments[4][112][0].apply(exports,arguments)
+},{"dup":112}],122:[function(require,module,exports){
- // (re)initialise layers
- if (this.layers.length < 1) {
+var indexOf = [].indexOf;
- // first push the base layer.
- this.layers.push({
- ssrc: baseLayerSSRC,
- msid: baseLayer.msid,
- cname: baseLayer.cname
- });
+module.exports = function(arr, obj){
+ if (indexOf) return arr.indexOf(obj);
+ for (var i = 0; i < arr.length; ++i) {
+ if (arr[i] === obj) return i;
+ }
+ return -1;
+};
+},{}],123:[function(require,module,exports){
- var rtx = false; // RFC 4588
- if (Array.isArray(mLine.rtp)) {
- rtx = mLine.rtp.some(
- function (rtpmap) { return rtpmap.codec === 'rtx'; });
- }
+/**
+ * HOP ref.
+ */
- if (rtx) {
- this.layers[0].rtx = generateSSRC();
- }
+var has = Object.prototype.hasOwnProperty;
- // now push additional layers.
- for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
+/**
+ * Return own keys in `obj`.
+ *
+ * @param {Object} obj
+ * @return {Array}
+ * @api public
+ */
- var layer = { ssrc: generateSSRC() };
- if (rtx) {
- layer.rtx = generateSSRC();
- }
+exports.keys = Object.keys || function(obj){
+ var keys = [];
+ for (var key in obj) {
+ if (has.call(obj, key)) {
+ keys.push(key);
+ }
+ }
+ return keys;
+};
- this.layers.push(layer);
- }
+/**
+ * Return own values in `obj`.
+ *
+ * @param {Object} obj
+ * @return {Array}
+ * @api public
+ */
+
+exports.values = function(obj){
+ var vals = [];
+ for (var key in obj) {
+ if (has.call(obj, key)) {
+ vals.push(obj[key]);
}
+ }
+ return vals;
};
/**
+ * Merge `b` into `a`.
*
- * @param mLine
- * @private
+ * @param {Object} a
+ * @param {Object} b
+ * @return {Object} a
+ * @api public
*/
-Simulcast.prototype._restoreSimulcastView = function(mLine) {
- if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
- var sources = {};
+exports.merge = function(a, b){
+ for (var key in b) {
+ if (has.call(b, key)) {
+ a[key] = b[key];
+ }
+ }
+ return a;
+};
- var msid = this.layers[0].msid;
- var cname = this.layers[0].cname;
- var simulcastSsrcs = [];
- var ssrcGroups = [];
+/**
+ * Return length of `obj`.
+ *
+ * @param {Object} obj
+ * @return {Number}
+ * @api public
+ */
- for (var i = 0; i < this.layers.length; i++) {
- var layer = this.layers[i];
+exports.length = function(obj){
+ return exports.keys(obj).length;
+};
- sources[layer.ssrc] = { msid: msid, cname: cname };
- simulcastSsrcs.push(layer.ssrc);
+/**
+ * Check if `obj` is empty.
+ *
+ * @param {Object} obj
+ * @return {Boolean}
+ * @api public
+ */
- if (layer.rtx) {
+exports.isEmpty = function(obj){
+ return 0 == exports.length(obj);
+};
+},{}],124:[function(require,module,exports){
+/**
+ * Parses an URI
+ *
+ * @author Steven Levithan <stevenlevithan.com> (MIT license)
+ * @api private
+ */
- sources[layer.rtx] = {
- msid: msid,
- cname: cname
- }
+var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
- ssrcGroups.push({
- semantics: 'FID',
- ssrcs: [layer.ssrc, layer.rtx].join(' ')
- });
- }
- }
+var parts = [
+ 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
+ , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
+];
- ssrcGroups.push({
- semantics: 'SIM',
- ssrcs: simulcastSsrcs.join(' ')
- });
+module.exports = function parseuri(str) {
+ var m = re.exec(str || '')
+ , uri = {}
+ , i = 14;
- mLine.ssrcGroups = ssrcGroups;
- mLine.ssrcs = writeSsrcs(sources);
- }
-}
+ while (i--) {
+ uri[parts[i]] = m[i] || '';
+ }
-//endregion
+ return uri;
+};
-//region "Public" functions
+},{}],125:[function(require,module,exports){
+(function (global){
+/*global Blob,File*/
-Simulcast.prototype.isSupported = function () {
- return window.chrome;
+/**
+ * Module requirements
+ */
- // TODO this needs improvements. For example I doubt that Chrome in Android
- // has simulcast support. Also, only recent versions of Chromium have native
- // simulcast support.
-}
+var isArray = require('isarray');
+var isBuf = require('./is-buffer');
/**
+ * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
+ * Anything with blobs or files should be fed through removeBlobs before coming
+ * here.
*
- * @param desc
- * @returns {RTCSessionDescription}
- */
-Simulcast.prototype.mungeRemoteDescription = function (desc) {
+ * @param {Object} packet - socket.io event packet
+ * @return {Object} with deconstructed packet and list of buffers
+ * @api public
+ */
+
+exports.deconstructPacket = function(packet){
+ var buffers = [];
+ var packetData = packet.data;
+
+ function _deconstructPacket(data) {
+ if (!data) return data;
+
+ if (isBuf(data)) {
+ var placeholder = { _placeholder: true, num: buffers.length };
+ buffers.push(data);
+ return placeholder;
+ } else if (isArray(data)) {
+ var newData = new Array(data.length);
+ for (var i = 0; i < data.length; i++) {
+ newData[i] = _deconstructPacket(data[i]);
+ }
+ return newData;
+ } else if ('object' == typeof data && !(data instanceof Date)) {
+ var newData = {};
+ for (var key in data) {
+ newData[key] = _deconstructPacket(data[key]);
+ }
+ return newData;
+ }
+ return data;
+ }
- if (!validateDescription(desc)) {
- return desc;
+ var pack = packet;
+ pack.data = _deconstructPacket(packetData);
+ pack.attachments = buffers.length; // number of binary 'attachments'
+ return {packet: pack, buffers: buffers};
+};
+
+/**
+ * Reconstructs a binary packet from its placeholder packet and buffers
+ *
+ * @param {Object} packet - event packet with placeholders
+ * @param {Array} buffers - binary buffers to put in placeholder positions
+ * @return {Object} reconstructed packet
+ * @api public
+ */
+
+exports.reconstructPacket = function(packet, buffers) {
+ var curPlaceHolder = 0;
+
+ function _reconstructPacket(data) {
+ if (data && data._placeholder) {
+ var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
+ return buf;
+ } else if (isArray(data)) {
+ for (var i = 0; i < data.length; i++) {
+ data[i] = _reconstructPacket(data[i]);
+ }
+ return data;
+ } else if (data && 'object' == typeof data) {
+ for (var key in data) {
+ data[key] = _reconstructPacket(data[key]);
+ }
+ return data;
}
+ return data;
+ }
- var session = transform.parse(desc.sdp);
+ packet.data = _reconstructPacket(packet.data);
+ packet.attachments = undefined; // no longer useful
+ return packet;
+};
- var self = this;
- processVideo(session, function (mLine) {
+/**
+ * Asynchronously removes Blobs or Files from data via
+ * FileReader's readAsArrayBuffer method. Used before encoding
+ * data as msgpack. Calls callback with the blobless data.
+ *
+ * @param {Object} data
+ * @param {Function} callback
+ * @api private
+ */
- // Handle simulcast reception.
- if (self.options.explodeRemoteSimulcast) {
- explodeRemoteSimulcast(mLine);
- } else {
- implodeRemoteSimulcast(mLine);
+exports.removeBlobs = function(data, callback) {
+ function _removeBlobs(obj, curKey, containingObject) {
+ if (!obj) return obj;
+
+ // convert any blob
+ if ((global.Blob && obj instanceof Blob) ||
+ (global.File && obj instanceof File)) {
+ pendingBlobs++;
+
+ // async filereader
+ var fileReader = new FileReader();
+ fileReader.onload = function() { // this.result == arraybuffer
+ if (containingObject) {
+ containingObject[curKey] = this.result;
+ }
+ else {
+ bloblessData = this.result;
}
- // If native simulcast is enabled, we must append the x-goog-conference
- // attribute to the SDP.
- if (self.layers.length < 1) {
- removeGoogConference(mLine);
- } else {
- assertGoogConference(mLine);
+ // if nothing pending its callback time
+ if(! --pendingBlobs) {
+ callback(bloblessData);
}
- });
+ };
- return new RTCSessionDescription({
- type: desc.type,
- sdp: transform.write(session)
- });
+ fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
+ } else if (isArray(obj)) { // handle array
+ for (var i = 0; i < obj.length; i++) {
+ _removeBlobs(obj[i], i, obj);
+ }
+ } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
+ for (var key in obj) {
+ _removeBlobs(obj[key], key, obj);
+ }
+ }
+ }
+
+ var pendingBlobs = 0;
+ var bloblessData = data;
+ _removeBlobs(bloblessData);
+ if (!pendingBlobs) {
+ callback(bloblessData);
+ }
};
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{"./is-buffer":127,"isarray":128}],126:[function(require,module,exports){
+
/**
+ * Module dependencies.
+ */
+
+var debug = require('debug')('socket.io-parser');
+var json = require('json3');
+var isArray = require('isarray');
+var Emitter = require('component-emitter');
+var binary = require('./binary');
+var isBuf = require('./is-buffer');
+
+/**
+ * Protocol version.
*
- * @param desc
- * @returns {RTCSessionDescription}
+ * @api public
*/
-Simulcast.prototype.mungeLocalDescription = function (desc) {
- if (!validateDescription(desc) || !this.isSupported()) {
- return desc;
- }
+exports.protocol = 4;
- var session = transform.parse(desc.sdp);
+/**
+ * Packet types.
+ *
+ * @api public
+ */
- var self = this;
- processVideo(session, function (mLine) {
- if (mLine.direction == 'recvonly' || mLine.direction == 'inactive')
- {
- return;
- }
- // Initialize native simulcast layers, if not already done.
- self._maybeInitializeLayers(mLine);
+exports.types = [
+ 'CONNECT',
+ 'DISCONNECT',
+ 'EVENT',
+ 'BINARY_EVENT',
+ 'ACK',
+ 'BINARY_ACK',
+ 'ERROR'
+];
- // Update the SDP with the simulcast layers.
- self._restoreSimulcastView(mLine);
- });
+/**
+ * Packet type `connect`.
+ *
+ * @api public
+ */
- return new RTCSessionDescription({
- type: desc.type,
- sdp: transform.write(session)
- });
-};
+exports.CONNECT = 0;
-//endregion
+/**
+ * Packet type `disconnect`.
+ *
+ * @api public
+ */
+
+exports.DISCONNECT = 1;
+
+/**
+ * Packet type `event`.
+ *
+ * @api public
+ */
-module.exports = Simulcast;
+exports.EVENT = 2;
-},{"./transform-utils":69,"sdp-transform":71}],69:[function(require,module,exports){
-/* Copyright @ 2015 Atlassian Pty Ltd
+/**
+ * Packet type `ack`.
*
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * @api public
+ */
+
+exports.ACK = 3;
+
+/**
+ * Packet type `error`.
*
- * http://www.apache.org/licenses/LICENSE-2.0
+ * @api public
+ */
+
+exports.ERROR = 4;
+
+/**
+ * Packet type 'binary event'
*
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
+ * @api public
*/
-exports.writeSsrcs = function(sources, order) {
- var ssrcs = [];
+exports.BINARY_EVENT = 5;
- // expand sources to ssrcs
- if (typeof sources !== 'undefined' &&
- Object.keys(sources).length !== 0) {
+/**
+ * Packet type `binary ack`. For acks with binary arguments.
+ *
+ * @api public
+ */
- if (Array.isArray(order)) {
- for (var i = 0; i < order.length; i++) {
- var ssrc = order[i];
- var source = sources[ssrc];
- Object.keys(source).forEach(function (attribute) {
- ssrcs.push({
- id: ssrc,
- attribute: attribute,
- value: source[attribute]
- });
- });
- }
- } else {
- Object.keys(sources).forEach(function (ssrc) {
- var source = sources[ssrc];
- Object.keys(source).forEach(function (attribute) {
- ssrcs.push({
- id: ssrc,
- attribute: attribute,
- value: source[attribute]
- });
- });
- });
- }
- }
+exports.BINARY_ACK = 6;
- return ssrcs;
-};
+/**
+ * Encoder constructor.
+ *
+ * @api public
+ */
-exports.parseSsrcs = function (mLine) {
- var sources = {};
- // group sources attributes by ssrc.
- if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
- mLine.ssrcs.forEach(function (ssrc) {
- if (!sources[ssrc.id])
- sources[ssrc.id] = {};
- sources[ssrc.id][ssrc.attribute] = ssrc.value;
- });
- }
- return sources;
-};
+exports.Encoder = Encoder;
+/**
+ * Decoder constructor.
+ *
+ * @api public
+ */
-},{}],70:[function(require,module,exports){
-var grammar = module.exports = {
- v: [{
- name: 'version',
- reg: /^(\d*)$/
- }],
- o: [{ //o=- 20518 0 IN IP4 203.0.113.1
- // NB: sessionId will be a String in most cases because it is huge
- name: 'origin',
- reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
- names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
- format: "%s %s %d %s IP%d %s"
- }],
- // default parsing of these only (though some of these feel outdated)
- s: [{ name: 'name' }],
- i: [{ name: 'description' }],
- u: [{ name: 'uri' }],
- e: [{ name: 'email' }],
- p: [{ name: 'phone' }],
- z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
- r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
- //k: [{}], // outdated thing ignored
- t: [{ //t=0 0
- name: 'timing',
- reg: /^(\d*) (\d*)/,
- names: ['start', 'stop'],
- format: "%d %d"
- }],
- c: [{ //c=IN IP4 10.47.197.26
- name: 'connection',
- reg: /^IN IP(\d) (\S*)/,
- names: ['version', 'ip'],
- format: "IN IP%d %s"
- }],
- b: [{ //b=AS:4000
- push: 'bandwidth',
- reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
- names: ['type', 'limit'],
- format: "%s:%s"
- }],
- m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
- // NB: special - pushes to session
- // TODO: rtp/fmtp should be filtered by the payloads found here?
- reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
- names: ['type', 'port', 'protocol', 'payloads'],
- format: "%s %d %s %s"
- }],
- a: [
- { //a=rtpmap:110 opus/48000/2
- push: 'rtp',
- reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
- names: ['payload', 'codec', 'rate', 'encoding'],
- format: function (o) {
- return (o.encoding) ?
- "rtpmap:%d %s/%s/%s":
- o.rate ?
- "rtpmap:%d %s/%s":
- "rtpmap:%d %s";
- }
- },
- {
- //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
- //a=fmtp:111 minptime=10; useinbandfec=1
- push: 'fmtp',
- reg: /^fmtp:(\d*) ([\S| ]*)/,
- names: ['payload', 'config'],
- format: "fmtp:%d %s"
- },
- { //a=control:streamid=0
- name: 'control',
- reg: /^control:(.*)/,
- format: "control:%s"
- },
- { //a=rtcp:65179 IN IP4 193.84.77.194
- name: 'rtcp',
- reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
- names: ['port', 'netType', 'ipVer', 'address'],
- format: function (o) {
- return (o.address != null) ?
- "rtcp:%d %s IP%d %s":
- "rtcp:%d";
- }
- },
- { //a=rtcp-fb:98 trr-int 100
- push: 'rtcpFbTrrInt',
- reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
- names: ['payload', 'value'],
- format: "rtcp-fb:%d trr-int %d"
- },
- { //a=rtcp-fb:98 nack rpsi
- push: 'rtcpFb',
- reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
- names: ['payload', 'type', 'subtype'],
- format: function (o) {
- return (o.subtype != null) ?
- "rtcp-fb:%s %s %s":
- "rtcp-fb:%s %s";
- }
- },
- { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
- //a=extmap:1/recvonly URI-gps-string
- push: 'ext',
- reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
- names: ['value', 'uri', 'config'], // value may include "/direction" suffix
- format: function (o) {
- return (o.config != null) ?
- "extmap:%s %s %s":
- "extmap:%s %s";
- }
- },
- {
- //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
- push: 'crypto',
- reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
- names: ['id', 'suite', 'config', 'sessionConfig'],
- format: function (o) {
- return (o.sessionConfig != null) ?
- "crypto:%d %s %s %s":
- "crypto:%d %s %s";
- }
- },
- { //a=setup:actpass
- name: 'setup',
- reg: /^setup:(\w*)/,
- format: "setup:%s"
- },
- { //a=mid:1
- name: 'mid',
- reg: /^mid:([^\s]*)/,
- format: "mid:%s"
- },
- { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
- name: 'msid',
- reg: /^msid:(.*)/,
- format: "msid:%s"
- },
- { //a=ptime:20
- name: 'ptime',
- reg: /^ptime:(\d*)/,
- format: "ptime:%d"
- },
- { //a=maxptime:60
- name: 'maxptime',
- reg: /^maxptime:(\d*)/,
- format: "maxptime:%d"
- },
- { //a=sendrecv
- name: 'direction',
- reg: /^(sendrecv|recvonly|sendonly|inactive)/
- },
- { //a=ice-lite
- name: 'icelite',
- reg: /^(ice-lite)/
- },
- { //a=ice-ufrag:F7gI
- name: 'iceUfrag',
- reg: /^ice-ufrag:(\S*)/,
- format: "ice-ufrag:%s"
- },
- { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
- name: 'icePwd',
- reg: /^ice-pwd:(\S*)/,
- format: "ice-pwd:%s"
- },
- { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
- name: 'fingerprint',
- reg: /^fingerprint:(\S*) (\S*)/,
- names: ['type', 'hash'],
- format: "fingerprint:%s %s"
- },
- {
- //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
- //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
- //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
- //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
- //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
- push:'candidates',
- reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
- names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
- format: function (o) {
- var str = "candidate:%s %d %s %d %s %d typ %s";
+exports.Decoder = Decoder;
- str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
+/**
+ * A socket.io Encoder instance
+ *
+ * @api public
+ */
- // NB: candidate has three optional chunks, so %void middles one if it's missing
- str += (o.tcptype != null) ? " tcptype %s" : "%v";
+function Encoder() {}
- if (o.generation != null) {
- str += " generation %d";
- }
- return str;
- }
- },
- { //a=end-of-candidates (keep after the candidates line for readability)
- name: 'endOfCandidates',
- reg: /^(end-of-candidates)/
- },
- { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
- name: 'remoteCandidates',
- reg: /^remote-candidates:(.*)/,
- format: "remote-candidates:%s"
- },
- { //a=ice-options:google-ice
- name: 'iceOptions',
- reg: /^ice-options:(\S*)/,
- format: "ice-options:%s"
- },
- { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
- push: "ssrcs",
- reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
- names: ['id', 'attribute', 'value'],
- format: "ssrc:%d %s:%s"
- },
- { //a=ssrc-group:FEC 1 2
- push: "ssrcGroups",
- reg: /^ssrc-group:(\w*) (.*)/,
- names: ['semantics', 'ssrcs'],
- format: "ssrc-group:%s %s"
- },
- { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
- name: "msidSemantic",
- reg: /^msid-semantic:\s?(\w*) (\S*)/,
- names: ['semantic', 'token'],
- format: "msid-semantic: %s %s" // space after ":" is not accidental
- },
- { //a=group:BUNDLE audio video
- push: 'groups',
- reg: /^group:(\w*) (.*)/,
- names: ['type', 'mids'],
- format: "group:%s %s"
- },
- { //a=rtcp-mux
- name: 'rtcpMux',
- reg: /^(rtcp-mux)/
- },
- { //a=rtcp-rsize
- name: 'rtcpRsize',
- reg: /^(rtcp-rsize)/
- },
- { // any a= that we don't understand is kepts verbatim on media.invalid
- push: 'invalid',
- names: ["value"]
- }
- ]
+/**
+ * Encode a packet as a single string if non-binary, or as a
+ * buffer sequence, depending on packet type.
+ *
+ * @param {Object} obj - packet object
+ * @param {Function} callback - function to handle encodings (likely engine.write)
+ * @return Calls callback with Array of encodings
+ * @api public
+ */
+
+Encoder.prototype.encode = function(obj, callback){
+ debug('encoding packet %j', obj);
+
+ if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
+ encodeAsBinary(obj, callback);
+ }
+ else {
+ var encoding = encodeAsString(obj);
+ callback([encoding]);
+ }
};
-// set sensible defaults to avoid polluting the grammar with boring details
-Object.keys(grammar).forEach(function (key) {
- var objs = grammar[key];
- objs.forEach(function (obj) {
- if (!obj.reg) {
- obj.reg = /(.*)/;
- }
- if (!obj.format) {
- obj.format = "%s";
+/**
+ * Encode packet as string.
+ *
+ * @param {Object} packet
+ * @return {String} encoded
+ * @api private
+ */
+
+function encodeAsString(obj) {
+ var str = '';
+ var nsp = false;
+
+ // first is type
+ str += obj.type;
+
+ // attachments if we have them
+ if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
+ str += obj.attachments;
+ str += '-';
+ }
+
+ // if we have a namespace other than `/`
+ // we append it followed by a comma `,`
+ if (obj.nsp && '/' != obj.nsp) {
+ nsp = true;
+ str += obj.nsp;
+ }
+
+ // immediately followed by the id
+ if (null != obj.id) {
+ if (nsp) {
+ str += ',';
+ nsp = false;
}
- });
-});
+ str += obj.id;
+ }
-},{}],71:[function(require,module,exports){
-var parser = require('./parser');
-var writer = require('./writer');
+ // json data
+ if (null != obj.data) {
+ if (nsp) str += ',';
+ str += json.stringify(obj.data);
+ }
-exports.write = writer;
-exports.parse = parser.parse;
-exports.parseFmtpConfig = parser.parseFmtpConfig;
-exports.parsePayloads = parser.parsePayloads;
-exports.parseRemoteCandidates = parser.parseRemoteCandidates;
+ debug('encoded %j as %s', obj, str);
+ return str;
+}
-},{"./parser":72,"./writer":73}],72:[function(require,module,exports){
-var toIntIfInt = function (v) {
- return String(Number(v)) === v ? Number(v) : v;
-};
+/**
+ * Encode packet as 'buffer sequence' by removing blobs, and
+ * deconstructing packet into object with placeholders and
+ * a list of buffers.
+ *
+ * @param {Object} packet
+ * @return {Buffer} encoded
+ * @api private
+ */
-var attachProperties = function (match, location, names, rawName) {
- if (rawName && !names) {
- location[rawName] = toIntIfInt(match[1]);
+function encodeAsBinary(obj, callback) {
+
+ function writeEncoding(bloblessData) {
+ var deconstruction = binary.deconstructPacket(bloblessData);
+ var pack = encodeAsString(deconstruction.packet);
+ var buffers = deconstruction.buffers;
+
+ buffers.unshift(pack); // add packet info to beginning of data list
+ callback(buffers); // write all the buffers
}
- else {
- for (var i = 0; i < names.length; i += 1) {
- if (match[i+1] != null) {
- location[names[i]] = toIntIfInt(match[i+1]);
+
+ binary.removeBlobs(obj, writeEncoding);
+}
+
+/**
+ * A socket.io Decoder instance
+ *
+ * @return {Object} decoder
+ * @api public
+ */
+
+function Decoder() {
+ this.reconstructor = null;
+}
+
+/**
+ * Mix in `Emitter` with Decoder.
+ */
+
+Emitter(Decoder.prototype);
+
+/**
+ * Decodes an ecoded packet string into packet JSON.
+ *
+ * @param {String} obj - encoded packet
+ * @return {Object} packet
+ * @api public
+ */
+
+Decoder.prototype.add = function(obj) {
+ var packet;
+ if ('string' == typeof obj) {
+ packet = decodeString(obj);
+ if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
+ this.reconstructor = new BinaryReconstructor(packet);
+
+ // no attachments, labeled binary but no binary data to follow
+ if (this.reconstructor.reconPack.attachments === 0) {
+ this.emit('decoded', packet);
+ }
+ } else { // non-binary full packet
+ this.emit('decoded', packet);
+ }
+ }
+ else if (isBuf(obj) || obj.base64) { // raw binary data
+ if (!this.reconstructor) {
+ throw new Error('got binary data when not reconstructing a packet');
+ } else {
+ packet = this.reconstructor.takeBinaryData(obj);
+ if (packet) { // received final buffer
+ this.reconstructor = null;
+ this.emit('decoded', packet);
}
}
}
+ else {
+ throw new Error('Unknown type: ' + obj);
+ }
};
-var parseReg = function (obj, location, content) {
- var needsBlank = obj.name && obj.names;
- if (obj.push && !location[obj.push]) {
- location[obj.push] = [];
+/**
+ * Decode a packet String (JSON data)
+ *
+ * @param {String} str
+ * @return {Object} packet
+ * @api private
+ */
+
+function decodeString(str) {
+ var p = {};
+ var i = 0;
+
+ // look up type
+ p.type = Number(str.charAt(0));
+ if (null == exports.types[p.type]) return error();
+
+ // look up attachments if type binary
+ if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
+ var buf = '';
+ while (str.charAt(++i) != '-') {
+ buf += str.charAt(i);
+ if (i == str.length) break;
+ }
+ if (buf != Number(buf) || str.charAt(i) != '-') {
+ throw new Error('Illegal attachments');
+ }
+ p.attachments = Number(buf);
}
- else if (needsBlank && !location[obj.name]) {
- location[obj.name] = {};
+
+ // look up namespace (if any)
+ if ('/' == str.charAt(i + 1)) {
+ p.nsp = '';
+ while (++i) {
+ var c = str.charAt(i);
+ if (',' == c) break;
+ p.nsp += c;
+ if (i == str.length) break;
+ }
+ } else {
+ p.nsp = '/';
}
- var keyLocation = obj.push ?
- {} : // blank object that will be pushed
- needsBlank ? location[obj.name] : location; // otherwise, named location or root
- attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
+ // look up id
+ var next = str.charAt(i + 1);
+ if ('' !== next && Number(next) == next) {
+ p.id = '';
+ while (++i) {
+ var c = str.charAt(i);
+ if (null == c || Number(c) != c) {
+ --i;
+ break;
+ }
+ p.id += str.charAt(i);
+ if (i == str.length) break;
+ }
+ p.id = Number(p.id);
+ }
- if (obj.push) {
- location[obj.push].push(keyLocation);
+ // look up json data
+ if (str.charAt(++i)) {
+ try {
+ p.data = json.parse(str.substr(i));
+ } catch(e){
+ return error();
+ }
+ }
+
+ debug('decoded %s as %j', str, p);
+ return p;
+}
+
+/**
+ * Deallocates a parser's resources
+ *
+ * @api public
+ */
+
+Decoder.prototype.destroy = function() {
+ if (this.reconstructor) {
+ this.reconstructor.finishedReconstruction();
+ }
+};
+
+/**
+ * A manager of a binary event's 'buffer sequence'. Should
+ * be constructed whenever a packet of type BINARY_EVENT is
+ * decoded.
+ *
+ * @param {Object} packet
+ * @return {BinaryReconstructor} initialized reconstructor
+ * @api private
+ */
+
+function BinaryReconstructor(packet) {
+ this.reconPack = packet;
+ this.buffers = [];
+}
+
+/**
+ * Method to be called when binary data received from connection
+ * after a BINARY_EVENT packet.
+ *
+ * @param {Buffer | ArrayBuffer} binData - the raw binary data received
+ * @return {null | Object} returns null if more binary data is expected or
+ * a reconstructed packet object if all buffers have been received.
+ * @api private
+ */
+
+BinaryReconstructor.prototype.takeBinaryData = function(binData) {
+ this.buffers.push(binData);
+ if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
+ var packet = binary.reconstructPacket(this.reconPack, this.buffers);
+ this.finishedReconstruction();
+ return packet;
}
+ return null;
+};
+
+/**
+ * Cleans up binary packet reconstruction variables.
+ *
+ * @api private
+ */
+
+BinaryReconstructor.prototype.finishedReconstruction = function() {
+ this.reconPack = null;
+ this.buffers = [];
};
-var grammar = require('./grammar');
-var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
+function error(data){
+ return {
+ type: exports.ERROR,
+ data: 'parser error'
+ };
+}
+
+},{"./binary":125,"./is-buffer":127,"component-emitter":89,"debug":90,"isarray":128,"json3":129}],127:[function(require,module,exports){
+(function (global){
+
+module.exports = isBuf;
+
+/**
+ * Returns true if obj is a buffer or an arraybuffer.
+ *
+ * @api private
+ */
+
+function isBuf(obj) {
+ return (global.Buffer && global.Buffer.isBuffer(obj)) ||
+ (global.ArrayBuffer && obj instanceof ArrayBuffer);
+}
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],128:[function(require,module,exports){
+arguments[4][112][0].apply(exports,arguments)
+},{"dup":112}],129:[function(require,module,exports){
+/*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
+;(function (window) {
+ // Convenience aliases.
+ var getClass = {}.toString, isProperty, forEach, undef;
+
+ // Detect the `define` function exposed by asynchronous module loaders. The
+ // strict `define` check is necessary for compatibility with `r.js`.
+ var isLoader = typeof define === "function" && define.amd;
+
+ // Detect native implementations.
+ var nativeJSON = typeof JSON == "object" && JSON;
+
+ // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
+ // available.
+ var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
+
+ if (JSON3 && nativeJSON) {
+ // Explicitly delegate to the native `stringify` and `parse`
+ // implementations in CommonJS environments.
+ JSON3.stringify = nativeJSON.stringify;
+ JSON3.parse = nativeJSON.parse;
+ } else {
+ // Export for web browsers, JavaScript engines, and asynchronous module
+ // loaders, using the global `JSON` object if available.
+ JSON3 = window.JSON = nativeJSON || {};
+ }
+
+ // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
+ var isExtended = new Date(-3509827334573292);
+ try {
+ // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
+ // results for certain dates in Opera >= 10.53.
+ isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
+ // Safari < 2.0.2 stores the internal millisecond time value correctly,
+ // but clips the values returned by the date methods to the range of
+ // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
+ isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
+ } catch (exception) {}
+
+ // Internal: Determines whether the native `JSON.stringify` and `parse`
+ // implementations are spec-compliant. Based on work by Ken Snyder.
+ function has(name) {
+ if (has[name] !== undef) {
+ // Return cached feature test result.
+ return has[name];
+ }
+
+ var isSupported;
+ if (name == "bug-string-char-index") {
+ // IE <= 7 doesn't support accessing string characters using square
+ // bracket notation. IE 8 only supports this for primitives.
+ isSupported = "a"[0] != "a";
+ } else if (name == "json") {
+ // Indicates whether both `JSON.stringify` and `JSON.parse` are
+ // supported.
+ isSupported = has("json-stringify") && has("json-parse");
+ } else {
+ var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
+ // Test `JSON.stringify`.
+ if (name == "json-stringify") {
+ var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
+ if (stringifySupported) {
+ // A test function object with a custom `toJSON` method.
+ (value = function () {
+ return 1;
+ }).toJSON = value;
+ try {
+ stringifySupported =
+ // Firefox 3.1b1 and b2 serialize string, number, and boolean
+ // primitives as object literals.
+ stringify(0) === "0" &&
+ // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
+ // literals.
+ stringify(new Number()) === "0" &&
+ stringify(new String()) == '""' &&
+ // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
+ // does not define a canonical JSON representation (this applies to
+ // objects with `toJSON` properties as well, *unless* they are nested
+ // within an object or array).
+ stringify(getClass) === undef &&
+ // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
+ // FF 3.1b3 pass this test.
+ stringify(undef) === undef &&
+ // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
+ // respectively, if the value is omitted entirely.
+ stringify() === undef &&
+ // FF 3.1b1, 2 throw an error if the given value is not a number,
+ // string, array, object, Boolean, or `null` literal. This applies to
+ // objects with custom `toJSON` methods as well, unless they are nested
+ // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
+ // methods entirely.
+ stringify(value) === "1" &&
+ stringify([value]) == "[1]" &&
+ // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
+ // `"[null]"`.
+ stringify([undef]) == "[null]" &&
+ // YUI 3.0.0b1 fails to serialize `null` literals.
+ stringify(null) == "null" &&
+ // FF 3.1b1, 2 halts serialization if an array contains a function:
+ // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
+ // elides non-JSON values from objects and arrays, unless they
+ // define custom `toJSON` methods.
+ stringify([undef, getClass, null]) == "[null,null,null]" &&
+ // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
+ // where character escape codes are expected (e.g., `\b` => `\u0008`).
+ stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
+ // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
+ stringify(null, value) === "1" &&
+ stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
+ // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
+ // serialize extended years.
+ stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
+ // The milliseconds are optional in ES 5, but required in 5.1.
+ stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
+ // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
+ // four-digit years instead of six-digit years. Credits: @Yaffle.
+ stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
+ // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
+ // values less than 1000. Credits: @Yaffle.
+ stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
+ } catch (exception) {
+ stringifySupported = false;
+ }
+ }
+ isSupported = stringifySupported;
+ }
+ // Test `JSON.parse`.
+ if (name == "json-parse") {
+ var parse = JSON3.parse;
+ if (typeof parse == "function") {
+ try {
+ // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
+ // Conforming implementations should also coerce the initial argument to
+ // a string prior to parsing.
+ if (parse("0") === 0 && !parse(false)) {
+ // Simple parsing test.
+ value = parse(serialized);
+ var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
+ if (parseSupported) {
+ try {
+ // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
+ parseSupported = !parse('"\t"');
+ } catch (exception) {}
+ if (parseSupported) {
+ try {
+ // FF 4.0 and 4.0.1 allow leading `+` signs and leading
+ // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
+ // certain octal literals.
+ parseSupported = parse("01") !== 1;
+ } catch (exception) {}
+ }
+ if (parseSupported) {
+ try {
+ // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
+ // points. These environments, along with FF 3.1b1 and 2,
+ // also allow trailing commas in JSON objects and arrays.
+ parseSupported = parse("1.") !== 1;
+ } catch (exception) {}
+ }
+ }
+ }
+ } catch (exception) {
+ parseSupported = false;
+ }
+ }
+ isSupported = parseSupported;
+ }
+ }
+ return has[name] = !!isSupported;
+ }
+
+ if (!has("json")) {
+ // Common `[[Class]]` name aliases.
+ var functionClass = "[object Function]";
+ var dateClass = "[object Date]";
+ var numberClass = "[object Number]";
+ var stringClass = "[object String]";
+ var arrayClass = "[object Array]";
+ var booleanClass = "[object Boolean]";
+
+ // Detect incomplete support for accessing string characters by index.
+ var charIndexBuggy = has("bug-string-char-index");
+
+ // Define additional utility methods if the `Date` methods are buggy.
+ if (!isExtended) {
+ var floor = Math.floor;
+ // A mapping between the months of the year and the number of days between
+ // January 1st and the first of the respective month.
+ var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
+ // Internal: Calculates the number of days between the Unix epoch and the
+ // first day of the given month.
+ var getDay = function (year, month) {
+ return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
+ };
+ }
+
+ // Internal: Determines if a property is a direct property of the given
+ // object. Delegates to the native `Object#hasOwnProperty` method.
+ if (!(isProperty = {}.hasOwnProperty)) {
+ isProperty = function (property) {
+ var members = {}, constructor;
+ if ((members.__proto__ = null, members.__proto__ = {
+ // The *proto* property cannot be set multiple times in recent
+ // versions of Firefox and SeaMonkey.
+ "toString": 1
+ }, members).toString != getClass) {
+ // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
+ // supports the mutable *proto* property.
+ isProperty = function (property) {
+ // Capture and break the object's prototype chain (see section 8.6.2
+ // of the ES 5.1 spec). The parenthesized expression prevents an
+ // unsafe transformation by the Closure Compiler.
+ var original = this.__proto__, result = property in (this.__proto__ = null, this);
+ // Restore the original prototype chain.
+ this.__proto__ = original;
+ return result;
+ };
+ } else {
+ // Capture a reference to the top-level `Object` constructor.
+ constructor = members.constructor;
+ // Use the `constructor` property to simulate `Object#hasOwnProperty` in
+ // other environments.
+ isProperty = function (property) {
+ var parent = (this.constructor || constructor).prototype;
+ return property in this && !(property in parent && this[property] === parent[property]);
+ };
+ }
+ members = null;
+ return isProperty.call(this, property);
+ };
+ }
+
+ // Internal: A set of primitive types used by `isHostType`.
+ var PrimitiveTypes = {
+ 'boolean': 1,
+ 'number': 1,
+ 'string': 1,
+ 'undefined': 1
+ };
+
+ // Internal: Determines if the given object `property` value is a
+ // non-primitive.
+ var isHostType = function (object, property) {
+ var type = typeof object[property];
+ return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
+ };
+
+ // Internal: Normalizes the `for...in` iteration algorithm across
+ // environments. Each enumerated key is yielded to a `callback` function.
+ forEach = function (object, callback) {
+ var size = 0, Properties, members, property;
+
+ // Tests for bugs in the current environment's `for...in` algorithm. The
+ // `valueOf` property inherits the non-enumerable flag from
+ // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
+ (Properties = function () {
+ this.valueOf = 0;
+ }).prototype.valueOf = 0;
+
+ // Iterate over a new instance of the `Properties` class.
+ members = new Properties();
+ for (property in members) {
+ // Ignore all properties inherited from `Object.prototype`.
+ if (isProperty.call(members, property)) {
+ size++;
+ }
+ }
+ Properties = members = null;
+
+ // Normalize the iteration algorithm.
+ if (!size) {
+ // A list of non-enumerable properties inherited from `Object.prototype`.
+ members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
+ // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
+ // properties.
+ forEach = function (object, callback) {
+ var isFunction = getClass.call(object) == functionClass, property, length;
+ var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
+ for (property in object) {
+ // Gecko <= 1.0 enumerates the `prototype` property of functions under
+ // certain conditions; IE does not.
+ if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
+ callback(property);
+ }
+ }
+ // Manually invoke the callback for each non-enumerable property.
+ for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
+ };
+ } else if (size == 2) {
+ // Safari <= 2.0.4 enumerates shadowed properties twice.
+ forEach = function (object, callback) {
+ // Create a set of iterated properties.
+ var members = {}, isFunction = getClass.call(object) == functionClass, property;
+ for (property in object) {
+ // Store each property name to prevent double enumeration. The
+ // `prototype` property of functions is not enumerated due to cross-
+ // environment inconsistencies.
+ if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
+ callback(property);
+ }
+ }
+ };
+ } else {
+ // No bugs detected; use the standard `for...in` algorithm.
+ forEach = function (object, callback) {
+ var isFunction = getClass.call(object) == functionClass, property, isConstructor;
+ for (property in object) {
+ if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
+ callback(property);
+ }
+ }
+ // Manually invoke the callback for the `constructor` property due to
+ // cross-environment inconsistencies.
+ if (isConstructor || isProperty.call(object, (property = "constructor"))) {
+ callback(property);
+ }
+ };
+ }
+ return forEach(object, callback);
+ };
+
+ // Public: Serializes a JavaScript `value` as a JSON string. The optional
+ // `filter` argument may specify either a function that alters how object and
+ // array members are serialized, or an array of strings and numbers that
+ // indicates which properties should be serialized. The optional `width`
+ // argument may be either a string or number that specifies the indentation
+ // level of the output.
+ if (!has("json-stringify")) {
+ // Internal: A map of control characters and their escaped equivalents.
+ var Escapes = {
+ 92: "\\\\",
+ 34: '\\"',
+ 8: "\\b",
+ 12: "\\f",
+ 10: "\\n",
+ 13: "\\r",
+ 9: "\\t"
+ };
-exports.parse = function (sdp) {
- var session = {}
- , media = []
- , location = session; // points at where properties go under (one of the above)
+ // Internal: Converts `value` into a zero-padded string such that its
+ // length is at least equal to `width`. The `width` must be <= 6.
+ var leadingZeroes = "000000";
+ var toPaddedString = function (width, value) {
+ // The `|| 0` expression is necessary to work around a bug in
+ // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
+ return (leadingZeroes + (value || 0)).slice(-width);
+ };
- // parse lines we understand
- sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
- var type = l[0];
- var content = l.slice(2);
- if (type === 'm') {
- media.push({rtp: [], fmtp: []});
- location = media[media.length-1]; // point at latest media line
- }
+ // Internal: Double-quotes a string `value`, replacing all ASCII control
+ // characters (characters with code unit values between 0 and 31) with
+ // their escaped equivalents. This is an implementation of the
+ // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
+ var unicodePrefix = "\\u00";
+ var quote = function (value) {
+ var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
+ if (isLarge) {
+ symbols = value.split("");
+ }
+ for (; index < length; index++) {
+ var charCode = value.charCodeAt(index);
+ // If the character is a control character, append its Unicode or
+ // shorthand escape sequence; otherwise, append the character as-is.
+ switch (charCode) {
+ case 8: case 9: case 10: case 12: case 13: case 34: case 92:
+ result += Escapes[charCode];
+ break;
+ default:
+ if (charCode < 32) {
+ result += unicodePrefix + toPaddedString(2, charCode.toString(16));
+ break;
+ }
+ result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
+ }
+ }
+ return result + '"';
+ };
- for (var j = 0; j < (grammar[type] || []).length; j += 1) {
- var obj = grammar[type][j];
- if (obj.reg.test(content)) {
- return parseReg(obj, location, content);
- }
- }
- });
+ // Internal: Recursively serializes an object. Implements the
+ // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
+ var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
+ var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
+ try {
+ // Necessary for host object support.
+ value = object[property];
+ } catch (exception) {}
+ if (typeof value == "object" && value) {
+ className = getClass.call(value);
+ if (className == dateClass && !isProperty.call(value, "toJSON")) {
+ if (value > -1 / 0 && value < 1 / 0) {
+ // Dates are serialized according to the `Date#toJSON` method
+ // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
+ // for the ISO 8601 date time string format.
+ if (getDay) {
+ // Manually compute the year, month, date, hours, minutes,
+ // seconds, and milliseconds if the `getUTC*` methods are
+ // buggy. Adapted from @Yaffle's `date-shim` project.
+ date = floor(value / 864e5);
+ for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
+ for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
+ date = 1 + date - getDay(year, month);
+ // The `time` value specifies the time within the day (see ES
+ // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
+ // to compute `A modulo B`, as the `%` operator does not
+ // correspond to the `modulo` operation for negative numbers.
+ time = (value % 864e5 + 864e5) % 864e5;
+ // The hours, minutes, seconds, and milliseconds are obtained by
+ // decomposing the time within the day. See section 15.9.1.10.
+ hours = floor(time / 36e5) % 24;
+ minutes = floor(time / 6e4) % 60;
+ seconds = floor(time / 1e3) % 60;
+ milliseconds = time % 1e3;
+ } else {
+ year = value.getUTCFullYear();
+ month = value.getUTCMonth();
+ date = value.getUTCDate();
+ hours = value.getUTCHours();
+ minutes = value.getUTCMinutes();
+ seconds = value.getUTCSeconds();
+ milliseconds = value.getUTCMilliseconds();
+ }
+ // Serialize extended years correctly.
+ value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
+ "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
+ // Months, dates, hours, minutes, and seconds should have two
+ // digits; milliseconds should have three.
+ "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
+ // Milliseconds are optional in ES 5.0, but required in 5.1.
+ "." + toPaddedString(3, milliseconds) + "Z";
+ } else {
+ value = null;
+ }
+ } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
+ // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
+ // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
+ // ignores all `toJSON` methods on these objects unless they are
+ // defined directly on an instance.
+ value = value.toJSON(property);
+ }
+ }
+ if (callback) {
+ // If a replacement function was provided, call it to obtain the value
+ // for serialization.
+ value = callback.call(object, property, value);
+ }
+ if (value === null) {
+ return "null";
+ }
+ className = getClass.call(value);
+ if (className == booleanClass) {
+ // Booleans are represented literally.
+ return "" + value;
+ } else if (className == numberClass) {
+ // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
+ // `"null"`.
+ return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
+ } else if (className == stringClass) {
+ // Strings are double-quoted and escaped.
+ return quote("" + value);
+ }
+ // Recursively serialize objects and arrays.
+ if (typeof value == "object") {
+ // Check for cyclic structures. This is a linear search; performance
+ // is inversely proportional to the number of unique nested objects.
+ for (length = stack.length; length--;) {
+ if (stack[length] === value) {
+ // Cyclic structures cannot be serialized by `JSON.stringify`.
+ throw TypeError();
+ }
+ }
+ // Add the object to the stack of traversed objects.
+ stack.push(value);
+ results = [];
+ // Save the current indentation level and indent one additional level.
+ prefix = indentation;
+ indentation += whitespace;
+ if (className == arrayClass) {
+ // Recursively serialize array elements.
+ for (index = 0, length = value.length; index < length; index++) {
+ element = serialize(index, value, callback, properties, whitespace, indentation, stack);
+ results.push(element === undef ? "null" : element);
+ }
+ result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
+ } else {
+ // Recursively serialize object members. Members are selected from
+ // either a user-specified list of property names, or the object
+ // itself.
+ forEach(properties || value, function (property) {
+ var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
+ if (element !== undef) {
+ // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
+ // is not the empty string, let `member` {quote(property) + ":"}
+ // be the concatenation of `member` and the `space` character."
+ // The "`space` character" refers to the literal space
+ // character, not the `space` {width} argument provided to
+ // `JSON.stringify`.
+ results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
+ }
+ });
+ result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
+ }
+ // Remove the object from the traversed object stack.
+ stack.pop();
+ return result;
+ }
+ };
- session.media = media; // link it up
- return session;
-};
+ // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
+ JSON3.stringify = function (source, filter, width) {
+ var whitespace, callback, properties, className;
+ if (typeof filter == "function" || typeof filter == "object" && filter) {
+ if ((className = getClass.call(filter)) == functionClass) {
+ callback = filter;
+ } else if (className == arrayClass) {
+ // Convert the property names array into a makeshift set.
+ properties = {};
+ for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
+ }
+ }
+ if (width) {
+ if ((className = getClass.call(width)) == numberClass) {
+ // Convert the `width` to an integer and create a string containing
+ // `width` number of space characters.
+ if ((width -= width % 1) > 0) {
+ for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
+ }
+ } else if (className == stringClass) {
+ whitespace = width.length <= 10 ? width : width.slice(0, 10);
+ }
+ }
+ // Opera <= 7.54u2 discards the values associated with empty string keys
+ // (`""`) only if they are used directly within an object member list
+ // (e.g., `!("" in { "": 1})`).
+ return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
+ };
+ }
-var fmtpReducer = function (acc, expr) {
- var s = expr.split('=');
- if (s.length === 2) {
- acc[s[0]] = toIntIfInt(s[1]);
- }
- return acc;
-};
+ // Public: Parses a JSON source string.
+ if (!has("json-parse")) {
+ var fromCharCode = String.fromCharCode;
+
+ // Internal: A map of escaped control characters and their unescaped
+ // equivalents.
+ var Unescapes = {
+ 92: "\\",
+ 34: '"',
+ 47: "/",
+ 98: "\b",
+ 116: "\t",
+ 110: "\n",
+ 102: "\f",
+ 114: "\r"
+ };
-exports.parseFmtpConfig = function (str) {
- return str.split(/\;\s?/).reduce(fmtpReducer, {});
-};
+ // Internal: Stores the parser state.
+ var Index, Source;
-exports.parsePayloads = function (str) {
- return str.split(' ').map(Number);
-};
+ // Internal: Resets the parser state and throws a `SyntaxError`.
+ var abort = function() {
+ Index = Source = null;
+ throw SyntaxError();
+ };
-exports.parseRemoteCandidates = function (str) {
- var candidates = [];
- var parts = str.split(' ').map(toIntIfInt);
- for (var i = 0; i < parts.length; i += 3) {
- candidates.push({
- component: parts[i],
- ip: parts[i + 1],
- port: parts[i + 2]
- });
- }
- return candidates;
-};
+ // Internal: Returns the next token, or `"$"` if the parser has reached
+ // the end of the source string. A token may be a string, number, `null`
+ // literal, or Boolean literal.
+ var lex = function () {
+ var source = Source, length = source.length, value, begin, position, isSigned, charCode;
+ while (Index < length) {
+ charCode = source.charCodeAt(Index);
+ switch (charCode) {
+ case 9: case 10: case 13: case 32:
+ // Skip whitespace tokens, including tabs, carriage returns, line
+ // feeds, and space characters.
+ Index++;
+ break;
+ case 123: case 125: case 91: case 93: case 58: case 44:
+ // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
+ // the current position.
+ value = charIndexBuggy ? source.charAt(Index) : source[Index];
+ Index++;
+ return value;
+ case 34:
+ // `"` delimits a JSON string; advance to the next character and
+ // begin parsing the string. String tokens are prefixed with the
+ // sentinel `@` character to distinguish them from punctuators and
+ // end-of-string tokens.
+ for (value = "@", Index++; Index < length;) {
+ charCode = source.charCodeAt(Index);
+ if (charCode < 32) {
+ // Unescaped ASCII control characters (those with a code unit
+ // less than the space character) are not permitted.
+ abort();
+ } else if (charCode == 92) {
+ // A reverse solidus (`\`) marks the beginning of an escaped
+ // control character (including `"`, `\`, and `/`) or Unicode
+ // escape sequence.
+ charCode = source.charCodeAt(++Index);
+ switch (charCode) {
+ case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
+ // Revive escaped control characters.
+ value += Unescapes[charCode];
+ Index++;
+ break;
+ case 117:
+ // `\u` marks the beginning of a Unicode escape sequence.
+ // Advance to the first character and validate the
+ // four-digit code point.
+ begin = ++Index;
+ for (position = Index + 4; Index < position; Index++) {
+ charCode = source.charCodeAt(Index);
+ // A valid sequence comprises four hexdigits (case-
+ // insensitive) that form a single hexadecimal value.
+ if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
+ // Invalid Unicode escape sequence.
+ abort();
+ }
+ }
+ // Revive the escaped character.
+ value += fromCharCode("0x" + source.slice(begin, Index));
+ break;
+ default:
+ // Invalid escape sequence.
+ abort();
+ }
+ } else {
+ if (charCode == 34) {
+ // An unescaped double-quote character marks the end of the
+ // string.
+ break;
+ }
+ charCode = source.charCodeAt(Index);
+ begin = Index;
+ // Optimize for the common case where a string is valid.
+ while (charCode >= 32 && charCode != 92 && charCode != 34) {
+ charCode = source.charCodeAt(++Index);
+ }
+ // Append the string as-is.
+ value += source.slice(begin, Index);
+ }
+ }
+ if (source.charCodeAt(Index) == 34) {
+ // Advance to the next character and return the revived string.
+ Index++;
+ return value;
+ }
+ // Unterminated string.
+ abort();
+ default:
+ // Parse numbers and literals.
+ begin = Index;
+ // Advance past the negative sign, if one is specified.
+ if (charCode == 45) {
+ isSigned = true;
+ charCode = source.charCodeAt(++Index);
+ }
+ // Parse an integer or floating-point value.
+ if (charCode >= 48 && charCode <= 57) {
+ // Leading zeroes are interpreted as octal literals.
+ if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
+ // Illegal octal literal.
+ abort();
+ }
+ isSigned = false;
+ // Parse the integer component.
+ for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
+ // Floats cannot contain a leading decimal point; however, this
+ // case is already accounted for by the parser.
+ if (source.charCodeAt(Index) == 46) {
+ position = ++Index;
+ // Parse the decimal component.
+ for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
+ if (position == Index) {
+ // Illegal trailing decimal.
+ abort();
+ }
+ Index = position;
+ }
+ // Parse exponents. The `e` denoting the exponent is
+ // case-insensitive.
+ charCode = source.charCodeAt(Index);
+ if (charCode == 101 || charCode == 69) {
+ charCode = source.charCodeAt(++Index);
+ // Skip past the sign following the exponent, if one is
+ // specified.
+ if (charCode == 43 || charCode == 45) {
+ Index++;
+ }
+ // Parse the exponential component.
+ for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
+ if (position == Index) {
+ // Illegal empty exponent.
+ abort();
+ }
+ Index = position;
+ }
+ // Coerce the parsed value to a JavaScript number.
+ return +source.slice(begin, Index);
+ }
+ // A negative sign may only precede numbers.
+ if (isSigned) {
+ abort();
+ }
+ // `true`, `false`, and `null` literals.
+ if (source.slice(Index, Index + 4) == "true") {
+ Index += 4;
+ return true;
+ } else if (source.slice(Index, Index + 5) == "false") {
+ Index += 5;
+ return false;
+ } else if (source.slice(Index, Index + 4) == "null") {
+ Index += 4;
+ return null;
+ }
+ // Unrecognized token.
+ abort();
+ }
+ }
+ // Return the sentinel `$` character if the parser has reached the end
+ // of the source string.
+ return "$";
+ };
-},{"./grammar":70}],73:[function(require,module,exports){
-var grammar = require('./grammar');
+ // Internal: Parses a JSON `value` token.
+ var get = function (value) {
+ var results, hasMembers;
+ if (value == "$") {
+ // Unexpected end of input.
+ abort();
+ }
+ if (typeof value == "string") {
+ if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
+ // Remove the sentinel `@` character.
+ return value.slice(1);
+ }
+ // Parse object and array literals.
+ if (value == "[") {
+ // Parses a JSON array, returning a new JavaScript array.
+ results = [];
+ for (;; hasMembers || (hasMembers = true)) {
+ value = lex();
+ // A closing square bracket marks the end of the array literal.
+ if (value == "]") {
+ break;
+ }
+ // If the array literal contains elements, the current token
+ // should be a comma separating the previous element from the
+ // next.
+ if (hasMembers) {
+ if (value == ",") {
+ value = lex();
+ if (value == "]") {
+ // Unexpected trailing `,` in array literal.
+ abort();
+ }
+ } else {
+ // A `,` must separate each array element.
+ abort();
+ }
+ }
+ // Elisions and leading commas are not permitted.
+ if (value == ",") {
+ abort();
+ }
+ results.push(get(value));
+ }
+ return results;
+ } else if (value == "{") {
+ // Parses a JSON object, returning a new JavaScript object.
+ results = {};
+ for (;; hasMembers || (hasMembers = true)) {
+ value = lex();
+ // A closing curly brace marks the end of the object literal.
+ if (value == "}") {
+ break;
+ }
+ // If the object literal contains members, the current token
+ // should be a comma separator.
+ if (hasMembers) {
+ if (value == ",") {
+ value = lex();
+ if (value == "}") {
+ // Unexpected trailing `,` in object literal.
+ abort();
+ }
+ } else {
+ // A `,` must separate each object member.
+ abort();
+ }
+ }
+ // Leading commas are not permitted, object property names must be
+ // double-quoted strings, and a `:` must separate each property
+ // name and value.
+ if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
+ abort();
+ }
+ results[value.slice(1)] = get(lex());
+ }
+ return results;
+ }
+ // Unexpected token encountered.
+ abort();
+ }
+ return value;
+ };
-// customized util.format - discards excess arguments and can void middle ones
-var formatRegExp = /%[sdv%]/g;
-var format = function (formatStr) {
- var i = 1;
- var args = arguments;
- var len = args.length;
- return formatStr.replace(formatRegExp, function (x) {
- if (i >= len) {
- return x; // missing argument
- }
- var arg = args[i];
- i += 1;
- switch (x) {
- case '%%':
- return '%';
- case '%s':
- return String(arg);
- case '%d':
- return Number(arg);
- case '%v':
- return '';
- }
- });
- // NB: we discard excess arguments - they are typically undefined from makeLine
-};
+ // Internal: Updates a traversed object member.
+ var update = function(source, property, callback) {
+ var element = walk(source, property, callback);
+ if (element === undef) {
+ delete source[property];
+ } else {
+ source[property] = element;
+ }
+ };
-var makeLine = function (type, obj, location) {
- var str = obj.format instanceof Function ?
- (obj.format(obj.push ? location : location[obj.name])) :
- obj.format;
+ // Internal: Recursively traverses a parsed JSON object, invoking the
+ // `callback` function for each value. This is an implementation of the
+ // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
+ var walk = function (source, property, callback) {
+ var value = source[property], length;
+ if (typeof value == "object" && value) {
+ // `forEach` can't be used to traverse an array in Opera <= 8.54
+ // because its `Object#hasOwnProperty` implementation returns `false`
+ // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
+ if (getClass.call(value) == arrayClass) {
+ for (length = value.length; length--;) {
+ update(value, length, callback);
+ }
+ } else {
+ forEach(value, function (property) {
+ update(value, property, callback);
+ });
+ }
+ }
+ return callback.call(source, property, value);
+ };
- var args = [type + '=' + str];
- if (obj.names) {
- for (var i = 0; i < obj.names.length; i += 1) {
- var n = obj.names[i];
- if (obj.name) {
- args.push(location[obj.name][n]);
- }
- else { // for mLine and push attributes
- args.push(location[obj.names[i]]);
- }
+ // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
+ JSON3.parse = function (source, callback) {
+ var result, value;
+ Index = 0;
+ Source = "" + source;
+ result = get(lex());
+ // If a JSON string contains multiple tokens, it is invalid.
+ if (lex() != "$") {
+ abort();
+ }
+ // Reset the parser state.
+ Index = Source = null;
+ return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
+ };
}
}
- else {
- args.push(location[obj.name]);
- }
- return format.apply(null, args);
-};
-
-// RFC specified order
-// TODO: extend this with all the rest
-var defaultOuterOrder = [
- 'v', 'o', 's', 'i',
- 'u', 'e', 'p', 'c',
- 'b', 't', 'r', 'z', 'a'
-];
-var defaultInnerOrder = ['i', 'c', 'b', 'a'];
-
-module.exports = function (session, opts) {
- opts = opts || {};
- // ensure certain properties exist
- if (session.version == null) {
- session.version = 0; // "v=0" must be there (only defined version atm)
- }
- if (session.name == null) {
- session.name = " "; // "s= " must be there if no meaningful name set
+ // Export for asynchronous module loaders.
+ if (isLoader) {
+ define(function () {
+ return JSON3;
+ });
}
- session.media.forEach(function (mLine) {
- if (mLine.payloads == null) {
- mLine.payloads = "";
- }
- });
+}(this));
- var outerOrder = opts.outerOrder || defaultOuterOrder;
- var innerOrder = opts.innerOrder || defaultInnerOrder;
- var sdp = [];
+},{}],130:[function(require,module,exports){
+module.exports = toArray
- // loop through outerOrder for matching properties on session
- outerOrder.forEach(function (type) {
- grammar[type].forEach(function (obj) {
- if (obj.name in session && session[obj.name] != null) {
- sdp.push(makeLine(type, obj, session));
- }
- else if (obj.push in session && session[obj.push] != null) {
- session[obj.push].forEach(function (el) {
- sdp.push(makeLine(type, obj, el));
- });
- }
- });
- });
+function toArray(list, index) {
+ var array = []
- // then for each media line, follow the innerOrder
- session.media.forEach(function (mLine) {
- sdp.push(makeLine('m', grammar.m[0], mLine));
+ index = index || 0
- innerOrder.forEach(function (type) {
- grammar[type].forEach(function (obj) {
- if (obj.name in mLine && mLine[obj.name] != null) {
- sdp.push(makeLine(type, obj, mLine));
- }
- else if (obj.push in mLine && mLine[obj.push] != null) {
- mLine[obj.push].forEach(function (el) {
- sdp.push(makeLine(type, obj, el));
- });
- }
- });
- });
- });
+ for (var i = index || 0; i < list.length; i++) {
+ array[i - index] = list[i]
+ }
- return sdp.join('\r\n') + '\r\n';
-};
+ return array
+}
-},{"./grammar":70}],74:[function(require,module,exports){
+},{}],131:[function(require,module,exports){
var MediaStreamType = {
VIDEO_TYPE: "Video",
AUDIO_TYPE: "Audio"
};
module.exports = MediaStreamType;
-},{}],75:[function(require,module,exports){
+},{}],132:[function(require,module,exports){
var RTCEvents = {
RTC_READY: "rtc.ready",
DATA_CHANNEL_OPEN: "rtc.data_channel_open",
@@ -23347,7 +31326,7 @@ var RTCEvents = {
};
module.exports = RTCEvents;
-},{}],76:[function(require,module,exports){
+},{}],133:[function(require,module,exports){
var Resolutions = {
"1080": {
width: 1920,
@@ -23401,7 +31380,7 @@ var Resolutions = {
}
};
module.exports = Resolutions;
-},{}],77:[function(require,module,exports){
+},{}],134:[function(require,module,exports){
var AuthenticationEvents = {
/**
* Event callback arguments:
@@ -23415,7 +31394,7 @@ var AuthenticationEvents = {
};
module.exports = AuthenticationEvents;
-},{}],78:[function(require,module,exports){
+},{}],135:[function(require,module,exports){
var DesktopSharingEventTypes = {
/**
* An event which indicates that the jidesha extension for Firefox is
@@ -23426,7 +31405,7 @@ var DesktopSharingEventTypes = {
module.exports = DesktopSharingEventTypes;
-},{}],79:[function(require,module,exports){
+},{}],136:[function(require,module,exports){
module.exports = {
/**
* An event carrying connection statistics.
@@ -23442,12 +31421,12 @@ module.exports = {
STOP: "statistics.stop"
};
-},{}],80:[function(require,module,exports){
+},{}],137:[function(require,module,exports){
var Constants = {
LOCAL_JID: 'local'
};
module.exports = Constants;
-},{}],81:[function(require,module,exports){
+},{}],138:[function(require,module,exports){
var XMPPEvents = {
// Designates an event indicating that the connection to the XMPP server
// failed.
@@ -23552,7 +31531,27 @@ var XMPPEvents = {
/**
* Indicates that phone number changed.
*/
- PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged"
+ PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged",
+ /**
+ * Indicates error while create offer call.
+ */
+ CREATE_OFFER_FAILED: "xmpp.create_offer_failed",
+ /**
+ * Indicates error while create answer call.
+ */
+ CREATE_ANSWER_FAILED: "xmpp.create_answer_failed",
+ /**
+ * Indicates error while set local description.
+ */
+ SET_LOCAL_DESCRIPTION_FAILED: "xmpp.set_local_description_failed",
+ /**
+ * Indicates error while set remote description.
+ */
+ SET_REMOTE_DESCRIPTION_FAILED: "xmpp.set_remote_description_failed",
+ /**
+ * Indicates error while adding ice candidate.
+ */
+ ADD_ICE_CANDIDATE_FAILED: "xmpp.add_ice_candidate_failed"
};
module.exports = XMPPEvents;
diff --git a/modules/UI/videolayout/LocalVideo.js b/modules/UI/videolayout/LocalVideo.js
index 318a82570c..05118ca328 100644
--- a/modules/UI/videolayout/LocalVideo.js
+++ b/modules/UI/videolayout/LocalVideo.js
@@ -170,7 +170,6 @@ LocalVideo.prototype.changeVideo = function (stream) {
localVideo.autoplay = true;
localVideo.volume = 0; // is it required if audio is separated ?
}
- localVideo.oncontextmenu = function () { return false; };
var localVideoContainer = document.getElementById('localVideoWrapper');
// Put the new video always in front