Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

xmpp.js 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. /* global $, APP, config, Strophe*/
  2. var Moderator = require("./moderator");
  3. var EventEmitter = require("events");
  4. var Recording = require("./recording");
  5. var SDP = require("./SDP");
  6. var Settings = require("../settings/Settings");
  7. var Pako = require("pako");
  8. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  9. var RTCEvents = require("../../service/RTC/RTCEvents");
  10. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11. var retry = require('retry');
  12. var eventEmitter = new EventEmitter();
  13. var connection = null;
  14. var authenticatedUser = false;
  15. function connect(jid, password) {
  16. var faultTolerantConnect = retry.operation({
  17. retries: 3
  18. });
  19. // fault tolerant connect
  20. faultTolerantConnect.attempt(function () {
  21. connection = XMPP.createConnection();
  22. Moderator.setConnection(connection);
  23. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  24. if (config.useIPv6) {
  25. // https://code.google.com/p/webrtc/issues/detail?id=2828
  26. if (!connection.jingle.pc_constraints.optional)
  27. connection.jingle.pc_constraints.optional = [];
  28. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  29. }
  30. // Include user info in MUC presence
  31. var settings = Settings.getSettings();
  32. if (settings.email) {
  33. connection.emuc.addEmailToPresence(settings.email);
  34. }
  35. if (settings.uid) {
  36. connection.emuc.addUserIdToPresence(settings.uid);
  37. }
  38. if (settings.displayName) {
  39. connection.emuc.addDisplayNameToPresence(settings.displayName);
  40. }
  41. // connection.connect() starts the connection process.
  42. //
  43. // As the connection process proceeds, the user supplied callback will
  44. // be triggered multiple times with status updates. The callback should
  45. // take two arguments - the status code and the error condition.
  46. //
  47. // The status code will be one of the values in the Strophe.Status
  48. // constants. The error condition will be one of the conditions defined
  49. // in RFC 3920 or the condition ‘strophe-parsererror’.
  50. //
  51. // The Parameters wait, hold and route are optional and only relevant
  52. // for BOSH connections. Please see XEP 124 for a more detailed
  53. // explanation of the optional parameters.
  54. //
  55. // Connection status constants for use by the connection handler
  56. // callback.
  57. //
  58. // Status.ERROR - An error has occurred (websockets specific)
  59. // Status.CONNECTING - The connection is currently being made
  60. // Status.CONNFAIL - The connection attempt failed
  61. // Status.AUTHENTICATING - The connection is authenticating
  62. // Status.AUTHFAIL - The authentication attempt failed
  63. // Status.CONNECTED - The connection has succeeded
  64. // Status.DISCONNECTED - The connection has been terminated
  65. // Status.DISCONNECTING - The connection is currently being terminated
  66. // Status.ATTACHED - The connection has been attached
  67. var anonymousConnectionFailed = false;
  68. var connectionFailed = false;
  69. var lastErrorMsg;
  70. connection.connect(jid, password, function (status, msg) {
  71. console.log('Strophe status changed to',
  72. Strophe.getStatusString(status), msg);
  73. if (status === Strophe.Status.CONNECTED) {
  74. if (config.useStunTurn) {
  75. connection.jingle.getStunAndTurnCredentials();
  76. }
  77. console.info("My Jabber ID: " + connection.jid);
  78. if (password)
  79. authenticatedUser = true;
  80. maybeDoJoin();
  81. } else if (status === Strophe.Status.CONNFAIL) {
  82. if (msg === 'x-strophe-bad-non-anon-jid') {
  83. anonymousConnectionFailed = true;
  84. } else {
  85. connectionFailed = true;
  86. }
  87. lastErrorMsg = msg;
  88. } else if (status === Strophe.Status.DISCONNECTED) {
  89. if (anonymousConnectionFailed) {
  90. // prompt user for username and password
  91. XMPP.promptLogin();
  92. } else {
  93. // Strophe already has built-in HTTP/BOSH error handling and
  94. // request retry logic. Requests are resent automatically
  95. // until their error count reaches 5. Strophe.js disconnects
  96. // if the error count is > 5. We are not replicating this
  97. // here.
  98. //
  99. // The "problem" is that failed HTTP/BOSH requests don't
  100. // trigger a callback with a status update, so when a
  101. // callback with status Strophe.Status.DISCONNECTED arrives,
  102. // we can't be sure if it's a graceful disconnect or if it's
  103. // triggered by some HTTP/BOSH error.
  104. //
  105. // But that's a minor issue in Jitsi Meet as we never
  106. // disconnect anyway, not even when the user closes the
  107. // browser window (which is kind of wrong, but the point is
  108. // that we should never ever get disconnected).
  109. //
  110. // On the other hand, failed connections due to XMPP layer
  111. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  112. //
  113. // Here we implement retry logic for failed connections due
  114. // to XMPP layer errors and we display an error to the user
  115. // if we get disconnected from the XMPP server permanently.
  116. // If the connection failed, retry.
  117. if (connectionFailed &&
  118. faultTolerantConnect.retry("connection-failed")) {
  119. return;
  120. }
  121. // If we failed to connect to the XMPP server, fire an event
  122. // to let all the interested module now about it.
  123. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  124. msg ? msg : lastErrorMsg);
  125. }
  126. } else if (status === Strophe.Status.AUTHFAIL) {
  127. // wrong password or username, prompt user
  128. XMPP.promptLogin();
  129. }
  130. });
  131. });
  132. }
  133. function maybeDoJoin() {
  134. if (connection && connection.connected &&
  135. Strophe.getResourceFromJid(connection.jid) &&
  136. (APP.RTC.localAudio || APP.RTC.localVideo)) {
  137. // .connected is true while connecting?
  138. doJoin();
  139. }
  140. }
  141. function doJoin() {
  142. eventEmitter.emit(XMPPEvents.READY_TO_JOIN);
  143. }
  144. function initStrophePlugins()
  145. {
  146. require("./strophe.emuc")(XMPP, eventEmitter);
  147. require("./strophe.jingle")(XMPP, eventEmitter);
  148. require("./strophe.moderate")(XMPP, eventEmitter);
  149. require("./strophe.util")();
  150. require("./strophe.rayo")();
  151. require("./strophe.logger")();
  152. }
  153. function registerListeners() {
  154. APP.RTC.addStreamListener(maybeDoJoin,
  155. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  156. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  157. XMPP.addToPresence("devices", devices);
  158. });
  159. }
  160. var unload = (function () {
  161. var unloaded = false;
  162. return function () {
  163. if (unloaded) { return; }
  164. unloaded = true;
  165. if (connection && connection.connected) {
  166. // ensure signout
  167. $.ajax({
  168. type: 'POST',
  169. url: config.bosh,
  170. async: false,
  171. cache: false,
  172. contentType: 'application/xml',
  173. data: "<body rid='" +
  174. (connection.rid || connection._proto.rid) +
  175. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  176. (connection.sid || connection._proto.sid) +
  177. "' type='terminate'>" +
  178. "<presence xmlns='jabber:client' type='unavailable'/>" +
  179. "</body>",
  180. success: function (data) {
  181. console.log('signed out');
  182. console.log(data);
  183. },
  184. error: function (XMLHttpRequest, textStatus, errorThrown) {
  185. console.log('signout error',
  186. textStatus + ' (' + errorThrown + ')');
  187. }
  188. });
  189. }
  190. XMPP.disposeConference(true);
  191. };
  192. })();
  193. function setupEvents() {
  194. // In recent versions of FF the 'beforeunload' event is not fired when the
  195. // window or the tab is closed. It is only fired when we leave the page
  196. // (change URL). If this participant doesn't unload properly, then it
  197. // becomes a ghost for the rest of the participants that stay in the
  198. // conference. Thankfully handling the 'unload' event in addition to the
  199. // 'beforeunload' event seems to guarantee the execution of the 'unload'
  200. // method at least once.
  201. //
  202. // The 'unload' method can safely be run multiple times, it will actually do
  203. // something only the first time that it's run, so we're don't have to worry
  204. // about browsers that fire both events.
  205. $(window).bind('beforeunload', unload);
  206. $(window).bind('unload', unload);
  207. }
  208. var XMPP = {
  209. getConnection: function(){ return connection; },
  210. sessionTerminated: false,
  211. /**
  212. * XMPP connection status
  213. */
  214. Status: Strophe.Status,
  215. /**
  216. * Remembers if we were muted by the focus.
  217. * @type {boolean}
  218. */
  219. forceMuted: false,
  220. start: function () {
  221. setupEvents();
  222. initStrophePlugins();
  223. registerListeners();
  224. Moderator.init(this, eventEmitter);
  225. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  226. // Force authenticated domain if room is appended with '?login=true'
  227. if (config.hosts.anonymousdomain &&
  228. window.location.search.indexOf("login=true") !== -1) {
  229. configDomain = config.hosts.domain;
  230. }
  231. var jid = configDomain || window.location.hostname;
  232. connect(jid, null);
  233. },
  234. createConnection: function () {
  235. var bosh = config.bosh || '/http-bind';
  236. return new Strophe.Connection(bosh);
  237. },
  238. getStatusString: function (status) {
  239. return Strophe.getStatusString(status);
  240. },
  241. promptLogin: function () {
  242. eventEmitter.emit(XMPPEvents.PROMPT_FOR_LOGIN);
  243. },
  244. joinRoom: function(roomName, useNicks, nick) {
  245. var roomjid = roomName;
  246. if (useNicks) {
  247. if (nick) {
  248. roomjid += '/' + nick;
  249. } else {
  250. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  251. }
  252. } else {
  253. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  254. if(!authenticatedUser)
  255. tmpJid = tmpJid.substr(0, 8);
  256. roomjid += '/' + tmpJid;
  257. }
  258. connection.emuc.doJoin(roomjid);
  259. },
  260. myJid: function () {
  261. if(!connection)
  262. return null;
  263. return connection.emuc.myroomjid;
  264. },
  265. myResource: function () {
  266. if(!connection || ! connection.emuc.myroomjid)
  267. return null;
  268. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  269. },
  270. disposeConference: function (onUnload) {
  271. var handler = connection.jingle.activecall;
  272. if (handler && handler.peerconnection) {
  273. // FIXME: probably removing streams is not required and close() should
  274. // be enough
  275. if (APP.RTC.localAudio) {
  276. handler.peerconnection.removeStream(
  277. APP.RTC.localAudio.getOriginalStream(), onUnload);
  278. }
  279. if (APP.RTC.localVideo) {
  280. handler.peerconnection.removeStream(
  281. APP.RTC.localVideo.getOriginalStream(), onUnload);
  282. }
  283. handler.peerconnection.close();
  284. }
  285. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  286. connection.jingle.activecall = null;
  287. if (!onUnload) {
  288. this.sessionTerminated = true;
  289. connection.emuc.doLeave();
  290. }
  291. },
  292. addListener: function(type, listener) {
  293. eventEmitter.on(type, listener);
  294. },
  295. removeListener: function (type, listener) {
  296. eventEmitter.removeListener(type, listener);
  297. },
  298. allocateConferenceFocus: function(roomName, callback) {
  299. Moderator.allocateConferenceFocus(roomName, callback);
  300. },
  301. getLoginUrl: function (roomName, callback) {
  302. Moderator.getLoginUrl(roomName, callback);
  303. },
  304. getPopupLoginUrl: function (roomName, callback) {
  305. Moderator.getPopupLoginUrl(roomName, callback);
  306. },
  307. isModerator: function () {
  308. return Moderator.isModerator();
  309. },
  310. isSipGatewayEnabled: function () {
  311. return Moderator.isSipGatewayEnabled();
  312. },
  313. isExternalAuthEnabled: function () {
  314. return Moderator.isExternalAuthEnabled();
  315. },
  316. isConferenceInProgress: function () {
  317. return connection && connection.jingle.activecall &&
  318. connection.jingle.activecall.peerconnection;
  319. },
  320. switchStreams: function (stream, oldStream, callback, isAudio) {
  321. if (this.isConferenceInProgress()) {
  322. // FIXME: will block switchInProgress on true value in case of exception
  323. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  324. } else {
  325. // We are done immediately
  326. console.warn("No conference handler or conference not started yet");
  327. callback();
  328. }
  329. },
  330. sendVideoInfoPresence: function (mute) {
  331. if(!connection)
  332. return;
  333. connection.emuc.addVideoInfoToPresence(mute);
  334. connection.emuc.sendPresence();
  335. },
  336. setVideoMute: function (mute, callback, options) {
  337. if(!connection)
  338. return;
  339. var self = this;
  340. var localCallback = function (mute) {
  341. self.sendVideoInfoPresence(mute);
  342. return callback(mute);
  343. };
  344. if(connection.jingle.activecall)
  345. {
  346. connection.jingle.activecall.setVideoMute(
  347. mute, localCallback, options);
  348. }
  349. else {
  350. localCallback(mute);
  351. }
  352. },
  353. setAudioMute: function (mute, callback) {
  354. if (!(connection && APP.RTC.localAudio)) {
  355. return false;
  356. }
  357. if (this.forceMuted && !mute) {
  358. console.info("Asking focus for unmute");
  359. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  360. // FIXME: wait for result before resetting muted status
  361. this.forceMuted = false;
  362. }
  363. if (mute == APP.RTC.localAudio.isMuted()) {
  364. // Nothing to do
  365. return true;
  366. }
  367. APP.RTC.localAudio.setMute(mute);
  368. this.sendAudioInfoPresence(mute, callback);
  369. return true;
  370. },
  371. sendAudioInfoPresence: function(mute, callback) {
  372. if(connection) {
  373. connection.emuc.addAudioInfoToPresence(mute);
  374. connection.emuc.sendPresence();
  375. }
  376. callback();
  377. return true;
  378. },
  379. toggleRecording: function (tokenEmptyCallback,
  380. startingCallback, startedCallback) {
  381. Recording.toggleRecording(tokenEmptyCallback,
  382. startingCallback, startedCallback, connection);
  383. },
  384. addToPresence: function (name, value, dontSend) {
  385. switch (name) {
  386. case "displayName":
  387. connection.emuc.addDisplayNameToPresence(value);
  388. break;
  389. case "prezi":
  390. connection.emuc.addPreziToPresence(value, 0);
  391. break;
  392. case "preziSlide":
  393. connection.emuc.addCurrentSlideToPresence(value);
  394. break;
  395. case "connectionQuality":
  396. connection.emuc.addConnectionInfoToPresence(value);
  397. break;
  398. case "email":
  399. connection.emuc.addEmailToPresence(value);
  400. break;
  401. case "devices":
  402. connection.emuc.addDevicesToPresence(value);
  403. break;
  404. case "startMuted":
  405. if(!Moderator.isModerator())
  406. return;
  407. connection.emuc.addStartMutedToPresence(value[0],
  408. value[1]);
  409. break;
  410. default :
  411. console.log("Unknown tag for presence: " + name);
  412. return;
  413. }
  414. if (!dontSend)
  415. connection.emuc.sendPresence();
  416. },
  417. /**
  418. * Sends 'data' as a log message to the focus. Returns true iff a message
  419. * was sent.
  420. * @param data
  421. * @returns {boolean} true iff a message was sent.
  422. */
  423. sendLogs: function (data) {
  424. if(!connection.emuc.focusMucJid)
  425. return false;
  426. var deflate = true;
  427. var content = JSON.stringify(data);
  428. if (deflate) {
  429. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  430. }
  431. content = Base64.encode(content);
  432. // XEP-0337-ish
  433. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  434. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  435. id: 'PeerConnectionStats'});
  436. message.c('message').t(content).up();
  437. if (deflate) {
  438. message.c('tag', {name: "deflated", value: "true"}).up();
  439. }
  440. message.up();
  441. connection.send(message);
  442. return true;
  443. },
  444. populateData: function () {
  445. var data = {};
  446. if (connection.jingle) {
  447. data = connection.jingle.populateData();
  448. }
  449. return data;
  450. },
  451. getLogger: function () {
  452. if(connection.logger)
  453. return connection.logger.log;
  454. return null;
  455. },
  456. getPrezi: function () {
  457. return connection.emuc.getPrezi(this.myJid());
  458. },
  459. removePreziFromPresence: function () {
  460. connection.emuc.removePreziFromPresence();
  461. connection.emuc.sendPresence();
  462. },
  463. sendChatMessage: function (message, nickname) {
  464. connection.emuc.sendMessage(message, nickname);
  465. },
  466. setSubject: function (topic) {
  467. connection.emuc.setSubject(topic);
  468. },
  469. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  470. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  471. },
  472. dial: function (to, from, roomName,roomPass) {
  473. connection.rayo.dial(to, from, roomName,roomPass);
  474. },
  475. setMute: function (jid, mute) {
  476. connection.moderate.setMute(jid, mute);
  477. },
  478. eject: function (jid) {
  479. connection.moderate.eject(jid);
  480. },
  481. logout: function (callback) {
  482. Moderator.logout(callback);
  483. },
  484. findJidFromResource: function (resource) {
  485. return connection.emuc.findJidFromResource(resource);
  486. },
  487. getMembers: function () {
  488. return connection.emuc.members;
  489. },
  490. getJidFromSSRC: function (ssrc) {
  491. if (!this.isConferenceInProgress())
  492. return null;
  493. return connection.jingle.activecall.getSsrcOwner(ssrc);
  494. },
  495. getMUCJoined: function () {
  496. return connection.emuc.joined;
  497. },
  498. getSessions: function () {
  499. return connection.jingle.sessions;
  500. },
  501. removeStream: function (stream) {
  502. if (!this.isConferenceInProgress())
  503. return;
  504. connection.jingle.activecall.peerconnection.removeStream(stream);
  505. }
  506. };
  507. module.exports = XMPP;