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 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. var Moderator = require("./moderator");
  2. var EventEmitter = require("events");
  3. var Recording = require("./recording");
  4. var SDP = require("./SDP");
  5. var eventEmitter = new EventEmitter();
  6. var connection = null;
  7. var authenticatedUser = false;
  8. var activecall = null;
  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")();
  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. }
  91. function setupEvents() {
  92. $(window).bind('beforeunload', function () {
  93. if (connection && connection.connected) {
  94. // ensure signout
  95. $.ajax({
  96. type: 'POST',
  97. url: config.bosh,
  98. async: false,
  99. cache: false,
  100. contentType: 'application/xml',
  101. data: "<body rid='" + (connection.rid || connection._proto.rid)
  102. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  103. + (connection.sid || connection._proto.sid)
  104. + "' type='terminate'>" +
  105. "<presence xmlns='jabber:client' type='unavailable'/>" +
  106. "</body>",
  107. success: function (data) {
  108. console.log('signed out');
  109. console.log(data);
  110. },
  111. error: function (XMLHttpRequest, textStatus, errorThrown) {
  112. console.log('signout error',
  113. textStatus + ' (' + errorThrown + ')');
  114. }
  115. });
  116. }
  117. XMPP.disposeConference(true);
  118. });
  119. }
  120. var XMPP = {
  121. sessionTerminated: false,
  122. /**
  123. * Remembers if we were muted by the focus.
  124. * @type {boolean}
  125. */
  126. forceMuted: false,
  127. start: function (uiCredentials) {
  128. setupEvents();
  129. initStrophePlugins();
  130. registerListeners();
  131. Moderator.init();
  132. var jid = uiCredentials.jid ||
  133. config.hosts.anonymousdomain ||
  134. config.hosts.domain ||
  135. window.location.hostname;
  136. connect(jid, null, uiCredentials);
  137. },
  138. promptLogin: function () {
  139. UI.showLoginPopup(connect);
  140. },
  141. joinRooom: function(roomName, useNicks, nick)
  142. {
  143. var roomjid;
  144. roomjid = roomName;
  145. if (useNicks) {
  146. if (nick) {
  147. roomjid += '/' + nick;
  148. } else {
  149. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  150. }
  151. } else {
  152. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  153. if(!authenticatedUser)
  154. tmpJid = tmpJid.substr(0, 8);
  155. roomjid += '/' + tmpJid;
  156. }
  157. connection.emuc.doJoin(roomjid);
  158. },
  159. myJid: function () {
  160. if(!connection)
  161. return null;
  162. return connection.emuc.myroomjid;
  163. },
  164. myResource: function () {
  165. if(!connection || ! connection.emuc.myroomjid)
  166. return null;
  167. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  168. },
  169. disposeConference: function (onUnload) {
  170. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  171. var handler = activecall;
  172. if (handler && handler.peerconnection) {
  173. // FIXME: probably removing streams is not required and close() should
  174. // be enough
  175. if (RTC.localAudio) {
  176. handler.peerconnection.removeStream(RTC.localAudio.getOriginalStream(), onUnload);
  177. }
  178. if (RTC.localVideo) {
  179. handler.peerconnection.removeStream(RTC.localVideo.getOriginalStream(), onUnload);
  180. }
  181. handler.peerconnection.close();
  182. }
  183. activecall = null;
  184. if(!onUnload)
  185. {
  186. this.sessionTerminated = true;
  187. connection.emuc.doLeave();
  188. }
  189. },
  190. addListener: function(type, listener)
  191. {
  192. eventEmitter.on(type, listener);
  193. },
  194. removeListener: function (type, listener) {
  195. eventEmitter.removeListener(type, listener);
  196. },
  197. allocateConferenceFocus: function(roomName, callback) {
  198. Moderator.allocateConferenceFocus(roomName, callback);
  199. },
  200. isModerator: function () {
  201. return Moderator.isModerator();
  202. },
  203. isSipGatewayEnabled: function () {
  204. return Moderator.isSipGatewayEnabled();
  205. },
  206. isExternalAuthEnabled: function () {
  207. return Moderator.isExternalAuthEnabled();
  208. },
  209. switchStreams: function (stream, oldStream, callback) {
  210. if (activecall) {
  211. // FIXME: will block switchInProgress on true value in case of exception
  212. activecall.switchStreams(stream, oldStream, callback);
  213. } else {
  214. // We are done immediately
  215. console.error("No conference handler");
  216. UI.messageHandler.showError('Error',
  217. 'Unable to switch video stream.');
  218. callback();
  219. }
  220. },
  221. setVideoMute: function (mute, callback, options) {
  222. if(activecall && connection && RTC.localVideo)
  223. {
  224. activecall.setVideoMute(mute, callback, options);
  225. }
  226. },
  227. setAudioMute: function (mute, callback) {
  228. if (!(connection && RTC.localAudio)) {
  229. return false;
  230. }
  231. if (this.forceMuted && !mute) {
  232. console.info("Asking focus for unmute");
  233. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  234. // FIXME: wait for result before resetting muted status
  235. this.forceMuted = false;
  236. }
  237. if (mute == RTC.localAudio.isMuted()) {
  238. // Nothing to do
  239. return true;
  240. }
  241. // It is not clear what is the right way to handle multiple tracks.
  242. // So at least make sure that they are all muted or all unmuted and
  243. // that we send presence just once.
  244. RTC.localAudio.mute();
  245. // isMuted is the opposite of audioEnabled
  246. connection.emuc.addAudioInfoToPresence(mute);
  247. connection.emuc.sendPresence();
  248. callback();
  249. return true;
  250. },
  251. // Really mute video, i.e. dont even send black frames
  252. muteVideo: function (pc, unmute) {
  253. // FIXME: this probably needs another of those lovely state safeguards...
  254. // which checks for iceconn == connected and sigstate == stable
  255. pc.setRemoteDescription(pc.remoteDescription,
  256. function () {
  257. pc.createAnswer(
  258. function (answer) {
  259. var sdp = new SDP(answer.sdp);
  260. if (sdp.media.length > 1) {
  261. if (unmute)
  262. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  263. else
  264. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  265. sdp.raw = sdp.session + sdp.media.join('');
  266. answer.sdp = sdp.raw;
  267. }
  268. pc.setLocalDescription(answer,
  269. function () {
  270. console.log('mute SLD ok');
  271. },
  272. function (error) {
  273. console.log('mute SLD error');
  274. UI.messageHandler.showError('Error',
  275. 'Oops! Something went wrong and we failed to ' +
  276. 'mute! (SLD Failure)');
  277. }
  278. );
  279. },
  280. function (error) {
  281. console.log(error);
  282. UI.messageHandler.showError();
  283. }
  284. );
  285. },
  286. function (error) {
  287. console.log('muteVideo SRD error');
  288. UI.messageHandler.showError('Error',
  289. 'Oops! Something went wrong and we failed to stop video!' +
  290. '(SRD Failure)');
  291. }
  292. );
  293. },
  294. toggleRecording: function (tokenEmptyCallback,
  295. startingCallback, startedCallback) {
  296. Recording.toggleRecording(tokenEmptyCallback,
  297. startingCallback, startedCallback);
  298. },
  299. addToPresence: function (name, value, dontSend) {
  300. switch (name)
  301. {
  302. case "displayName":
  303. connection.emuc.addDisplayNameToPresence(value);
  304. break;
  305. case "etherpad":
  306. connection.emuc.addEtherpadToPresence(value);
  307. break;
  308. case "prezi":
  309. connection.emuc.addPreziToPresence(value, 0);
  310. break;
  311. case "preziSlide":
  312. connection.emuc.addCurrentSlideToPresence(value);
  313. break;
  314. case "connectionQuality":
  315. connection.emuc.addConnectionInfoToPresence(value);
  316. break;
  317. case "email":
  318. connection.emuc.addEmailToPresence(value);
  319. default :
  320. console.log("Unknown tag for presence.");
  321. return;
  322. }
  323. if(!dontSend)
  324. connection.emuc.sendPresence();
  325. },
  326. sendLogs: function (data) {
  327. if(!focusMucJid)
  328. return;
  329. var deflate = true;
  330. var content = JSON.stringify(dataYes);
  331. if (deflate) {
  332. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  333. }
  334. content = Base64.encode(content);
  335. // XEP-0337-ish
  336. var message = $msg({to: focusMucJid, type: 'normal'});
  337. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  338. id: 'PeerConnectionStats'});
  339. message.c('message').t(content).up();
  340. if (deflate) {
  341. message.c('tag', {name: "deflated", value: "true"}).up();
  342. }
  343. message.up();
  344. connection.send(message);
  345. },
  346. populateData: function () {
  347. var data = {};
  348. if (connection.jingle) {
  349. data = connection.jingle.populateData();
  350. }
  351. return data;
  352. },
  353. getLogger: function () {
  354. if(connection.logger)
  355. return connection.logger.log;
  356. return null;
  357. },
  358. getPrezi: function () {
  359. return connection.emuc.getPrezi(this.myJid());
  360. },
  361. removePreziFromPresence: function () {
  362. connection.emuc.removePreziFromPresence();
  363. connection.emuc.sendPresence();
  364. },
  365. sendChatMessage: function (message, nickname) {
  366. connection.emuc.sendMessage(message, nickname);
  367. },
  368. setSubject: function (topic) {
  369. connection.emuc.setSubject(topic);
  370. },
  371. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  372. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  373. },
  374. dial: function (to, from, roomName,roomPass) {
  375. connection.rayo.dial(to, from, roomName,roomPass);
  376. },
  377. setMute: function (jid, mute) {
  378. connection.moderate.setMute(jid, mute);
  379. },
  380. eject: function (jid) {
  381. connection.moderate.eject(jid);
  382. },
  383. findJidFromResource: function (resource) {
  384. connection.emuc.findJidFromResource(resource);
  385. },
  386. getMembers: function () {
  387. return connection.emuc.members;
  388. }
  389. };
  390. module.exports = XMPP;