You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

xmpp.js 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. var Moderator = require("./moderator");
  2. var EventEmitter = require("events");
  3. var Recording = require("./recording");
  4. var SDP = require("./SDP");
  5. var Pako = require("pako");
  6. var eventEmitter = new EventEmitter();
  7. var connection = null;
  8. var authenticatedUser = false;
  9. function connect(jid, password, uiCredentials) {
  10. var bosh
  11. = uiCredentials.bosh || config.bosh || '/http-bind';
  12. connection = new Strophe.Connection(bosh);
  13. Moderator.setConnection(connection);
  14. var settings = UI.getSettings();
  15. var email = settings.email;
  16. var displayName = settings.displayName;
  17. if(email) {
  18. connection.emuc.addEmailToPresence(email);
  19. } else {
  20. connection.emuc.addUserIdToPresence(settings.uid);
  21. }
  22. if(displayName) {
  23. connection.emuc.addDisplayNameToPresence(displayName);
  24. }
  25. if (connection.disco) {
  26. // for chrome, add multistream cap
  27. }
  28. connection.jingle.pc_constraints = RTC.getPCConstraints();
  29. if (config.useIPv6) {
  30. // https://code.google.com/p/webrtc/issues/detail?id=2828
  31. if (!connection.jingle.pc_constraints.optional)
  32. connection.jingle.pc_constraints.optional = [];
  33. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  34. }
  35. if(!password)
  36. password = uiCredentials.password;
  37. var anonymousConnectionFailed = false;
  38. connection.connect(jid, password, function (status, msg) {
  39. console.log('Strophe status changed to',
  40. Strophe.getStatusString(status));
  41. if (status === Strophe.Status.CONNECTED) {
  42. if (config.useStunTurn) {
  43. connection.jingle.getStunAndTurnCredentials();
  44. }
  45. UI.disableConnect();
  46. console.info("My Jabber ID: " + connection.jid);
  47. if(password)
  48. authenticatedUser = true;
  49. maybeDoJoin();
  50. } else if (status === Strophe.Status.CONNFAIL) {
  51. if(msg === 'x-strophe-bad-non-anon-jid') {
  52. anonymousConnectionFailed = true;
  53. }
  54. } else if (status === Strophe.Status.DISCONNECTED) {
  55. if(anonymousConnectionFailed) {
  56. // prompt user for username and password
  57. XMPP.promptLogin();
  58. }
  59. } else if (status === Strophe.Status.AUTHFAIL) {
  60. // wrong password or username, prompt user
  61. XMPP.promptLogin();
  62. }
  63. });
  64. }
  65. function maybeDoJoin() {
  66. if (connection && connection.connected &&
  67. Strophe.getResourceFromJid(connection.jid)
  68. && (RTC.localAudio || RTC.localVideo)) {
  69. // .connected is true while connecting?
  70. doJoin();
  71. }
  72. }
  73. function doJoin() {
  74. var roomName = UI.generateRoomName();
  75. Moderator.allocateConferenceFocus(
  76. roomName, UI.checkForNicknameAndJoin);
  77. }
  78. function initStrophePlugins()
  79. {
  80. require("./strophe.emuc")(XMPP, eventEmitter);
  81. require("./strophe.jingle")(XMPP, eventEmitter);
  82. require("./strophe.moderate")(XMPP);
  83. require("./strophe.util")();
  84. require("./strophe.rayo")();
  85. require("./strophe.logger")();
  86. }
  87. function registerListeners() {
  88. RTC.addStreamListener(maybeDoJoin,
  89. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  90. UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  91. XMPP.addToPresence("displayName", nickname);
  92. });
  93. }
  94. function setupEvents() {
  95. $(window).bind('beforeunload', function () {
  96. if (connection && connection.connected) {
  97. // ensure signout
  98. $.ajax({
  99. type: 'POST',
  100. url: config.bosh,
  101. async: false,
  102. cache: false,
  103. contentType: 'application/xml',
  104. data: "<body rid='" + (connection.rid || connection._proto.rid)
  105. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  106. + (connection.sid || connection._proto.sid)
  107. + "' type='terminate'>" +
  108. "<presence xmlns='jabber:client' type='unavailable'/>" +
  109. "</body>",
  110. success: function (data) {
  111. console.log('signed out');
  112. console.log(data);
  113. },
  114. error: function (XMLHttpRequest, textStatus, errorThrown) {
  115. console.log('signout error',
  116. textStatus + ' (' + errorThrown + ')');
  117. }
  118. });
  119. }
  120. XMPP.disposeConference(true);
  121. });
  122. }
  123. var XMPP = {
  124. sessionTerminated: false,
  125. /**
  126. * Remembers if we were muted by the focus.
  127. * @type {boolean}
  128. */
  129. forceMuted: false,
  130. start: function (uiCredentials) {
  131. setupEvents();
  132. initStrophePlugins();
  133. registerListeners();
  134. Moderator.init();
  135. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  136. // Force authenticated domain if room is appended with '?login=true'
  137. if (config.hosts.anonymousdomain &&
  138. window.location.search.indexOf("login=true") !== -1) {
  139. configDomain = config.hosts.domain;
  140. }
  141. var jid = uiCredentials.jid || configDomain || window.location.hostname;
  142. connect(jid, null, uiCredentials);
  143. },
  144. promptLogin: function () {
  145. UI.showLoginPopup(connect);
  146. },
  147. joinRoom: function(roomName, useNicks, nick)
  148. {
  149. var roomjid;
  150. roomjid = roomName;
  151. if (useNicks) {
  152. if (nick) {
  153. roomjid += '/' + nick;
  154. } else {
  155. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  156. }
  157. } else {
  158. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  159. if(!authenticatedUser)
  160. tmpJid = tmpJid.substr(0, 8);
  161. roomjid += '/' + tmpJid;
  162. }
  163. connection.emuc.doJoin(roomjid);
  164. },
  165. myJid: function () {
  166. if(!connection)
  167. return null;
  168. return connection.emuc.myroomjid;
  169. },
  170. myResource: function () {
  171. if(!connection || ! connection.emuc.myroomjid)
  172. return null;
  173. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  174. },
  175. disposeConference: function (onUnload) {
  176. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  177. var handler = connection.jingle.activecall;
  178. if (handler && handler.peerconnection) {
  179. // FIXME: probably removing streams is not required and close() should
  180. // be enough
  181. if (RTC.localAudio) {
  182. handler.peerconnection.removeStream(RTC.localAudio.getOriginalStream(), onUnload);
  183. }
  184. if (RTC.localVideo) {
  185. handler.peerconnection.removeStream(RTC.localVideo.getOriginalStream(), onUnload);
  186. }
  187. handler.peerconnection.close();
  188. }
  189. connection.jingle.activecall = null;
  190. if(!onUnload)
  191. {
  192. this.sessionTerminated = true;
  193. connection.emuc.doLeave();
  194. }
  195. },
  196. addListener: function(type, listener)
  197. {
  198. eventEmitter.on(type, listener);
  199. },
  200. removeListener: function (type, listener) {
  201. eventEmitter.removeListener(type, listener);
  202. },
  203. allocateConferenceFocus: function(roomName, callback) {
  204. Moderator.allocateConferenceFocus(roomName, callback);
  205. },
  206. isModerator: function () {
  207. return Moderator.isModerator();
  208. },
  209. isSipGatewayEnabled: function () {
  210. return Moderator.isSipGatewayEnabled();
  211. },
  212. isExternalAuthEnabled: function () {
  213. return Moderator.isExternalAuthEnabled();
  214. },
  215. switchStreams: function (stream, oldStream, callback) {
  216. if (connection && connection.jingle.activecall) {
  217. // FIXME: will block switchInProgress on true value in case of exception
  218. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  219. } else {
  220. // We are done immediately
  221. console.error("No conference handler");
  222. UI.messageHandler.showError('Error',
  223. 'Unable to switch video stream.');
  224. callback();
  225. }
  226. },
  227. setVideoMute: function (mute, callback, options) {
  228. if(connection && RTC.localVideo && connection.jingle.activecall)
  229. {
  230. connection.jingle.activecall.setVideoMute(mute, callback, options);
  231. }
  232. },
  233. setAudioMute: function (mute, callback) {
  234. if (!(connection && RTC.localAudio)) {
  235. return false;
  236. }
  237. if (this.forceMuted && !mute) {
  238. console.info("Asking focus for unmute");
  239. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  240. // FIXME: wait for result before resetting muted status
  241. this.forceMuted = false;
  242. }
  243. if (mute == RTC.localAudio.isMuted()) {
  244. // Nothing to do
  245. return true;
  246. }
  247. // It is not clear what is the right way to handle multiple tracks.
  248. // So at least make sure that they are all muted or all unmuted and
  249. // that we send presence just once.
  250. RTC.localAudio.mute();
  251. // isMuted is the opposite of audioEnabled
  252. connection.emuc.addAudioInfoToPresence(mute);
  253. connection.emuc.sendPresence();
  254. callback();
  255. return true;
  256. },
  257. // Really mute video, i.e. dont even send black frames
  258. muteVideo: function (pc, unmute) {
  259. // FIXME: this probably needs another of those lovely state safeguards...
  260. // which checks for iceconn == connected and sigstate == stable
  261. pc.setRemoteDescription(pc.remoteDescription,
  262. function () {
  263. pc.createAnswer(
  264. function (answer) {
  265. var sdp = new SDP(answer.sdp);
  266. if (sdp.media.length > 1) {
  267. if (unmute)
  268. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  269. else
  270. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  271. sdp.raw = sdp.session + sdp.media.join('');
  272. answer.sdp = sdp.raw;
  273. }
  274. pc.setLocalDescription(answer,
  275. function () {
  276. console.log('mute SLD ok');
  277. },
  278. function (error) {
  279. console.log('mute SLD error');
  280. UI.messageHandler.showError('Error',
  281. 'Oops! Something went wrong and we failed to ' +
  282. 'mute! (SLD Failure)');
  283. }
  284. );
  285. },
  286. function (error) {
  287. console.log(error);
  288. UI.messageHandler.showError();
  289. }
  290. );
  291. },
  292. function (error) {
  293. console.log('muteVideo SRD error');
  294. UI.messageHandler.showError('Error',
  295. 'Oops! Something went wrong and we failed to stop video!' +
  296. '(SRD Failure)');
  297. }
  298. );
  299. },
  300. toggleRecording: function (tokenEmptyCallback,
  301. startingCallback, startedCallback) {
  302. Recording.toggleRecording(tokenEmptyCallback,
  303. startingCallback, startedCallback, connection);
  304. },
  305. addToPresence: function (name, value, dontSend) {
  306. switch (name)
  307. {
  308. case "displayName":
  309. connection.emuc.addDisplayNameToPresence(value);
  310. break;
  311. case "etherpad":
  312. connection.emuc.addEtherpadToPresence(value);
  313. break;
  314. case "prezi":
  315. connection.emuc.addPreziToPresence(value, 0);
  316. break;
  317. case "preziSlide":
  318. connection.emuc.addCurrentSlideToPresence(value);
  319. break;
  320. case "connectionQuality":
  321. connection.emuc.addConnectionInfoToPresence(value);
  322. break;
  323. case "email":
  324. connection.emuc.addEmailToPresence(value);
  325. default :
  326. console.log("Unknown tag for presence.");
  327. return;
  328. }
  329. if(!dontSend)
  330. connection.emuc.sendPresence();
  331. },
  332. sendLogs: function (data) {
  333. if(!connection.emuc.focusMucJid)
  334. return;
  335. var deflate = true;
  336. var content = JSON.stringify(data);
  337. if (deflate) {
  338. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  339. }
  340. content = Base64.encode(content);
  341. // XEP-0337-ish
  342. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  343. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  344. id: 'PeerConnectionStats'});
  345. message.c('message').t(content).up();
  346. if (deflate) {
  347. message.c('tag', {name: "deflated", value: "true"}).up();
  348. }
  349. message.up();
  350. connection.send(message);
  351. },
  352. populateData: function () {
  353. var data = {};
  354. if (connection.jingle) {
  355. data = connection.jingle.populateData();
  356. }
  357. return data;
  358. },
  359. getLogger: function () {
  360. if(connection.logger)
  361. return connection.logger.log;
  362. return null;
  363. },
  364. getPrezi: function () {
  365. return connection.emuc.getPrezi(this.myJid());
  366. },
  367. removePreziFromPresence: function () {
  368. connection.emuc.removePreziFromPresence();
  369. connection.emuc.sendPresence();
  370. },
  371. sendChatMessage: function (message, nickname) {
  372. connection.emuc.sendMessage(message, nickname);
  373. },
  374. setSubject: function (topic) {
  375. connection.emuc.setSubject(topic);
  376. },
  377. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  378. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  379. },
  380. dial: function (to, from, roomName,roomPass) {
  381. connection.rayo.dial(to, from, roomName,roomPass);
  382. },
  383. setMute: function (jid, mute) {
  384. connection.moderate.setMute(jid, mute);
  385. },
  386. eject: function (jid) {
  387. connection.moderate.eject(jid);
  388. },
  389. findJidFromResource: function (resource) {
  390. return connection.emuc.findJidFromResource(resource);
  391. },
  392. getMembers: function () {
  393. return connection.emuc.members;
  394. },
  395. getJidFromSSRC: function (ssrc) {
  396. if(!connection)
  397. return null;
  398. return connection.emuc.ssrc2jid[ssrc];
  399. }
  400. };
  401. module.exports = XMPP;