Jitsi Meet - Secure, Simple and Scalable Video Conferences that you use as a standalone app or embed in your web application.
TypeScript debiandeep-videojitsijitsi-meetscalable-video-conferencessfuvideovideo-communicationvideo-conferencingwebrtc
Merge branch 'master' of github.com:jitsi/jitsi-meet
hristoterezovf4acf97b00c7
diff --cc app.jsindex 5cee715dc5,845307f73a..0d51d62392--- a/app.js+++ b/app.js@@@ -21,9 -30,679 +21,662 @@@ var focusedVideoInfo = nullfunction init() {-- RTC.addStreamListener(maybeDoJoin, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);RTC.start();+ xmpp.start(UI.getCreadentials);++<<<<<<< HEAD++=======+ var configDomain = config.hosts.anonymousdomain || config.hosts.domain;++ // Force authenticated domain if room is appended with '?login=true'+ if (config.hosts.anonymousdomain &&+ window.location.search.indexOf("login=true") !== -1) {+ configDomain = config.hosts.domain;+ }++ var jid = document.getElementById('jid').value || configDomain || window.location.hostname;+ connect(jid);+ }++ function connect(jid, password) {+ connection = new Strophe.Connection(document.getElementById('boshURL').value || config.bosh || '/http-bind');++ var settings = UI.getSettings();+ var email = settings.email;+ var displayName = settings.displayName;+ if(email) {+ connection.emuc.addEmailToPresence(email);+ } else {+ connection.emuc.addUserIdToPresence(settings.uid);+ }+ if(displayName) {+ connection.emuc.addDisplayNameToPresence(displayName);+ }++ if (connection.disco) {+ // for chrome, add multistream cap+ }+ connection.jingle.pc_constraints = RTC.getPCConstraints();+ if (config.useIPv6) {+ // https://code.google.com/p/webrtc/issues/detail?id=2828+ if (!connection.jingle.pc_constraints.optional) connection.jingle.pc_constraints.optional = [];+ connection.jingle.pc_constraints.optional.push({googIPv6: true});+ }++ if(!password)+ password = document.getElementById('password').value;++ var anonymousConnectionFailed = false;+ connection.connect(jid, password, function (status, msg) {+ console.log('Strophe status changed to', Strophe.getStatusString(status));+ if (status === Strophe.Status.CONNECTED) {+ if (config.useStunTurn) {+ connection.jingle.getStunAndTurnCredentials();+ }+ document.getElementById('connect').disabled = true;++ console.info("My Jabber ID: " + connection.jid);++ if(password)+ authenticatedUser = true;+ maybeDoJoin();+ } else if (status === Strophe.Status.CONNFAIL) {+ if(msg === 'x-strophe-bad-non-anon-jid') {+ anonymousConnectionFailed = true;+ }+ } else if (status === Strophe.Status.DISCONNECTED) {+ if(anonymousConnectionFailed) {+ // prompt user for username and password+ $(document).trigger('passwordrequired.main');+ }+ } else if (status === Strophe.Status.AUTHFAIL) {+ // wrong password or username, prompt user+ $(document).trigger('passwordrequired.main');++ }+ });+ }++++ function maybeDoJoin() {+ if (connection && connection.connected && Strophe.getResourceFromJid(connection.jid) // .connected is true while connecting?+ && (RTC.localAudio || RTC.localVideo)) {+ doJoin();+ }+ }++ function doJoin() {+ if (!roomName) {+ UI.generateRoomName();+ }++ Moderator.allocateConferenceFocus(+ roomName, doJoinAfterFocus);+ }++ function doJoinAfterFocus() {++ // Close authentication dialog if opened+ if (authDialog) {+ UI.messageHandler.closeDialog();+ authDialog = null;+ }+ // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice+ if (authRetryId) {+ window.clearTimeout(authRetryId);+ authRetryId = null;+ }++ var roomjid;+ roomjid = roomName;++ if (config.useNicks) {+ var nick = window.prompt('Your nickname (optional)');+ if (nick) {+ roomjid += '/' + nick;+ } else {+ roomjid += '/' + Strophe.getNodeFromJid(connection.jid);+ }+ } else {++ var tmpJid = Strophe.getNodeFromJid(connection.jid);++ if(!authenticatedUser)+ tmpJid = tmpJid.substr(0, 8);++ roomjid += '/' + tmpJid;+ }+ connection.emuc.doJoin(roomjid);+ }++ function waitForRemoteVideo(selector, ssrc, stream, jid) {+ // XXX(gp) so, every call to this function is *always* preceded by a call+ // to the RTC.attachMediaStream() function but that call is *not* followed+ // by an update to the videoSrcToSsrc map!+ //+ // The above way of doing things results in video SRCs that don't correspond+ // to any SSRC for a short period of time (to be more precise, for as long+ // the waitForRemoteVideo takes to complete). This causes problems (see+ // bellow).+ //+ // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()+ // a second time in here and only then update the videoSrcToSsrc map? Why+ // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()+ // is called the first time? I actually do that in the lastN changed event+ // handler because the "orphan" video SRC is causing troubles there. The+ // purpose of this method would then be to fire the "videoactive.jingle".+ //+ // Food for though I guess :-)++ if (selector.removed || !selector.parent().is(":visible")) {+ console.warn("Media removed before had started", selector);+ return;+ }++ if (stream.id === 'mixedmslabel') return;++ if (selector[0].currentTime > 0) {+ var videoStream = simulcast.getReceivingVideoStream(stream);+ RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?++ // FIXME: add a class that will associate peer Jid, video.src, it's ssrc and video type+ // in order to get rid of too many maps+ if (ssrc && jid) {+ jid2Ssrc[Strophe.getResourceFromJid(jid)] = ssrc;+ } else {+ console.warn("No ssrc given for jid", jid);+ }++ $(document).trigger('videoactive.jingle', [selector]);+ } else {+ setTimeout(function () {+ waitForRemoteVideo(selector, ssrc, stream, jid);+ }, 250);+ }+ }++ $(document).bind('remotestreamadded.jingle', function (event, data, sid) {+ waitForPresence(data, sid);+ });++ function waitForPresence(data, sid) {+ var sess = connection.jingle.sessions[sid];++ var thessrc;++ // look up an associated JID for a stream id+ if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {+ // look only at a=ssrc: and _not_ at a=ssrc-group: lines++ var ssrclines+ = SDPUtil.find_lines(sess.peerconnection.remoteDescription.sdp, 'a=ssrc:');+ ssrclines = ssrclines.filter(function (line) {+ // NOTE(gp) previously we filtered on the mslabel, but that property+ // is not always present.+ // return line.indexOf('mslabel:' + data.stream.label) !== -1;++ return ((line.indexOf('msid:' + data.stream.id) !== -1));+ });+ if (ssrclines.length) {+ thessrc = ssrclines[0].substring(7).split(' ')[0];++ // We signal our streams (through Jingle to the focus) before we set+ // our presence (through which peers associate remote streams to+ // jids). So, it might arrive that a remote stream is added but+ // ssrc2jid is not yet updated and thus data.peerjid cannot be+ // successfully set. Here we wait for up to a second for the+ // presence to arrive.++ if (!ssrc2jid[thessrc]) {+ // TODO(gp) limit wait duration to 1 sec.+ setTimeout(function(d, s) {+ return function() {+ waitForPresence(d, s);+ }+ }(data, sid), 250);+ return;+ }++ // ok to overwrite the one from focus? might save work in colibri.js+ console.log('associated jid', ssrc2jid[thessrc], data.peerjid);+ if (ssrc2jid[thessrc]) {+ data.peerjid = ssrc2jid[thessrc];+ }+ }+ }++ //TODO: this code should be removed when firefox implement multistream support+ if(RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_FIREFOX)+ {+ if((notReceivedSSRCs.length == 0) ||+ !ssrc2jid[notReceivedSSRCs[notReceivedSSRCs.length - 1]])+ {+ // TODO(gp) limit wait duration to 1 sec.+ setTimeout(function(d, s) {+ return function() {+ waitForPresence(d, s);+ }+ }(data, sid), 250);+ return;+ }++ thessrc = notReceivedSSRCs.pop();+ if (ssrc2jid[thessrc]) {+ data.peerjid = ssrc2jid[thessrc];+ }+ }++ RTC.createRemoteStream(data, sid, thessrc);++ var isVideo = data.stream.getVideoTracks().length > 0;+ // an attempt to work around https://github.com/jitsi/jitmeet/issues/32+ if (isVideo &&+ data.peerjid && sess.peerjid === data.peerjid &&+ data.stream.getVideoTracks().length === 0 &&+ RTC.localVideo.getTracks().length > 0) {+ //+ window.setTimeout(function () {+ sendKeyframe(sess.peerconnection);+ }, 3000);+ }+ }++ // an attempt to work around https://github.com/jitsi/jitmeet/issues/32+ function sendKeyframe(pc) {+ console.log('sendkeyframe', pc.iceConnectionState);+ if (pc.iceConnectionState !== 'connected') return; // safe...+ pc.setRemoteDescription(+ pc.remoteDescription,+ function () {+ pc.createAnswer(+ function (modifiedAnswer) {+ pc.setLocalDescription(+ modifiedAnswer,+ function () {+ // noop+ },+ function (error) {+ console.log('triggerKeyframe setLocalDescription failed', error);+ UI.messageHandler.showError();+ }+ );+ },+ function (error) {+ console.log('triggerKeyframe createAnswer failed', error);+ UI.messageHandler.showError();+ }+ );+ },+ function (error) {+ console.log('triggerKeyframe setRemoteDescription failed', error);+ UI.messageHandler.showError();+ }+ );+ }++ // Really mute video, i.e. dont even send black frames+ function muteVideo(pc, unmute) {+ // FIXME: this probably needs another of those lovely state safeguards...+ // which checks for iceconn == connected and sigstate == stable+ pc.setRemoteDescription(pc.remoteDescription,+ function () {+ pc.createAnswer(+ function (answer) {+ var sdp = new SDP(answer.sdp);+ if (sdp.media.length > 1) {+ if (unmute)+ sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');+ else+ sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');+ sdp.raw = sdp.session + sdp.media.join('');+ answer.sdp = sdp.raw;+ }+ pc.setLocalDescription(answer,+ function () {+ console.log('mute SLD ok');+ },+ function (error) {+ console.log('mute SLD error');+ UI.messageHandler.showError('Error',+ 'Oops! Something went wrong and we failed to ' ++ 'mute! (SLD Failure)');+ }+ );+ },+ function (error) {+ console.log(error);+ UI.messageHandler.showError();+ }+ );+ },+ function (error) {+ console.log('muteVideo SRD error');+ UI.messageHandler.showError('Error',+ 'Oops! Something went wrong and we failed to stop video!' ++ '(SRD Failure)');++ }+ );+ }++ $(document).bind('setLocalDescription.jingle', function (event, sid) {+ // put our ssrcs into presence so other clients can identify our stream+ var sess = connection.jingle.sessions[sid];+ var newssrcs = [];+ var media = simulcast.parseMedia(sess.peerconnection.localDescription);+ media.forEach(function (media) {++ if(Object.keys(media.sources).length > 0) {+ // TODO(gp) maybe exclude FID streams?+ Object.keys(media.sources).forEach(function (ssrc) {+ newssrcs.push({+ 'ssrc': ssrc,+ 'type': media.type,+ 'direction': media.direction+ });+ });+ }+ else if(sess.localStreamsSSRC && sess.localStreamsSSRC[media.type])+ {+ newssrcs.push({+ 'ssrc': sess.localStreamsSSRC[media.type],+ 'type': media.type,+ 'direction': media.direction+ });+ }++ });++ console.log('new ssrcs', newssrcs);++ // Have to clear presence map to get rid of removed streams+ connection.emuc.clearPresenceMedia();++ if (newssrcs.length > 0) {+ for (var i = 1; i <= newssrcs.length; i ++) {+ // Change video type to screen+ if (newssrcs[i-1].type === 'video' && desktopsharing.isUsingScreenStream()) {+ newssrcs[i-1].type = 'screen';+ }+ connection.emuc.addMediaToPresence(i,+ newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);+ }++ connection.emuc.sendPresence();+ }+ });++ $(document).bind('iceconnectionstatechange.jingle', function (event, sid, session) {+ switch (session.peerconnection.iceConnectionState) {+ case 'checking':+ session.timeChecking = (new Date()).getTime();+ session.firstconnect = true;+ break;+ case 'completed': // on caller side+ case 'connected':+ if (session.firstconnect) {+ session.firstconnect = false;+ var metadata = {};+ metadata.setupTime = (new Date()).getTime() - session.timeChecking;+ session.peerconnection.getStats(function (res) {+ if(res && res.result) {+ res.result().forEach(function (report) {+ if (report.type == 'googCandidatePair' && report.stat('googActiveConnection') == 'true') {+ metadata.localCandidateType = report.stat('googLocalCandidateType');+ metadata.remoteCandidateType = report.stat('googRemoteCandidateType');++ // log pair as well so we can get nice pie charts+ metadata.candidatePair = report.stat('googLocalCandidateType') + ';' + report.stat('googRemoteCandidateType');++ if (report.stat('googRemoteAddress').indexOf('[') === 0) {+ metadata.ipv6 = true;+ }+ }+ });+ }+ });+ }+ break;+ }+ });++ $(document).bind('presence.muc', function (event, jid, info, pres) {++ //check if the video bridge is available+ if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {+ bridgeIsDown = true;+ UI.messageHandler.showError("Error",+ "Jitsi Videobridge is currently unavailable. Please try again later!");+ }++ if (info.isFocus)+ {+ return;+ }++ // Remove old ssrcs coming from the jid+ Object.keys(ssrc2jid).forEach(function (ssrc) {+ if (ssrc2jid[ssrc] == jid) {+ delete ssrc2jid[ssrc];+ delete ssrc2videoType[ssrc];+ }+ });++ $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {+ //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));+ var ssrcV = ssrc.getAttribute('ssrc');+ ssrc2jid[ssrcV] = jid;+ notReceivedSSRCs.push(ssrcV);++ var type = ssrc.getAttribute('type');+ ssrc2videoType[ssrcV] = type;++ // might need to update the direction if participant just went from sendrecv to recvonly+ if (type === 'video' || type === 'screen') {+ var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');+ switch (ssrc.getAttribute('direction')) {+ case 'sendrecv':+ el.show();+ break;+ case 'recvonly':+ el.hide();+ // FIXME: Check if we have to change large video+ //VideoLayout.updateLargeVideo(el);+ break;+ }+ }+ });++ var displayName = !config.displayJids+ ? info.displayName : Strophe.getResourceFromJid(jid);++ if (displayName && displayName.length > 0)+ $(document).trigger('displaynamechanged',+ [jid, displayName]);+ /*if (focus !== null && info.displayName !== null) {+ focus.setEndpointDisplayName(jid, info.displayName);+ }*/++ //check if the video bridge is available+ if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {+ bridgeIsDown = true;+ UI.messageHandler.showError("Error",+ "Jitsi Videobridge is currently unavailable. Please try again later!");+ }++ var id = $(pres).find('>userID').text();+ var email = $(pres).find('>email');+ if(email.length > 0) {+ id = email.text();+ }+ UI.setUserAvatar(jid, id);++ });++ $(document).bind('kicked.muc', function (event, jid) {+ console.info(jid + " has been kicked from MUC!");+ if (connection.emuc.myroomjid === jid) {+ sessionTerminated = true;+ disposeConference(false);+ connection.emuc.doLeave();+ UI.messageHandler.openMessageDialog("Session Terminated",+ "Ouch! You have been kicked out of the meet!");+ }+ });++ $(document).bind('passwordrequired.main', function (event) {+ console.log('password is required');++ UI.messageHandler.openTwoButtonDialog(null,+ '<h2>Password required</h2>' ++ '<input id="passwordrequired.username" type="text" placeholder="[email protected]" autofocus>' ++ '<input id="passwordrequired.password" type="password" placeholder="user password">',+ true,+ "Ok",+ function (e, v, m, f) {+ if (v) {+ var username = document.getElementById('passwordrequired.username');+ var password = document.getElementById('passwordrequired.password');++ if (username.value !== null && password.value != null) {+ connect(username.value, password.value);+ }+ }+ },+ function (event) {+ document.getElementById('passwordrequired.username').focus();+ }+ );+ });++ /**+ * Checks if video identified by given src is desktop stream.+ * @param videoSrc eg.+ * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395+ * @returns {boolean}+ */+ function isVideoSrcDesktop(jid) {+ // FIXME: fix this mapping mess...+ // figure out if large video is desktop stream or just a camera++ if(!jid)+ return false;+ var isDesktop = false;+ if (connection.emuc.myroomjid &&+ Strophe.getResourceFromJid(connection.emuc.myroomjid) === jid) {+ // local video+ isDesktop = desktopsharing.isUsingScreenStream();+ } else {+ // Do we have associations...+ var videoSsrc = jid2Ssrc[jid];+ if (videoSsrc) {+ var videoType = ssrc2videoType[videoSsrc];+ if (videoType) {+ // Finally there...+ isDesktop = videoType === 'screen';+ } else {+ console.error("No video type for ssrc: " + videoSsrc);+ }+ } else {+ console.error("No ssrc for jid: " + jid);+ }+ }+ return isDesktop;+ }++ /**+ * Mutes/unmutes the local video.+ *+ * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>+ * @param options an object which specifies optional arguments such as the+ * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which+ * specifies whether the method was initiated in response to a user command (in+ * contrast to an automatic decision taken by the application logic)+ */+ function setVideoMute(mute, options) {+ if (connection && RTC.localVideo) {+ if (activecall) {+ activecall.setVideoMute(+ mute,+ function (mute) {+ var video = $('#video');+ var communicativeClass = "icon-camera";+ var muteClass = "icon-camera icon-camera-disabled";++ if (mute) {+ video.removeClass(communicativeClass);+ video.addClass(muteClass);+ } else {+ video.removeClass(muteClass);+ video.addClass(communicativeClass);+ }+ connection.emuc.addVideoInfoToPresence(mute);+ connection.emuc.sendPresence();+ },+ options);+ }+ }+ }++ $(document).on('inlastnchanged', function (event, oldValue, newValue) {+ if (config.muteLocalVideoIfNotInLastN) {+ setVideoMute(!newValue, { 'byUser': false });+ }+ });++ /**+ * Mutes/unmutes the local video.+ */+ function toggleVideo() {+ buttonClick("#video", "icon-camera icon-camera-disabled");++ if (connection && activecall && RTC.localVideo ) {+ setVideoMute(!RTC.localVideo.isMuted());+ }+ }++ /**+ * Mutes / unmutes audio for the local participant.+ */+ function toggleAudio() {+ setAudioMuted(!RTC.localAudio.isMuted());+ }++ /**+ * Sets muted audio state for the local participant.+ */+ function setAudioMuted(mute) {+ if (!(connection && RTC.localAudio)) {+ preMuted = mute;+ // We still click the button.+ buttonClick("#mute", "icon-microphone icon-mic-disabled");+ return;+ }++ if (forceMuted && !mute) {+ console.info("Asking focus for unmute");+ connection.moderate.setMute(connection.emuc.myroomjid, mute);+ // FIXME: wait for result before resetting muted status+ forceMuted = false;+ }++ if (mute == RTC.localAudio.isMuted()) {+ // Nothing to do+ return;+ }++ // It is not clear what is the right way to handle multiple tracks.+ // So at least make sure that they are all muted or all unmuted and+ // that we send presence just once.+ RTC.localAudio.mute();+ // isMuted is the opposite of audioEnabled+ connection.emuc.addAudioInfoToPresence(mute);+ connection.emuc.sendPresence();+ UI.showLocalAudioIndicator(mute);++ buttonClick("#mute", "icon-microphone icon-mic-disabled");++>>>>>>> ed78c0053c52d49035c4d506016fc799f7ea6511}diff --cc modules/xmpp/moderator.jsindex 439d703117,be58236a0b..7803703505--- a/modules/xmpp/moderator.js+++ b/modules/xmpp/moderator.js@@@ -162,7 -162,7 +162,8 @@@ var Moderator =// Try to use focus user JID from the configModerator.setFocusUserJid(config.focusUserJid);// Send create conference IQ- var iq = Moderator.createConferenceIq();+ var iq = Moderator.createConferenceIq(roomName);++ var self = this;connection.sendIQ(iq,function (result) {@@@ -190,9 -190,17 +191,21 @@@// Not authorized to create new roomif ($(error).find('>error>not-authorized').length) {console.warn("Unauthorized to start the conference");- UI.onAuthenticationRequired(function () {- Moderator.allocateConferenceFocus(roomName, callback);- });+ var toDomain+ = Strophe.getDomainFromJid(error.getAttribute('to'));+ if (toDomain === config.hosts.anonymousdomain) {+ // we are connected with anonymous domain and+ // only non anonymous users can create rooms+ // we must authorize the user- $(document).trigger('passwordrequired.main');++++ self.xmppService.promptLogin();+ } else {+ // External authentication mode- UI.onAuthenticationRequired();++ UI.onAuthenticationRequired(function () {++ Moderator.allocateConferenceFocus(++ roomName, callback);++ });+ }return;}var waitMs = getNextErrorTimeout();diff --cc modules/xmpp/strophe.emuc.jsindex 63bf14713e,0000000000..e2ada347f2mode 100644,000000..100644--- a/modules/xmpp/strophe.emuc.js+++ b/modules/xmpp/strophe.emuc.js@@@ -1,607 -1,0 +1,614 @@@+/* jshint -W117 */+/* a simple MUC connection plugin+ * can only handle a single MUC room+ */++var bridgeIsDown = false;++var Moderator = require("./moderator");++module.exports = function(XMPP, eventEmitter) {+ Strophe.addConnectionPlugin('emuc', {+ connection: null,+ roomjid: null,+ myroomjid: null,+ members: {},+ list_members: [], // so we can elect a new focus+ presMap: {},+ preziMap: {},+ joined: false,+ isOwner: false,+ role: null,+ init: function (conn) {+ this.connection = conn;+ },+ initPresenceMap: function (myroomjid) {+ this.presMap['to'] = myroomjid;+ this.presMap['xns'] = 'http://jabber.org/protocol/muc';+ },+ doJoin: function (jid, password) {+ this.myroomjid = jid;++ console.info("Joined MUC as " + this.myroomjid);++ this.initPresenceMap(this.myroomjid);++ if (!this.roomjid) {+ this.roomjid = Strophe.getBareJidFromJid(jid);+ // add handlers (just once)+ this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});+ this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});+ this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});+ this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});+ }+ if (password !== undefined) {+ this.presMap['password'] = password;+ }+ this.sendPresence();+ },+ doLeave: function () {+ console.log("do leave", this.myroomjid);+ var pres = $pres({to: this.myroomjid, type: 'unavailable' });+ this.presMap.length = 0;+ this.connection.send(pres);+ },+ createNonAnonymousRoom: function () {+ // http://xmpp.org/extensions/xep-0045.html#createroom-reserved++ var getForm = $iq({type: 'get', to: this.roomjid})+ .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})+ .c('x', {xmlns: 'jabber:x:data', type: 'submit'});++ this.connection.sendIQ(getForm, function (form) {++ if (!$(form).find(+ '>query>x[xmlns="jabber:x:data"]' ++ '>field[var="muc#roomconfig_whois"]').length) {++ console.error('non-anonymous rooms not supported');+ return;+ }++ var formSubmit = $iq({to: this.roomjid, type: 'set'})+ .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});++ formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});++ formSubmit.c('field', {'var': 'FORM_TYPE'})+ .c('value')+ .t('http://jabber.org/protocol/muc#roomconfig').up().up();++ formSubmit.c('field', {'var': 'muc#roomconfig_whois'})+ .c('value').t('anyone').up().up();++ this.connection.sendIQ(formSubmit);++ }, function (error) {+ console.error("Error getting room configuration form");+ });+ },+ onPresence: function (pres) {+ var from = pres.getAttribute('from');++ // What is this for? A workaround for something?+ if (pres.getAttribute('type')) {+ return true;+ }++ // Parse etherpad tag.+ var etherpad = $(pres).find('>etherpad');+ if (etherpad.length) {+ if (config.etherpad_base && !Moderator.isModerator()) {+ UI.initEtherpad(etherpad.text());+ }+ }++ // Parse prezi tag.+ var presentation = $(pres).find('>prezi');+ if (presentation.length) {+ var url = presentation.attr('url');+ var current = presentation.find('>current').text();++ console.log('presentation info received from', from, url);++ if (this.preziMap[from] == null) {+ this.preziMap[from] = url;++ $(document).trigger('presentationadded.muc', [from, url, current]);+ }+ else {+ $(document).trigger('gotoslide.muc', [from, url, current]);+ }+ }+ else if (this.preziMap[from] != null) {+ var url = this.preziMap[from];+ delete this.preziMap[from];+ $(document).trigger('presentationremoved.muc', [from, url]);+ }++ // Parse audio info tag.+ var audioMuted = $(pres).find('>audiomuted');+ if (audioMuted.length) {+ $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);+ }++ // Parse video info tag.+ var videoMuted = $(pres).find('>videomuted');+ if (videoMuted.length) {+ $(document).trigger('videomuted.muc', [from, videoMuted.text()]);+ }++ var stats = $(pres).find('>stats');+ if (stats.length) {+ var statsObj = {};+ Strophe.forEachChild(stats[0], "stat", function (el) {+ statsObj[el.getAttribute("name")] = el.getAttribute("value");+ });+ connectionquality.updateRemoteStats(from, statsObj);+ }++ // Parse status.+ if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {+ this.isOwner = true;+ this.createNonAnonymousRoom();+ }++ // Parse roles.+ var member = {};+ member.show = $(pres).find('>show').text();+ member.status = $(pres).find('>status').text();+ var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');+ member.affiliation = tmp.attr('affiliation');+ member.role = tmp.attr('role');++ // Focus recognition+ member.jid = tmp.attr('jid');+ member.isFocus = false;+ if (member.jid+ && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {+ member.isFocus = true;+ }++ var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');+ member.displayName = (nicktag.length > 0 ? nicktag.html() : null);++ if (from == this.myroomjid) {+ if (member.affiliation == 'owner') this.isOwner = true;+ if (this.role !== member.role) {+ this.role = member.role;+ if (Moderator.onLocalRoleChange)+ Moderator.onLocalRoleChange(from, member, pres);+ UI.onLocalRoleChange(from, member, pres);+ }+ if (!this.joined) {+ this.joined = true;+ eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);+ this.list_members.push(from);+ }+ } else if (this.members[from] === undefined) {+ // new participant+ this.members[from] = member;+ this.list_members.push(from);+ console.log('entered', from, member);+ if (member.isFocus) {+ focusMucJid = from;+ console.info("Ignore focus: " + from + ", real JID: " + member.jid);+ }+ else {+ var id = $(pres).find('>userID').text();+ var email = $(pres).find('>email');+ if (email.length > 0) {+ id = email.text();+ }+ UI.onMucEntered(from, id, member.displayName);+ API.triggerEvent("participantJoined", {jid: from});+ }+ } else {+ // Presence update for existing participant+ // Watch role change:+ if (this.members[from].role != member.role) {+ this.members[from].role = member.role;+ UI.onMucRoleChanged(member.role, member.displayName);+ }+ }++ // Always trigger presence to update bindings+ $(document).trigger('presence.muc', [from, member, pres]);+ this.parsePresence(from, member, pres);++ // Trigger status message update+ if (member.status) {+ UI.onMucPresenceStatus(from, member);+ }++ return true;+ },+ onPresenceUnavailable: function (pres) {+ var from = pres.getAttribute('from');+ // Status code 110 indicates that this notification is "self-presence".+ if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {+ delete this.members[from];+ this.list_members.splice(this.list_members.indexOf(from), 1);+ this.onParticipantLeft(from);+ }+ // If the status code is 110 this means we're leaving and we would like+ // to remove everyone else from our view, so we trigger the event.+ else if (this.list_members.length > 1) {+ for (var i = 0; i < this.list_members.length; i++) {+ var member = this.list_members[i];+ delete this.members[i];+ this.list_members.splice(i, 1);+ this.onParticipantLeft(member);+ }+ }+ if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {+ $(document).trigger('kicked.muc', [from]);+ if (this.myroomjid === from) {+ XMPP.disposeConference(false);+ eventEmitter.emit(XMPPEvents.KICKED);+ }+ }+ return true;+ },+ onPresenceError: function (pres) {+ var from = pres.getAttribute('from');+ if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {+ console.log('on password required', from);+ var self = this;+ UI.onPasswordReqiured(function (value) {+ self.doJoin(from, value);+ });+ } else if ($(pres).find(+ '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {+ var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));+ if (toDomain === config.hosts.anonymousdomain) {- // we are connected with anonymous domain and only non anonymous users can create rooms- // we must authorize the user- XMPP.promptLogin();++ // enter the room by replying with 'not-authorized'. This would++ // result in reconnection from authorized domain.++ // We're either missing Jicofo/Prosody config for anonymous++ // domains or something is wrong.++// XMPP.promptLogin();++ UI.messageHandler.openReportDialog(null,++ 'Oops ! We couldn`t join the conference.' +++ ' There might be some problem with security' +++ ' configuration. Please contact service' +++ ' administrator.', pres);+ } else {+ console.warn('onPresError ', pres);+ UI.messageHandler.openReportDialog(null,+ 'Oops! Something went wrong and we couldn`t connect to the conference.',+ pres);+ }+ } else {+ console.warn('onPresError ', pres);+ UI.messageHandler.openReportDialog(null,+ 'Oops! Something went wrong and we couldn`t connect to the conference.',+ pres);+ }+ return true;+ },+ sendMessage: function (body, nickname) {+ var msg = $msg({to: this.roomjid, type: 'groupchat'});+ msg.c('body', body).up();+ if (nickname) {+ msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();+ }+ this.connection.send(msg);+ API.triggerEvent("outgoingMessage", {"message": body});+ },+ setSubject: function (subject) {+ var msg = $msg({to: this.roomjid, type: 'groupchat'});+ msg.c('subject', subject);+ this.connection.send(msg);+ console.log("topic changed to " + subject);+ },+ onMessage: function (msg) {+ // FIXME: this is a hack. but jingle on muc makes nickchanges hard+ var from = msg.getAttribute('from');+ var nick = $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]').text() || Strophe.getResourceFromJid(from);++ var txt = $(msg).find('>body').text();+ var type = msg.getAttribute("type");+ if (type == "error") {+ UI.chatAddError($(msg).find('>text').text(), txt);+ return true;+ }++ var subject = $(msg).find('>subject');+ if (subject.length) {+ var subjectText = subject.text();+ if (subjectText || subjectText == "") {+ UI.chatSetSubject(subjectText);+ console.log("Subject is changed to " + subjectText);+ }+ }+++ if (txt) {+ console.log('chat', nick, txt);+ UI.updateChatConversation(from, nick, txt);+ if (from != this.myroomjid)+ API.triggerEvent("incomingMessage",+ {"from": from, "nick": nick, "message": txt});+ }+ return true;+ },+ lockRoom: function (key, onSuccess, onError, onNotSupported) {+ //http://xmpp.org/extensions/xep-0045.html#roomconfig+ var ob = this;+ this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),+ function (res) {+ if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {+ var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});+ formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});+ formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();+ formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();+ // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373+ formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();+ // FIXME: is muc#roomconfig_passwordprotectedroom required?+ this.connection.sendIQ(formsubmit,+ onSuccess,+ onError);+ } else {+ onNotSupported();+ }+ }, onError);+ },+ kick: function (jid) {+ var kickIQ = $iq({to: this.roomjid, type: 'set'})+ .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})+ .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})+ .c('reason').t('You have been kicked.').up().up().up();++ this.connection.sendIQ(+ kickIQ,+ function (result) {+ console.log('Kick participant with jid: ', jid, result);+ },+ function (error) {+ console.log('Kick participant error: ', error);+ });+ },+ sendPresence: function () {+ var pres = $pres({to: this.presMap['to'] });+ pres.c('x', {xmlns: this.presMap['xns']});++ if (this.presMap['password']) {+ pres.c('password').t(this.presMap['password']).up();+ }++ pres.up();++ // Send XEP-0115 'c' stanza that contains our capabilities info+ if (this.connection.caps) {+ this.connection.caps.node = config.clientNode;+ pres.c('c', this.connection.caps.generateCapsAttrs()).up();+ }++ pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})+ .t(navigator.userAgent).up();++ if (this.presMap['bridgeIsDown']) {+ pres.c('bridgeIsDown').up();+ }++ if (this.presMap['email']) {+ pres.c('email').t(this.presMap['email']).up();+ }++ if (this.presMap['userId']) {+ pres.c('userId').t(this.presMap['userId']).up();+ }++ if (this.presMap['displayName']) {+ // XEP-0172+ pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})+ .t(this.presMap['displayName']).up();+ }++ if (this.presMap['audions']) {+ pres.c('audiomuted', {xmlns: this.presMap['audions']})+ .t(this.presMap['audiomuted']).up();+ }++ if (this.presMap['videons']) {+ pres.c('videomuted', {xmlns: this.presMap['videons']})+ .t(this.presMap['videomuted']).up();+ }++ if (this.presMap['statsns']) {+ var stats = pres.c('stats', {xmlns: this.presMap['statsns']});+ for (var stat in this.presMap["stats"])+ if (this.presMap["stats"][stat] != null)+ stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();+ pres.up();+ }++ if (this.presMap['prezins']) {+ pres.c('prezi',+ {xmlns: this.presMap['prezins'],+ 'url': this.presMap['preziurl']})+ .c('current').t(this.presMap['prezicurrent']).up().up();+ }++ if (this.presMap['etherpadns']) {+ pres.c('etherpad', {xmlns: this.presMap['etherpadns']})+ .t(this.presMap['etherpadname']).up();+ }++ if (this.presMap['medians']) {+ pres.c('media', {xmlns: this.presMap['medians']});+ var sourceNumber = 0;+ Object.keys(this.presMap).forEach(function (key) {+ if (key.indexOf('source') >= 0) {+ sourceNumber++;+ }+ });+ if (sourceNumber > 0)+ for (var i = 1; i <= sourceNumber / 3; i++) {+ pres.c('source',+ {type: this.presMap['source' + i + '_type'],+ ssrc: this.presMap['source' + i + '_ssrc'],+ direction: this.presMap['source' + i + '_direction']+ || 'sendrecv' }+ ).up();+ }+ }++ pres.up();+// console.debug(pres.toString());+ this.connection.send(pres);+ },+ addDisplayNameToPresence: function (displayName) {+ this.presMap['displayName'] = displayName;+ },+ addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {+ if (!this.presMap['medians'])+ this.presMap['medians'] = 'http://estos.de/ns/mjs';++ this.presMap['source' + sourceNumber + '_type'] = mtype;+ this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;+ this.presMap['source' + sourceNumber + '_direction'] = direction;+ },+ clearPresenceMedia: function () {+ var self = this;+ Object.keys(this.presMap).forEach(function (key) {+ if (key.indexOf('source') != -1) {+ delete self.presMap[key];+ }+ });+ },+ addPreziToPresence: function (url, currentSlide) {+ this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';+ this.presMap['preziurl'] = url;+ this.presMap['prezicurrent'] = currentSlide;+ },+ removePreziFromPresence: function () {+ delete this.presMap['prezins'];+ delete this.presMap['preziurl'];+ delete this.presMap['prezicurrent'];+ },+ addCurrentSlideToPresence: function (currentSlide) {+ this.presMap['prezicurrent'] = currentSlide;+ },+ getPrezi: function (roomjid) {+ return this.preziMap[roomjid];+ },+ addEtherpadToPresence: function (etherpadName) {+ this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';+ this.presMap['etherpadname'] = etherpadName;+ },+ addAudioInfoToPresence: function (isMuted) {+ this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';+ this.presMap['audiomuted'] = isMuted.toString();+ },+ addVideoInfoToPresence: function (isMuted) {+ this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';+ this.presMap['videomuted'] = isMuted.toString();+ },+ addConnectionInfoToPresence: function (stats) {+ this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';+ this.presMap['stats'] = stats;+ },+ findJidFromResource: function (resourceJid) {+ if (resourceJid &&+ resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {+ return this.myroomjid;+ }+ var peerJid = null;+ Object.keys(this.members).some(function (jid) {+ peerJid = jid;+ return Strophe.getResourceFromJid(jid) === resourceJid;+ });+ return peerJid;+ },+ addBridgeIsDownToPresence: function () {+ this.presMap['bridgeIsDown'] = true;+ },+ addEmailToPresence: function (email) {+ this.presMap['email'] = email;+ },+ addUserIdToPresence: function (userId) {+ this.presMap['userId'] = userId;+ },+ isModerator: function () {+ return this.role === 'moderator';+ },+ getMemberRole: function (peerJid) {+ if (this.members[peerJid]) {+ return this.members[peerJid].role;+ }+ return null;+ },+ onParticipantLeft: function (jid) {+ UI.onMucLeft(jid);++ API.triggerEvent("participantLeft", {jid: jid});++ delete jid2Ssrc[jid];++ this.connection.jingle.terminateByJid(jid);++ if (this.getPrezi(jid)) {+ $(document).trigger('presentationremoved.muc',+ [jid, this.getPrezi(jid)]);+ }++ Moderator.onMucLeft(jid);+ },+ parsePresence: function (from, memeber, pres) {+ if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {+ bridgeIsDown = true;+ eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);+ }++ if(memeber.isFocus)+ return;++ // Remove old ssrcs coming from the jid+ Object.keys(ssrc2jid).forEach(function (ssrc) {+ if (ssrc2jid[ssrc] == jid) {+ delete ssrc2jid[ssrc];+ delete ssrc2videoType[ssrc];+ }+ });++ var changedStreams = [];+ $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {+ //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));+ var ssrcV = ssrc.getAttribute('ssrc');+ ssrc2jid[ssrcV] = from;+ notReceivedSSRCs.push(ssrcV);++ var type = ssrc.getAttribute('type');+ ssrc2videoType[ssrcV] = type;++ var direction = ssrc.getAttribute('direction');++ changedStreams.push({type: type, direction: direction});++ });++ eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);++ var displayName = !config.displayJids+ ? memeber.displayName : Strophe.getResourceFromJid(from);++ if (displayName && displayName.length > 0)+ {+// $(document).trigger('displaynamechanged',+// [jid, displayName]);+ eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);+ }+++ var id = $(pres).find('>userID').text();+ var email = $(pres).find('>email');+ if(email.length > 0) {+ id = email.text();+ }++ eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);+ }+ });+};+diff --cc modules/xmpp/strophe.jingle.jsindex 4878d587c2,0000000000..1f9534a026mode 100644,000000..100644--- a/modules/xmpp/strophe.jingle.js+++ b/modules/xmpp/strophe.jingle.js@@@ -1,334 -1,0 +1,335 @@@+/* jshint -W117 */++var JingleSession = require("./JingleSession");++function CallIncomingJingle(sid, connection) {+ var sess = connection.jingle.sessions[sid];++ // TODO: do we check activecall == null?+ activecall = sess;++ statistics.onConferenceCreated(sess);+ RTC.onConferenceCreated(sess);++ // TODO: check affiliation and/or role+ console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);+ sess.usedrip = true; // not-so-naive trickle ice+ sess.sendAnswer();+ sess.accept();++};++module.exports = function(XMPP)+{+ Strophe.addConnectionPlugin('jingle', {+ connection: null,+ sessions: {},+ jid2session: {},+ ice_config: {iceServers: []},+ pc_constraints: {},+ media_constraints: {+ mandatory: {+ 'OfferToReceiveAudio': true,+ 'OfferToReceiveVideo': true+ }+ // MozDontOfferDataChannel: true when this is firefox+ },+ init: function (conn) {+ this.connection = conn;+ if (this.connection.disco) {+ // http://xmpp.org/extensions/xep-0167.html#support+ // http://xmpp.org/extensions/xep-0176.html#support+ this.connection.disco.addFeature('urn:xmpp:jingle:1');+ this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');+ this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');++ this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');+ this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');+ this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');+++ // this is dealt with by SDP O/A so we don't need to annouce this+ //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293+ //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294+ if (config.useRtcpMux) {+ this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux+ }+ if (config.useBundle) {+ this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle+ }+ //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc+ }+ this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);+ },+ onJingle: function (iq) {+ var sid = $(iq).find('jingle').attr('sid');+ var action = $(iq).find('jingle').attr('action');+ var fromJid = iq.getAttribute('from');+ // send ack first+ var ack = $iq({type: 'result',+ to: fromJid,+ id: iq.getAttribute('id')+ });+ console.log('on jingle ' + action + ' from ' + fromJid, iq);+ var sess = this.sessions[sid];+ if ('session-initiate' != action) {+ if (sess === null) {+ ack.type = 'error';+ ack.c('error', {type: 'cancel'})+ .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()+ .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});+ this.connection.send(ack);+ return true;+ }+ // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)+ // local jid is not checked+ if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {+ console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);+ ack.type = 'error';+ ack.c('error', {type: 'cancel'})+ .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()+ .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});+ this.connection.send(ack);+ return true;+ }+ } else if (sess !== undefined) {+ // existing session with same session id+ // this might be out-of-order if the sess.peerjid is the same as from+ ack.type = 'error';+ ack.c('error', {type: 'cancel'})+ .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();+ console.warn('duplicate session id', sid);+ this.connection.send(ack);+ return true;+ }+ // FIXME: check for a defined action+ this.connection.send(ack);+ // see http://xmpp.org/extensions/xep-0166.html#concepts-session+ switch (action) {+ case 'session-initiate':+ sess = new JingleSession(+ $(iq).attr('to'), $(iq).find('jingle').attr('sid'),+ this.connection, XMPP);+ // configure session++ sess.media_constraints = this.media_constraints;+ sess.pc_constraints = this.pc_constraints;+ sess.ice_config = this.ice_config;++ sess.initiate(fromJid, false);+ // FIXME: setRemoteDescription should only be done when this call is to be accepted+ sess.setRemoteDescription($(iq).find('>jingle'), 'offer');++ this.sessions[sess.sid] = sess;+ this.jid2session[sess.peerjid] = sess;++ // the callback should either+ // .sendAnswer and .accept+ // or .sendTerminate -- not necessarily synchronus+ CallIncomingJingle(sess.sid, this.connection);+ break;+ case 'session-accept':+ sess.setRemoteDescription($(iq).find('>jingle'), 'answer');+ sess.accept();+ $(document).trigger('callaccepted.jingle', [sess.sid]);+ break;+ case 'session-terminate':+ // If this is not the focus sending the terminate, we have+ // nothing more to do here.+ if (Object.keys(this.sessions).length < 1+ || !(this.sessions[Object.keys(this.sessions)[0]]+ instanceof JingleSession))+ {+ break;+ }+ console.log('terminating...', sess.sid);+ sess.terminate();+ this.terminate(sess.sid);+ if ($(iq).find('>jingle>reason').length) {+ $(document).trigger('callterminated.jingle', [+ sess.sid,+ sess.peerjid,+ $(iq).find('>jingle>reason>:first')[0].tagName,+ $(iq).find('>jingle>reason>text').text()+ ]);+ } else {+ $(document).trigger('callterminated.jingle',+ [sess.sid, sess.peerjid]);+ }+ break;+ case 'transport-info':+ sess.addIceCandidate($(iq).find('>jingle>content'));+ break;+ case 'session-info':+ var affected;+ if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {+ $(document).trigger('ringing.jingle', [sess.sid]);+ } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {+ affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');+ $(document).trigger('mute.jingle', [sess.sid, affected]);+ } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {+ affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');+ $(document).trigger('unmute.jingle', [sess.sid, affected]);+ }+ break;+ case 'addsource': // FIXME: proprietary, un-jingleish+ case 'source-add': // FIXME: proprietary+ sess.addSource($(iq).find('>jingle>content'), fromJid);+ break;+ case 'removesource': // FIXME: proprietary, un-jingleish+ case 'source-remove': // FIXME: proprietary+ sess.removeSource($(iq).find('>jingle>content'), fromJid);+ break;+ default:+ console.warn('jingle action not implemented', action);+ break;+ }+ return true;+ },+ initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid+ var sess = new JingleSession(myjid || this.connection.jid,+ Math.random().toString(36).substr(2, 12), // random string+ this.connection, XMPP);+ // configure session++ sess.media_constraints = this.media_constraints;+ sess.pc_constraints = this.pc_constraints;+ sess.ice_config = this.ice_config;++ sess.initiate(peerjid, true);+ this.sessions[sess.sid] = sess;+ this.jid2session[sess.peerjid] = sess;+ sess.sendOffer();+ return sess;+ },+ terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)+ if (sid === null || sid === undefined) {+ for (sid in this.sessions) {+ if (this.sessions[sid].state != 'ended') {+ this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);+ this.sessions[sid].terminate();+ }+ delete this.jid2session[this.sessions[sid].peerjid];+ delete this.sessions[sid];+ }+ } else if (this.sessions.hasOwnProperty(sid)) {+ if (this.sessions[sid].state != 'ended') {+ this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);+ this.sessions[sid].terminate();+ }+ delete this.jid2session[this.sessions[sid].peerjid];+ delete this.sessions[sid];+ }+ },+ // Used to terminate a session when an unavailable presence is received.+ terminateByJid: function (jid) {+ if (this.jid2session.hasOwnProperty(jid)) {+ var sess = this.jid2session[jid];+ if (sess) {+ sess.terminate();+ console.log('peer went away silently', jid);+ delete this.sessions[sess.sid];+ delete this.jid2session[jid];+ $(document).trigger('callterminated.jingle',+ [sess.sid, jid], 'gone');+ }+ }+ },+ terminateRemoteByJid: function (jid, reason) {+ if (this.jid2session.hasOwnProperty(jid)) {+ var sess = this.jid2session[jid];+ if (sess) {+ sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);+ sess.terminate();+ console.log('terminate peer with jid', sess.sid, jid);+ delete this.sessions[sess.sid];+ delete this.jid2session[jid];+ $(document).trigger('callterminated.jingle',+ [sess.sid, jid, 'kicked']);+ }+ }+ },+ getStunAndTurnCredentials: function () {+ // get stun and turn configuration from server via xep-0215+ // uses time-limited credentials as described in+ // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00+ //+ // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua+ // for a prosody module which implements this+ //+ // currently, this doesn't work with updateIce and therefore credentials with a long+ // validity have to be fetched before creating the peerconnection+ // TODO: implement refresh via updateIce as described in+ // https://code.google.com/p/webrtc/issues/detail?id=1650+ var self = this;+ this.connection.sendIQ(+ $iq({type: 'get', to: this.connection.domain})+ .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),+ function (res) {+ var iceservers = [];+ $(res).find('>services>service').each(function (idx, el) {+ el = $(el);+ var dict = {};+ var type = el.attr('type');+ switch (type) {+ case 'stun':+ dict.url = 'stun:' + el.attr('host');+ if (el.attr('port')) {+ dict.url += ':' + el.attr('port');+ }+ iceservers.push(dict);+ break;+ case 'turn':+ case 'turns':+ dict.url = type + ':';+ if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508+ if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {+ dict.url += el.attr('username') + '@';+ } else {+ dict.username = el.attr('username'); // only works in M28+ }+ }+ dict.url += el.attr('host');+ if (el.attr('port') && el.attr('port') != '3478') {+ dict.url += ':' + el.attr('port');+ }+ if (el.attr('transport') && el.attr('transport') != 'udp') {+ dict.url += '?transport=' + el.attr('transport');+ }+ if (el.attr('password')) {+ dict.credential = el.attr('password');+ }+ iceservers.push(dict);+ break;+ }+ });+ self.ice_config.iceServers = iceservers;+ },+ function (err) {+ console.warn('getting turn credentials failed', err);+ console.warn('is mod_turncredentials or similar installed?');+ }+ );+ // implement push?+ },++ /**+ * Populates the log data+ */+ populateData: function () {+ var data = {};+ Object.keys(this.sessions).forEach(function (sid) {+ var session = this.sessions[sid];+ if (session.peerconnection && session.peerconnection.updateLog) {+ // FIXME: should probably be a .dump call+ data["jingle_" + session.sid] = {+ updateLog: session.peerconnection.updateLog,+ stats: session.peerconnection.stats,+ url: window.location.href+ };+ }+ });+ return data;+ }+ });+};+diff --cc modules/xmpp/xmpp.jsindex d7ad4d2dcf,0000000000..fed7cddae7mode 100644,000000..100644--- a/modules/xmpp/xmpp.js+++ b/modules/xmpp/xmpp.js@@@ -1,422 -1,0 +1,425 @@@+var Moderator = require("./moderator");+var EventEmitter = require("events");+var Recording = require("./recording");+var SDP = require("./SDP");++var eventEmitter = new EventEmitter();+var connection = null;+var authenticatedUser = false;+var activecall = null;++function connect(jid, password, uiCredentials) {+ var bosh+ = uiCredentials.bosh || config.bosh || '/http-bind';+ connection = new Strophe.Connection(bosh);+ Moderator.setConnection(connection);++ var settings = UI.getSettings();+ var email = settings.email;+ var displayName = settings.displayName;+ if(email) {+ connection.emuc.addEmailToPresence(email);+ } else {+ connection.emuc.addUserIdToPresence(settings.uid);+ }+ if(displayName) {+ connection.emuc.addDisplayNameToPresence(displayName);+ }++ if (connection.disco) {+ // for chrome, add multistream cap+ }+ connection.jingle.pc_constraints = RTC.getPCConstraints();+ if (config.useIPv6) {+ // https://code.google.com/p/webrtc/issues/detail?id=2828+ if (!connection.jingle.pc_constraints.optional)+ connection.jingle.pc_constraints.optional = [];+ connection.jingle.pc_constraints.optional.push({googIPv6: true});+ }++ if(!password)+ password = uiCredentials.password;++ var anonymousConnectionFailed = false;+ connection.connect(jid, password, function (status, msg) {+ console.log('Strophe status changed to',+ Strophe.getStatusString(status));+ if (status === Strophe.Status.CONNECTED) {+ if (config.useStunTurn) {+ connection.jingle.getStunAndTurnCredentials();+ }+ UI.disableConnect();++ console.info("My Jabber ID: " + connection.jid);++ if(password)+ authenticatedUser = true;+ maybeDoJoin();+ } else if (status === Strophe.Status.CONNFAIL) {+ if(msg === 'x-strophe-bad-non-anon-jid') {+ anonymousConnectionFailed = true;+ }+ } else if (status === Strophe.Status.DISCONNECTED) {+ if(anonymousConnectionFailed) {+ // prompt user for username and password+ XMPP.promptLogin();+ }+ } else if (status === Strophe.Status.AUTHFAIL) {+ // wrong password or username, prompt user+ XMPP.promptLogin();++ }+ });+}++++function maybeDoJoin() {+ if (connection && connection.connected &&+ Strophe.getResourceFromJid(connection.jid)+ && (RTC.localAudio || RTC.localVideo)) {+ // .connected is true while connecting?+ doJoin();+ }+}++function doJoin() {+ var roomName = UI.generateRoomName();++ Moderator.allocateConferenceFocus(+ roomName, UI.checkForNicknameAndJoin);+}++function initStrophePlugins()+{+ require("./strophe.emuc")(XMPP, eventEmitter);+ require("./strophe.jingle")();+ require("./strophe.moderate")(XMPP);+ require("./strophe.util")();+ require("./strophe.rayo")();+ require("./strophe.logger")();+}++function registerListeners() {+ RTC.addStreamListener(maybeDoJoin,+ StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);+}++function setupEvents() {+ $(window).bind('beforeunload', function () {+ if (connection && connection.connected) {+ // ensure signout+ $.ajax({+ type: 'POST',+ url: config.bosh,+ async: false,+ cache: false,+ contentType: 'application/xml',+ data: "<body rid='" + (connection.rid || connection._proto.rid)+ + "' xmlns='http://jabber.org/protocol/httpbind' sid='"+ + (connection.sid || connection._proto.sid)+ + "' type='terminate'>" ++ "<presence xmlns='jabber:client' type='unavailable'/>" ++ "</body>",+ success: function (data) {+ console.log('signed out');+ console.log(data);+ },+ error: function (XMLHttpRequest, textStatus, errorThrown) {+ console.log('signout error',+ textStatus + ' (' + errorThrown + ')');+ }+ });+ }+ XMPP.disposeConference(true);+ });+}++var XMPP = {+ sessionTerminated: false,+ /**+ * Remembers if we were muted by the focus.+ * @type {boolean}+ */+ forceMuted: false,+ start: function (uiCredentials) {+ setupEvents();+ initStrophePlugins();+ registerListeners();+ Moderator.init();- var jid = uiCredentials.jid ||- config.hosts.anonymousdomain ||- config.hosts.domain ||- window.location.hostname;++ var configDomain = config.hosts.anonymousdomain || config.hosts.domain;++ // Force authenticated domain if room is appended with '?login=true'++ if (config.hosts.anonymousdomain &&++ window.location.search.indexOf("login=true") !== -1) {++ configDomain = config.hosts.domain;++ }++ var jid = uiCredentials.jid || configDomain || window.location.hostname;+ connect(jid, null, uiCredentials);+ },+ promptLogin: function () {+ UI.showLoginPopup(connect);+ },+ joinRooom: function(roomName, useNicks, nick)+ {+ var roomjid;+ roomjid = roomName;++ if (useNicks) {+ if (nick) {+ roomjid += '/' + nick;+ } else {+ roomjid += '/' + Strophe.getNodeFromJid(connection.jid);+ }+ } else {++ var tmpJid = Strophe.getNodeFromJid(connection.jid);++ if(!authenticatedUser)+ tmpJid = tmpJid.substr(0, 8);++ roomjid += '/' + tmpJid;+ }+ connection.emuc.doJoin(roomjid);+ },+ myJid: function () {+ if(!connection)+ return null;+ return connection.emuc.myroomjid;+ },+ myResource: function () {+ if(!connection || ! connection.emuc.myroomjid)+ return null;+ return Strophe.getResourceFromJid(connection.emuc.myroomjid);+ },+ disposeConference: function (onUnload) {+ eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);+ var handler = activecall;+ if (handler && handler.peerconnection) {+ // FIXME: probably removing streams is not required and close() should+ // be enough+ if (RTC.localAudio) {+ handler.peerconnection.removeStream(RTC.localAudio.getOriginalStream(), onUnload);+ }+ if (RTC.localVideo) {+ handler.peerconnection.removeStream(RTC.localVideo.getOriginalStream(), onUnload);+ }+ handler.peerconnection.close();+ }+ activecall = null;+ if(!onUnload)+ {+ this.sessionTerminated = true;+ connection.emuc.doLeave();+ }+ },+ addListener: function(type, listener)+ {+ eventEmitter.on(type, listener);+ },+ removeListener: function (type, listener) {+ eventEmitter.removeListener(type, listener);+ },+ allocateConferenceFocus: function(roomName, callback) {+ Moderator.allocateConferenceFocus(roomName, callback);+ },+ isModerator: function () {+ return Moderator.isModerator();+ },+ isSipGatewayEnabled: function () {+ return Moderator.isSipGatewayEnabled();+ },+ isExternalAuthEnabled: function () {+ return Moderator.isExternalAuthEnabled();+ },+ switchStreams: function (stream, oldStream, callback) {+ if (activecall) {+ // FIXME: will block switchInProgress on true value in case of exception+ activecall.switchStreams(stream, oldStream, callback);+ } else {+ // We are done immediately+ console.error("No conference handler");+ UI.messageHandler.showError('Error',+ 'Unable to switch video stream.');+ callback();+ }+ },+ setVideoMute: function (mute, callback, options) {+ if(activecall && connection && RTC.localVideo)+ {+ activecall.setVideoMute(mute, callback, options);+ }+ },+ setAudioMute: function (mute, callback) {+ if (!(connection && RTC.localAudio)) {+ return false;+ }+++ if (this.forceMuted && !mute) {+ console.info("Asking focus for unmute");+ connection.moderate.setMute(connection.emuc.myroomjid, mute);+ // FIXME: wait for result before resetting muted status+ this.forceMuted = false;+ }++ if (mute == RTC.localAudio.isMuted()) {+ // Nothing to do+ return true;+ }++ // It is not clear what is the right way to handle multiple tracks.+ // So at least make sure that they are all muted or all unmuted and+ // that we send presence just once.+ RTC.localAudio.mute();+ // isMuted is the opposite of audioEnabled+ connection.emuc.addAudioInfoToPresence(mute);+ connection.emuc.sendPresence();+ callback();+ return true;+ },+ // Really mute video, i.e. dont even send black frames+ muteVideo: function (pc, unmute) {+ // FIXME: this probably needs another of those lovely state safeguards...+ // which checks for iceconn == connected and sigstate == stable+ pc.setRemoteDescription(pc.remoteDescription,+ function () {+ pc.createAnswer(+ function (answer) {+ var sdp = new SDP(answer.sdp);+ if (sdp.media.length > 1) {+ if (unmute)+ sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');+ else+ sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');+ sdp.raw = sdp.session + sdp.media.join('');+ answer.sdp = sdp.raw;+ }+ pc.setLocalDescription(answer,+ function () {+ console.log('mute SLD ok');+ },+ function (error) {+ console.log('mute SLD error');+ UI.messageHandler.showError('Error',+ 'Oops! Something went wrong and we failed to ' ++ 'mute! (SLD Failure)');+ }+ );+ },+ function (error) {+ console.log(error);+ UI.messageHandler.showError();+ }+ );+ },+ function (error) {+ console.log('muteVideo SRD error');+ UI.messageHandler.showError('Error',+ 'Oops! Something went wrong and we failed to stop video!' ++ '(SRD Failure)');++ }+ );+ },+ toggleRecording: function (tokenEmptyCallback,+ startingCallback, startedCallback) {+ Recording.toggleRecording(tokenEmptyCallback,+ startingCallback, startedCallback);+ },+ addToPresence: function (name, value, dontSend) {+ switch (name)+ {+ case "displayName":+ connection.emuc.addDisplayNameToPresence(value);+ break;+ case "etherpad":+ connection.emuc.addEtherpadToPresence(value);+ break;+ case "prezi":+ connection.emuc.addPreziToPresence(value, 0);+ break;+ case "preziSlide":+ connection.emuc.addCurrentSlideToPresence(value);+ break;+ case "connectionQuality":+ connection.emuc.addConnectionInfoToPresence(value);+ break;+ case "email":+ connection.emuc.addEmailToPresence(value);+ default :+ console.log("Unknown tag for presence.");+ return;+ }+ if(!dontSend)+ connection.emuc.sendPresence();+ },+ sendLogs: function (data) {+ if(!focusMucJid)+ return;++ var deflate = true;+- var content = JSON.stringify(dataYes);++ var content = JSON.stringify(data);+ if (deflate) {+ content = String.fromCharCode.apply(null, Pako.deflateRaw(content));+ }+ content = Base64.encode(content);+ // XEP-0337-ish+ var message = $msg({to: focusMucJid, type: 'normal'});+ message.c('log', { xmlns: 'urn:xmpp:eventlog',+ id: 'PeerConnectionStats'});+ message.c('message').t(content).up();+ if (deflate) {+ message.c('tag', {name: "deflated", value: "true"}).up();+ }+ message.up();++ connection.send(message);+ },+ populateData: function () {+ var data = {};+ if (connection.jingle) {+ data = connection.jingle.populateData();+ }+ return data;+ },+ getLogger: function () {+ if(connection.logger)+ return connection.logger.log;+ return null;+ },+ getPrezi: function () {+ return connection.emuc.getPrezi(this.myJid());+ },+ removePreziFromPresence: function () {+ connection.emuc.removePreziFromPresence();+ connection.emuc.sendPresence();+ },+ sendChatMessage: function (message, nickname) {+ connection.emuc.sendMessage(message, nickname);+ },+ setSubject: function (topic) {+ connection.emuc.setSubject(topic);+ },+ lockRoom: function (key, onSuccess, onError, onNotSupported) {+ connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);+ },+ dial: function (to, from, roomName,roomPass) {+ connection.rayo.dial(to, from, roomName,roomPass);+ },+ setMute: function (jid, mute) {+ connection.moderate.setMute(jid, mute);+ },+ eject: function (jid) {+ connection.moderate.eject(jid);+ },+ findJidFromResource: function (resource) {+ connection.emuc.findJidFromResource(resource);+ },+ getMembers: function () {+ return connection.emuc.members;+ }++};++module.exports = XMPP;