您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

xmpp.js 22KB

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