modified lib-jitsi-meet dev repo
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

xmpp.js 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. /* global $ */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import { $msg, Strophe } from 'strophe.js';
  4. import 'strophejs-plugin-disco';
  5. import RandomUtil from '../util/RandomUtil';
  6. import * as JitsiConnectionErrors from '../../JitsiConnectionErrors';
  7. import * as JitsiConnectionEvents from '../../JitsiConnectionEvents';
  8. import browser from '../browser';
  9. import initEmuc from './strophe.emuc';
  10. import initJingle from './strophe.jingle';
  11. import initStropheUtil from './strophe.util';
  12. import initPing from './strophe.ping';
  13. import initRayo from './strophe.rayo';
  14. import initStropheLogger from './strophe.logger';
  15. import Listenable from '../util/Listenable';
  16. import Caps from './Caps';
  17. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  18. const logger = getLogger(__filename);
  19. /**
  20. *
  21. * @param token
  22. * @param bosh
  23. */
  24. function createConnection(token, bosh = '/http-bind') {
  25. // Append token as URL param
  26. if (token) {
  27. // eslint-disable-next-line no-param-reassign
  28. bosh += `${bosh.indexOf('?') === -1 ? '?' : '&'}token=${token}`;
  29. }
  30. const conn = new Strophe.Connection(bosh);
  31. // The default maxRetries is 5, which is too long.
  32. conn.maxRetries = 3;
  33. return conn;
  34. }
  35. /**
  36. *
  37. */
  38. export default class XMPP extends Listenable {
  39. /**
  40. * FIXME describe all options
  41. * @param {Object} options
  42. * @param {Array<Object>} options.p2pStunServers see
  43. * {@link JingleConnectionPlugin} for more details.
  44. * @param token
  45. */
  46. constructor(options, token) {
  47. super();
  48. this.connection = null;
  49. this.disconnectInProgress = false;
  50. this.connectionTimes = {};
  51. this.options = options;
  52. this.token = token;
  53. this.authenticatedUser = false;
  54. this._initStrophePlugins(this);
  55. this.connection = createConnection(token, options.bosh);
  56. this.caps = new Caps(this.connection, this.options.clientNode);
  57. // Initialize features advertised in disco-info
  58. this.initFeaturesList();
  59. // Setup a disconnect on unload as a way to facilitate API consumers. It
  60. // sounds like they would want that. A problem for them though may be if
  61. // they wanted to utilize the connected connection in an unload handler
  62. // of their own. However, it should be fairly easy for them to do that
  63. // by registering their unload handler before us.
  64. $(window).on('beforeunload unload', this.disconnect.bind(this));
  65. }
  66. /**
  67. * Initializes the list of feature advertised through the disco-info
  68. * mechanism.
  69. */
  70. initFeaturesList() {
  71. // http://xmpp.org/extensions/xep-0167.html#support
  72. // http://xmpp.org/extensions/xep-0176.html#support
  73. this.caps.addFeature('urn:xmpp:jingle:1');
  74. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:1');
  75. this.caps.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  76. this.caps.addFeature('urn:xmpp:jingle:apps:dtls:0');
  77. this.caps.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  78. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  79. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:video');
  80. if (!this.options.disableRtx && browser.supportsRtx()) {
  81. this.caps.addFeature('urn:ietf:rfc:4588');
  82. }
  83. // this is dealt with by SDP O/A so we don't need to announce this
  84. // XEP-0293
  85. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0');
  86. // XEP-0294
  87. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0');
  88. this.caps.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  89. this.caps.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  90. // this.caps.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  91. // Enable Lipsync ?
  92. if (browser.isChrome() && this.options.enableLipSync !== false) {
  93. logger.info('Lip-sync enabled !');
  94. this.caps.addFeature('http://jitsi.org/meet/lipsync');
  95. }
  96. if (this.connection.rayo) {
  97. this.caps.addFeature('urn:xmpp:rayo:client:1');
  98. }
  99. }
  100. /**
  101. *
  102. */
  103. getConnection() {
  104. return this.connection;
  105. }
  106. /**
  107. * Receive connection status changes and handles them.
  108. *
  109. * @param {Object} credentials
  110. * @param {string} credentials.jid - The user's XMPP ID passed to the
  111. * connect method. For example, 'user@xmpp.com'.
  112. * @param {string} credentials.password - The password passed to the connect
  113. * method.
  114. * @param {string} status - One of Strophe's connection status strings.
  115. * @param {string} [msg] - The connection error message provided by Strophe.
  116. */
  117. connectionHandler(credentials = {}, status, msg) {
  118. const now = window.performance.now();
  119. const statusStr = Strophe.getStatusString(status).toLowerCase();
  120. this.connectionTimes[statusStr] = now;
  121. logger.log(
  122. `(TIME) Strophe ${statusStr}${msg ? `[${msg}]` : ''}:\t`,
  123. now);
  124. if (status === Strophe.Status.CONNECTED
  125. || status === Strophe.Status.ATTACHED) {
  126. if (this.options.useStunTurn
  127. || (this.options.p2p && this.options.p2p.useStunTurn)) {
  128. this.connection.jingle.getStunAndTurnCredentials();
  129. }
  130. logger.info(`My Jabber ID: ${this.connection.jid}`);
  131. // Schedule ping ?
  132. const pingJid = this.connection.domain;
  133. this.caps.getFeaturesAndIdentities(pingJid)
  134. .then(({ features, identities }) => {
  135. if (features.has(Strophe.NS.PING)) {
  136. this.connection.ping.startInterval(pingJid);
  137. } else {
  138. logger.warn(`Ping NOT supported by ${pingJid}`);
  139. }
  140. // check for speakerstats
  141. identities.forEach(identity => {
  142. if (identity.type === 'speakerstats') {
  143. this.speakerStatsComponentAddress = identity.name;
  144. }
  145. });
  146. })
  147. .catch(error => {
  148. const errmsg = 'Feature discovery error';
  149. GlobalOnErrorHandler.callErrorHandler(
  150. new Error(`${errmsg}: ${error}`));
  151. logger.error(errmsg, error);
  152. });
  153. if (credentials.password) {
  154. this.authenticatedUser = true;
  155. }
  156. if (this.connection && this.connection.connected
  157. && Strophe.getResourceFromJid(this.connection.jid)) {
  158. // .connected is true while connecting?
  159. // this.connection.send($pres());
  160. this.eventEmitter.emit(
  161. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  162. Strophe.getResourceFromJid(this.connection.jid));
  163. }
  164. } else if (status === Strophe.Status.CONNFAIL) {
  165. if (msg === 'x-strophe-bad-non-anon-jid') {
  166. this.anonymousConnectionFailed = true;
  167. } else {
  168. this.connectionFailed = true;
  169. }
  170. this.lastErrorMsg = msg;
  171. if (msg === 'giving-up') {
  172. this.eventEmitter.emit(
  173. JitsiConnectionEvents.CONNECTION_FAILED,
  174. JitsiConnectionErrors.OTHER_ERROR, msg);
  175. }
  176. } else if (status === Strophe.Status.DISCONNECTED) {
  177. // Stop ping interval
  178. this.connection.ping.stopInterval();
  179. const wasIntentionalDisconnect = this.disconnectInProgress;
  180. const errMsg = msg || this.lastErrorMsg;
  181. this.disconnectInProgress = false;
  182. if (this.anonymousConnectionFailed) {
  183. // prompt user for username and password
  184. this.eventEmitter.emit(
  185. JitsiConnectionEvents.CONNECTION_FAILED,
  186. JitsiConnectionErrors.PASSWORD_REQUIRED);
  187. } else if (this.connectionFailed) {
  188. this.eventEmitter.emit(
  189. JitsiConnectionEvents.CONNECTION_FAILED,
  190. JitsiConnectionErrors.OTHER_ERROR,
  191. errMsg,
  192. undefined, /* credentials */
  193. this._getConnectionFailedReasonDetails());
  194. } else if (wasIntentionalDisconnect) {
  195. this.eventEmitter.emit(
  196. JitsiConnectionEvents.CONNECTION_DISCONNECTED, errMsg);
  197. } else {
  198. // XXX if Strophe drops the connection while not being asked to,
  199. // it means that most likely some serious error has occurred.
  200. // One currently known case is when a BOSH request fails for
  201. // more than 4 times. The connection is dropped without
  202. // supplying a reason(error message/event) through the API.
  203. logger.error('XMPP connection dropped!');
  204. // XXX if the last request error is within 5xx range it means it
  205. // was a server failure
  206. const lastErrorStatus = Strophe.getLastErrorStatus();
  207. if (lastErrorStatus >= 500 && lastErrorStatus < 600) {
  208. this.eventEmitter.emit(
  209. JitsiConnectionEvents.CONNECTION_FAILED,
  210. JitsiConnectionErrors.SERVER_ERROR,
  211. errMsg || 'server-error');
  212. } else {
  213. this.eventEmitter.emit(
  214. JitsiConnectionEvents.CONNECTION_FAILED,
  215. JitsiConnectionErrors.CONNECTION_DROPPED_ERROR,
  216. errMsg || 'connection-dropped-error');
  217. }
  218. }
  219. } else if (status === Strophe.Status.AUTHFAIL) {
  220. // wrong password or username, prompt user
  221. this.eventEmitter.emit(
  222. JitsiConnectionEvents.CONNECTION_FAILED,
  223. JitsiConnectionErrors.PASSWORD_REQUIRED,
  224. msg,
  225. credentials);
  226. }
  227. }
  228. /**
  229. *
  230. * @param jid
  231. * @param password
  232. */
  233. _connect(jid, password) {
  234. // connection.connect() starts the connection process.
  235. //
  236. // As the connection process proceeds, the user supplied callback will
  237. // be triggered multiple times with status updates. The callback should
  238. // take two arguments - the status code and the error condition.
  239. //
  240. // The status code will be one of the values in the Strophe.Status
  241. // constants. The error condition will be one of the conditions defined
  242. // in RFC 3920 or the condition ‘strophe-parsererror’.
  243. //
  244. // The Parameters wait, hold and route are optional and only relevant
  245. // for BOSH connections. Please see XEP 124 for a more detailed
  246. // explanation of the optional parameters.
  247. //
  248. // Connection status constants for use by the connection handler
  249. // callback.
  250. //
  251. // Status.ERROR - An error has occurred (websockets specific)
  252. // Status.CONNECTING - The connection is currently being made
  253. // Status.CONNFAIL - The connection attempt failed
  254. // Status.AUTHENTICATING - The connection is authenticating
  255. // Status.AUTHFAIL - The authentication attempt failed
  256. // Status.CONNECTED - The connection has succeeded
  257. // Status.DISCONNECTED - The connection has been terminated
  258. // Status.DISCONNECTING - The connection is currently being terminated
  259. // Status.ATTACHED - The connection has been attached
  260. this.anonymousConnectionFailed = false;
  261. this.connectionFailed = false;
  262. this.lastErrorMsg = undefined;
  263. this.connection.connect(
  264. jid,
  265. password,
  266. this.connectionHandler.bind(this, {
  267. jid,
  268. password
  269. }));
  270. }
  271. /**
  272. * Attach to existing connection. Can be used for optimizations. For
  273. * example: if the connection is created on the server we can attach to it
  274. * and start using it.
  275. *
  276. * @param options {object} connecting options - rid, sid, jid and password.
  277. */
  278. attach(options) {
  279. const now = this.connectionTimes.attaching = window.performance.now();
  280. logger.log(`(TIME) Strophe Attaching\t:${now}`);
  281. this.connection.attach(options.jid, options.sid,
  282. parseInt(options.rid, 10) + 1,
  283. this.connectionHandler.bind(this, {
  284. jid: options.jid,
  285. password: options.password
  286. }));
  287. }
  288. /**
  289. *
  290. * @param jid
  291. * @param password
  292. */
  293. connect(jid, password) {
  294. if (!jid) {
  295. const { anonymousdomain, domain } = this.options.hosts;
  296. let configDomain = anonymousdomain || domain;
  297. // Force authenticated domain if room is appended with '?login=true'
  298. // or if we're joining with the token
  299. // FIXME Do not rely on window.location because (1) React Native
  300. // does not have a window.location by default and (2) here we cannot
  301. // know for sure that query/search has not be stripped from
  302. // window.location by the time the following executes.
  303. const { location } = window;
  304. if (anonymousdomain) {
  305. const search = location && location.search;
  306. if ((search && search.indexOf('login=true') !== -1)
  307. || this.token) {
  308. configDomain = domain;
  309. }
  310. }
  311. // eslint-disable-next-line no-param-reassign
  312. jid = configDomain || (location && location.hostname);
  313. }
  314. return this._connect(jid, password);
  315. }
  316. /**
  317. *
  318. * @param roomName
  319. * @param options
  320. */
  321. createRoom(roomName, options) {
  322. // By default MUC nickname is the resource part of the JID
  323. let mucNickname = Strophe.getNodeFromJid(this.connection.jid);
  324. let roomjid = `${roomName}@${this.options.hosts.muc}/`;
  325. const cfgNickname
  326. = options.useNicks && options.nick ? options.nick : null;
  327. if (cfgNickname) {
  328. // Use nick if it's defined
  329. mucNickname = options.nick;
  330. } else if (!this.authenticatedUser) {
  331. // node of the anonymous JID is very long - here we trim it a bit
  332. mucNickname = mucNickname.substr(0, 8);
  333. }
  334. // Constant JIDs need some random part to be appended in order to be
  335. // able to join the MUC more than once.
  336. if (this.authenticatedUser || cfgNickname !== null) {
  337. mucNickname += `-${RandomUtil.randomHexString(6)}`;
  338. }
  339. roomjid += mucNickname;
  340. return this.connection.emuc.createRoom(roomjid, null, options);
  341. }
  342. /**
  343. * Returns the logs from strophe.jingle.
  344. * @returns {Object}
  345. */
  346. getJingleLog() {
  347. const jingle = this.connection.jingle;
  348. return jingle ? jingle.getLog() : {};
  349. }
  350. /**
  351. * Returns the logs from strophe.
  352. */
  353. getXmppLog() {
  354. return (this.connection.logger || {}).log || null;
  355. }
  356. /**
  357. *
  358. */
  359. dial(...args) {
  360. this.connection.rayo.dial(...args);
  361. }
  362. /**
  363. *
  364. * @param jid
  365. * @param mute
  366. */
  367. setMute(jid, mute) {
  368. this.connection.moderate.setMute(jid, mute);
  369. }
  370. /**
  371. *
  372. * @param jid
  373. */
  374. eject(jid) {
  375. this.connection.moderate.eject(jid);
  376. }
  377. /**
  378. *
  379. */
  380. getSessions() {
  381. return this.connection.jingle.sessions;
  382. }
  383. /**
  384. * Disconnects this from the XMPP server (if this is connected).
  385. *
  386. * @param ev optionally, the event which triggered the necessity to
  387. * disconnect from the XMPP server (e.g. beforeunload, unload).
  388. */
  389. disconnect(ev) {
  390. if (this.disconnectInProgress || !this.connection) {
  391. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  392. return;
  393. }
  394. this.disconnectInProgress = true;
  395. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  396. // means that there may not be enough time to send an unavailable
  397. // presence or disconnect at all. Switching Strophe to synchronous
  398. // sending is not much of an option because it may lead to a noticeable
  399. // delay in navigating away from the current location. As a compromise,
  400. // we will try to increase the chances of sending an unavailable
  401. // presence and/or disconecting within the short time span that we have
  402. // upon unloading by invoking flush() on the connection. We flush() once
  403. // before disconnect() in order to attemtp to have its unavailable
  404. // presence at the top of the send queue. We flush() once more after
  405. // disconnect() in order to attempt to have its unavailable presence
  406. // sent as soon as possible.
  407. this.connection.flush();
  408. if (ev !== null && typeof ev !== 'undefined') {
  409. const evType = ev.type;
  410. if (evType === 'beforeunload' || evType === 'unload') {
  411. // XXX Whatever we said above, synchronous sending is the best
  412. // (known) way to properly disconnect from the XMPP server.
  413. // Consequently, it may be fine to have the source code and
  414. // comment it in or out depending on whether we want to run with
  415. // it for some time.
  416. this.connection.options.sync = true;
  417. }
  418. }
  419. this.connection.disconnect();
  420. if (this.connection.options.sync !== true) {
  421. this.connection.flush();
  422. }
  423. }
  424. /**
  425. *
  426. */
  427. _initStrophePlugins() {
  428. const iceConfig = {
  429. jvb: { iceServers: [ ] },
  430. p2p: { iceServers: [ ] }
  431. };
  432. // FIXME: remove once we have a default config template. -saghul
  433. const defaultStunServers = [
  434. { urls: 'stun:stun.l.google.com:19302' },
  435. { urls: 'stun:stun1.l.google.com:19302' },
  436. { urls: 'stun:stun2.l.google.com:19302' }
  437. ];
  438. const p2pStunServers = (this.options.p2p
  439. && this.options.p2p.stunServers) || defaultStunServers;
  440. if (Array.isArray(p2pStunServers)) {
  441. logger.info('P2P STUN servers: ', p2pStunServers);
  442. iceConfig.p2p.iceServers = p2pStunServers;
  443. }
  444. if (this.options.p2p && this.options.p2p.iceTransportPolicy) {
  445. logger.info('P2P ICE transport policy: ',
  446. this.options.p2p.iceTransportPolicy);
  447. iceConfig.p2p.iceTransportPolicy
  448. = this.options.p2p.iceTransportPolicy;
  449. }
  450. initEmuc(this);
  451. initJingle(this, this.eventEmitter, iceConfig);
  452. initStropheUtil();
  453. initPing(this);
  454. initRayo();
  455. initStropheLogger();
  456. }
  457. /**
  458. * Returns details about connection failure. Shard change or is it after
  459. * suspend.
  460. * @returns {object} contains details about a connection failure.
  461. * @private
  462. */
  463. _getConnectionFailedReasonDetails() {
  464. const details = {};
  465. // check for moving between shard if information is available
  466. if (this.options.deploymentInfo
  467. && this.options.deploymentInfo.shard
  468. && this.connection._proto
  469. && this.connection._proto.lastResponseHeaders) {
  470. // split headers by line
  471. const headersArr = this.connection._proto.lastResponseHeaders
  472. .trim().split(/[\r\n]+/);
  473. const headers = {};
  474. headersArr.forEach(line => {
  475. const parts = line.split(': ');
  476. const header = parts.shift();
  477. const value = parts.join(': ');
  478. headers[header] = value;
  479. });
  480. /* eslint-disable camelcase */
  481. details.shard_changed
  482. = this.options.deploymentInfo.shard
  483. !== headers['x-jitsi-shard'];
  484. /* eslint-enable camelcase */
  485. }
  486. /* eslint-disable camelcase */
  487. // check for possible suspend
  488. details.suspend_time = this.connection.ping.getPingSuspendTime();
  489. /* eslint-enable camelcase */
  490. return details;
  491. }
  492. /**
  493. * Notifies speaker stats component if available that we are the new
  494. * dominant speaker in the conference.
  495. * @param {String} roomJid - The room jid where the speaker event occurred.
  496. */
  497. sendDominantSpeakerEvent(roomJid) {
  498. // no speaker stats component advertised
  499. if (!this.speakerStatsComponentAddress || !roomJid) {
  500. return;
  501. }
  502. const msg = $msg({ to: this.speakerStatsComponentAddress });
  503. msg.c('speakerstats', {
  504. xmlns: 'http://jitsi.org/jitmeet',
  505. room: `${roomJid}` })
  506. .up();
  507. this.connection.send(msg);
  508. }
  509. }