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

xmpp.js 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. /* global $ */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import { $msg, Strophe } from 'strophe.js';
  4. import 'strophejs-plugin-disco';
  5. import * as JitsiConnectionErrors from '../../JitsiConnectionErrors';
  6. import * as JitsiConnectionEvents from '../../JitsiConnectionEvents';
  7. import XMPPEvents from '../../service/xmpp/XMPPEvents';
  8. import browser from '../browser';
  9. import { E2EEncryption } from '../e2ee/E2EEncryption';
  10. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  11. import Listenable from '../util/Listenable';
  12. import RandomUtil from '../util/RandomUtil';
  13. import Caps, { parseDiscoInfo } from './Caps';
  14. import XmppConnection from './XmppConnection';
  15. import MucConnectionPlugin from './strophe.emuc';
  16. import JingleConnectionPlugin from './strophe.jingle';
  17. import initStropheLogger from './strophe.logger';
  18. import RayoConnectionPlugin from './strophe.rayo';
  19. import initStropheUtil from './strophe.util';
  20. const logger = getLogger(__filename);
  21. /**
  22. * Regex to extract exact error message on jwt error.
  23. */
  24. const FAILURE_REGEX = /<failure.*><not-allowed\/><text>(.*)<\/text><\/failure>/gi;
  25. /**
  26. * Creates XMPP connection.
  27. *
  28. * @param {Object} options
  29. * @param {string} [options.token] - JWT token used for authentication(JWT authentication module must be enabled in
  30. * Prosody).
  31. * @param {string} options.serviceUrl - The service URL for XMPP connection.
  32. * @param {string} options.shard - The shard where XMPP connection initially landed.
  33. * @param {string} options.enableWebsocketResume - True to enable stream resumption.
  34. * @param {number} [options.websocketKeepAlive] - See {@link XmppConnection} constructor.
  35. * @param {number} [options.websocketKeepAliveUrl] - See {@link XmppConnection} constructor.
  36. * @param {Object} [options.xmppPing] - See {@link XmppConnection} constructor.
  37. * @returns {XmppConnection}
  38. */
  39. function createConnection({
  40. enableWebsocketResume,
  41. serviceUrl = '/http-bind',
  42. shard,
  43. token,
  44. websocketKeepAlive,
  45. websocketKeepAliveUrl,
  46. xmppPing }) {
  47. // Append token as URL param
  48. if (token) {
  49. // eslint-disable-next-line no-param-reassign
  50. serviceUrl += `${serviceUrl.indexOf('?') === -1 ? '?' : '&'}token=${token}`;
  51. }
  52. return new XmppConnection({
  53. enableWebsocketResume,
  54. serviceUrl,
  55. websocketKeepAlive,
  56. websocketKeepAliveUrl,
  57. xmppPing,
  58. shard
  59. });
  60. }
  61. /**
  62. * Initializes Strophe plugins that need to work with Strophe.Connection directly rather than the lib-jitsi-meet's
  63. * {@link XmppConnection} wrapper.
  64. *
  65. * @returns {void}
  66. */
  67. function initStropheNativePlugins() {
  68. initStropheUtil();
  69. initStropheLogger();
  70. }
  71. // FIXME: remove once we have a default config template. -saghul
  72. /**
  73. * A list of ice servers to use by default for P2P.
  74. */
  75. export const DEFAULT_STUN_SERVERS = [
  76. { urls: 'stun:meet-jit-si-turnrelay.jitsi.net:443' }
  77. ];
  78. /**
  79. * The name of the field used to recognize a chat message as carrying a JSON
  80. * payload from another endpoint.
  81. * If the json-message of a chat message contains a valid JSON object, and
  82. * the JSON has this key, then it is a valid json-message to be sent.
  83. */
  84. export const JITSI_MEET_MUC_TYPE = 'type';
  85. /**
  86. * The feature used by jigasi participants.
  87. * @type {string}
  88. */
  89. export const FEATURE_JIGASI = 'http://jitsi.org/protocol/jigasi';
  90. /**
  91. * The feature used by the lib to mark support for e2ee. We use the feature by putting it in the presence
  92. * to avoid additional signaling (disco-info).
  93. * @type {string}
  94. */
  95. export const FEATURE_E2EE = 'https://jitsi.org/meet/e2ee';
  96. /**
  97. *
  98. */
  99. export default class XMPP extends Listenable {
  100. /**
  101. * FIXME describe all options
  102. * @param {Object} options
  103. * @param {String} options.serviceUrl - URL passed to the XMPP client which will be used to establish XMPP
  104. * connection with the server.
  105. * @param {String} options.bosh - Deprecated, use {@code serviceUrl}.
  106. * @param {boolean} options.enableWebsocketResume - Enables XEP-0198 stream management which will make the XMPP
  107. * module try to resume the session in case the Websocket connection breaks.
  108. * @param {number} [options.websocketKeepAlive] - The websocket keep alive interval. See {@link XmppConnection}
  109. * constructor for more details.
  110. * @param {number} [options.websocketKeepAliveUrl] - The websocket keep alive url. See {@link XmppConnection}
  111. * constructor for more details.
  112. * @param {Object} [options.xmppPing] - The xmpp ping settings.
  113. * @param {Array<Object>} options.p2pStunServers see {@link JingleConnectionPlugin} for more details.
  114. * @param token
  115. */
  116. constructor(options, token) {
  117. super();
  118. this.connection = null;
  119. this.disconnectInProgress = false;
  120. this.connectionTimes = {};
  121. this.options = options;
  122. this.token = token;
  123. this.authenticatedUser = false;
  124. initStropheNativePlugins();
  125. const xmppPing = options.xmppPing || {};
  126. // let's ping the main domain (in case a guest one is used for the connection)
  127. xmppPing.domain = options.hosts.domain;
  128. this.connection = createConnection({
  129. enableWebsocketResume: options.enableWebsocketResume,
  130. // FIXME remove deprecated bosh option at some point
  131. serviceUrl: options.serviceUrl || options.bosh,
  132. token,
  133. websocketKeepAlive: options.websocketKeepAlive,
  134. websocketKeepAliveUrl: options.websocketKeepAliveUrl,
  135. xmppPing,
  136. shard: options.deploymentInfo?.shard
  137. });
  138. // forwards the shard changed event
  139. this.connection.on(XmppConnection.Events.CONN_SHARD_CHANGED, () => {
  140. /* eslint-disable camelcase */
  141. const details = {
  142. shard_changed: true,
  143. suspend_time: this.connection.ping.getPingSuspendTime(),
  144. time_since_last_success: this.connection.getTimeSinceLastSuccess()
  145. };
  146. /* eslint-enable camelcase */
  147. this.eventEmitter.emit(
  148. JitsiConnectionEvents.CONNECTION_FAILED,
  149. JitsiConnectionErrors.OTHER_ERROR,
  150. undefined,
  151. undefined,
  152. details);
  153. });
  154. this._initStrophePlugins();
  155. this.caps = new Caps(this.connection, /* clientNode */ 'https://jitsi.org/jitsi-meet');
  156. // Initialize features advertised in disco-info
  157. this.initFeaturesList();
  158. // Setup a disconnect on unload as a way to facilitate API consumers. It
  159. // sounds like they would want that. A problem for them though may be if
  160. // they wanted to utilize the connected connection in an unload handler
  161. // of their own. However, it should be fairly easy for them to do that
  162. // by registering their unload handler before us.
  163. $(window).on('beforeunload unload', ev => {
  164. this.disconnect(ev).catch(() => {
  165. // ignore errors in order to not brake the unload.
  166. });
  167. });
  168. }
  169. /**
  170. * Initializes the list of feature advertised through the disco-info
  171. * mechanism.
  172. */
  173. initFeaturesList() {
  174. // http://xmpp.org/extensions/xep-0167.html#support
  175. // http://xmpp.org/extensions/xep-0176.html#support
  176. this.caps.addFeature('urn:xmpp:jingle:1');
  177. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:1');
  178. this.caps.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  179. this.caps.addFeature('urn:xmpp:jingle:apps:dtls:0');
  180. this.caps.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  181. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  182. this.caps.addFeature('urn:xmpp:jingle:apps:rtp:video');
  183. this.caps.addFeature('http://jitsi.org/json-encoded-sources');
  184. // Disable RTX on Firefox 83 and older versions because of
  185. // https://bugzilla.mozilla.org/show_bug.cgi?id=1668028
  186. if (!(this.options.disableRtx || (browser.isFirefox() && browser.isVersionLessThan(84)))) {
  187. this.caps.addFeature('urn:ietf:rfc:4588');
  188. }
  189. if (this.options.enableOpusRed === true && browser.supportsAudioRed()) {
  190. this.caps.addFeature('http://jitsi.org/opus-red');
  191. }
  192. if (typeof this.options.enableRemb === 'undefined' || this.options.enableRemb) {
  193. this.caps.addFeature('http://jitsi.org/remb');
  194. }
  195. // Disable TCC on Firefox because of a known issue where BWE is halved on every renegotiation.
  196. if (!browser.isFirefox() && (typeof this.options.enableTcc === 'undefined' || this.options.enableTcc)) {
  197. this.caps.addFeature('http://jitsi.org/tcc');
  198. }
  199. // this is dealt with by SDP O/A so we don't need to announce this
  200. // XEP-0293
  201. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0');
  202. // XEP-0294
  203. // this.caps.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0');
  204. this.caps.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  205. this.caps.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  206. // this.caps.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  207. // Enable Lipsync ?
  208. if (browser.isChromiumBased() && this.options.enableLipSync === true) {
  209. logger.info('Lip-sync enabled !');
  210. this.caps.addFeature('http://jitsi.org/meet/lipsync');
  211. }
  212. if (this.connection.rayo) {
  213. this.caps.addFeature('urn:xmpp:rayo:client:1');
  214. }
  215. if (E2EEncryption.isSupported(this.options)) {
  216. this.caps.addFeature(FEATURE_E2EE, false, true);
  217. }
  218. }
  219. /**
  220. *
  221. */
  222. getConnection() {
  223. return this.connection;
  224. }
  225. /**
  226. * Receive connection status changes and handles them.
  227. *
  228. * @param {Object} credentials
  229. * @param {string} credentials.jid - The user's XMPP ID passed to the
  230. * connect method. For example, 'user@xmpp.com'.
  231. * @param {string} credentials.password - The password passed to the connect
  232. * method.
  233. * @param {string} status - One of Strophe's connection status strings.
  234. * @param {string} [msg] - The connection error message provided by Strophe.
  235. */
  236. connectionHandler(credentials = {}, status, msg) {
  237. const now = window.performance.now();
  238. const statusStr = Strophe.getStatusString(status).toLowerCase();
  239. this.connectionTimes[statusStr] = now;
  240. logger.log(
  241. `(TIME) Strophe ${statusStr}${msg ? `[${msg}]` : ''}:\t`,
  242. now);
  243. this.eventEmitter.emit(XMPPEvents.CONNECTION_STATUS_CHANGED, credentials, status, msg);
  244. if (status === Strophe.Status.CONNECTED || status === Strophe.Status.ATTACHED) {
  245. // once connected or attached we no longer need this handle, drop it if it exist
  246. if (this._sysMessageHandler) {
  247. this.connection._stropheConn.deleteHandler(this._sysMessageHandler);
  248. this._sysMessageHandler = null;
  249. }
  250. this.sendDiscoInfo && this.connection.jingle.getStunAndTurnCredentials();
  251. logger.info(`My Jabber ID: ${this.connection.jid}`);
  252. // XmppConnection emits CONNECTED again on reconnect - a good opportunity to clear any "last error" flags
  253. this._resetState();
  254. this.sendDiscoInfo && this.caps.getFeaturesAndIdentities(this.options.hosts.domain)
  255. .then(({ features, identities }) => {
  256. if (!features.has(Strophe.NS.PING)) {
  257. logger.error(`Ping NOT supported by ${
  258. this.options.hosts.domain} - please enable ping in your XMPP server config`);
  259. }
  260. this._processDiscoInfoIdentities(
  261. identities, undefined /* when querying we will query for features */);
  262. })
  263. .catch(error => {
  264. const errmsg = 'Feature discovery error';
  265. GlobalOnErrorHandler.callErrorHandler(
  266. new Error(`${errmsg}: ${error}`));
  267. logger.error(errmsg, error);
  268. });
  269. // make sure we don't query again
  270. this.sendDiscoInfo = false;
  271. if (credentials.password) {
  272. this.authenticatedUser = true;
  273. }
  274. if (this.connection && this.connection.connected
  275. && Strophe.getResourceFromJid(this.connection.jid)) {
  276. // .connected is true while connecting?
  277. // this.connection.send($pres());
  278. this.eventEmitter.emit(
  279. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  280. Strophe.getResourceFromJid(this.connection.jid));
  281. }
  282. } else if (status === Strophe.Status.CONNFAIL) {
  283. if (msg === 'x-strophe-bad-non-anon-jid') {
  284. this.anonymousConnectionFailed = true;
  285. } else {
  286. this.connectionFailed = true;
  287. }
  288. this.lastErrorMsg = msg;
  289. if (msg === 'giving-up') {
  290. this.eventEmitter.emit(
  291. JitsiConnectionEvents.CONNECTION_FAILED,
  292. JitsiConnectionErrors.OTHER_ERROR, msg);
  293. }
  294. } else if (status === Strophe.Status.ERROR) {
  295. this.lastErrorMsg = msg;
  296. } else if (status === Strophe.Status.DISCONNECTED) {
  297. // Stop ping interval
  298. this.connection.ping.stopInterval();
  299. const wasIntentionalDisconnect = Boolean(this.disconnectInProgress);
  300. const errMsg = msg || this.lastErrorMsg;
  301. if (this.anonymousConnectionFailed) {
  302. // prompt user for username and password
  303. this.eventEmitter.emit(
  304. JitsiConnectionEvents.CONNECTION_FAILED,
  305. JitsiConnectionErrors.PASSWORD_REQUIRED);
  306. } else if (this.connectionFailed) {
  307. this.eventEmitter.emit(
  308. JitsiConnectionEvents.CONNECTION_FAILED,
  309. JitsiConnectionErrors.OTHER_ERROR,
  310. errMsg,
  311. undefined, /* credentials */
  312. this._getConnectionFailedReasonDetails());
  313. } else if (wasIntentionalDisconnect) {
  314. this.eventEmitter.emit(
  315. JitsiConnectionEvents.CONNECTION_DISCONNECTED, errMsg);
  316. } else {
  317. // XXX if Strophe drops the connection while not being asked to,
  318. // it means that most likely some serious error has occurred.
  319. // One currently known case is when a BOSH request fails for
  320. // more than 4 times. The connection is dropped without
  321. // supplying a reason(error message/event) through the API.
  322. logger.error('XMPP connection dropped!');
  323. // XXX if the last request error is within 5xx range it means it
  324. // was a server failure
  325. const lastErrorStatus = Strophe.getLastErrorStatus();
  326. if (lastErrorStatus >= 500 && lastErrorStatus < 600) {
  327. this.eventEmitter.emit(
  328. JitsiConnectionEvents.CONNECTION_FAILED,
  329. JitsiConnectionErrors.SERVER_ERROR,
  330. errMsg || 'server-error',
  331. /* credentials */ undefined,
  332. this._getConnectionFailedReasonDetails());
  333. } else {
  334. this.eventEmitter.emit(
  335. JitsiConnectionEvents.CONNECTION_FAILED,
  336. JitsiConnectionErrors.CONNECTION_DROPPED_ERROR,
  337. errMsg || 'connection-dropped-error',
  338. /* credentials */ undefined,
  339. this._getConnectionFailedReasonDetails());
  340. }
  341. }
  342. } else if (status === Strophe.Status.AUTHFAIL) {
  343. const lastFailedRawMessage = this.getConnection().getLastFailedMessage();
  344. // wrong password or username, prompt user
  345. this.eventEmitter.emit(
  346. JitsiConnectionEvents.CONNECTION_FAILED,
  347. JitsiConnectionErrors.PASSWORD_REQUIRED,
  348. msg || this._parseConnectionFailedMessage(lastFailedRawMessage),
  349. credentials);
  350. }
  351. }
  352. /**
  353. * Process received identities.
  354. * @param {Set<String>} identities The identities to process.
  355. * @param {Set<String>} features The features to process, optional. If missing lobby component will be queried
  356. * for more features.
  357. * @private
  358. */
  359. _processDiscoInfoIdentities(identities, features) {
  360. // check for speakerstats
  361. identities.forEach(identity => {
  362. if (identity.type === 'av_moderation') {
  363. this.avModerationComponentAddress = identity.name;
  364. }
  365. if (identity.type === 'speakerstats') {
  366. this.speakerStatsComponentAddress = identity.name;
  367. }
  368. if (identity.type === 'conference_duration') {
  369. this.conferenceDurationComponentAddress = identity.name;
  370. }
  371. if (identity.type === 'lobbyrooms') {
  372. this.lobbySupported = true;
  373. const processLobbyFeatures = f => {
  374. f.forEach(fr => {
  375. if (fr.endsWith('#displayname_required')) {
  376. this.eventEmitter.emit(JitsiConnectionEvents.DISPLAY_NAME_REQUIRED);
  377. }
  378. });
  379. };
  380. if (features) {
  381. processLobbyFeatures(features);
  382. } else {
  383. identity.name && this.caps.getFeaturesAndIdentities(identity.name, identity.type)
  384. .then(({ features: f }) => processLobbyFeatures(f))
  385. .catch(e => logger.warn('Error getting features from lobby.', e && e.message));
  386. }
  387. }
  388. });
  389. if (this.avModerationComponentAddress
  390. || this.speakerStatsComponentAddress
  391. || this.conferenceDurationComponentAddress) {
  392. this.connection.addHandler(this._onPrivateMessage.bind(this), null, 'message', null, null);
  393. }
  394. }
  395. /**
  396. * Parses a raw failure xmpp xml message received on auth failed.
  397. *
  398. * @param {string} msg - The raw failure message from xmpp.
  399. * @returns {string|null} - The parsed message from the raw xmpp message.
  400. */
  401. _parseConnectionFailedMessage(msg) {
  402. if (!msg) {
  403. return null;
  404. }
  405. const matches = FAILURE_REGEX.exec(msg);
  406. return matches ? matches[1] : null;
  407. }
  408. /**
  409. *
  410. * @param jid
  411. * @param password
  412. */
  413. _connect(jid, password) {
  414. // connection.connect() starts the connection process.
  415. //
  416. // As the connection process proceeds, the user supplied callback will
  417. // be triggered multiple times with status updates. The callback should
  418. // take two arguments - the status code and the error condition.
  419. //
  420. // The status code will be one of the values in the Strophe.Status
  421. // constants. The error condition will be one of the conditions defined
  422. // in RFC 3920 or the condition ‘strophe-parsererror’.
  423. //
  424. // The Parameters wait, hold and route are optional and only relevant
  425. // for BOSH connections. Please see XEP 124 for a more detailed
  426. // explanation of the optional parameters.
  427. //
  428. // Connection status constants for use by the connection handler
  429. // callback.
  430. //
  431. // Status.ERROR - An error has occurred (websockets specific)
  432. // Status.CONNECTING - The connection is currently being made
  433. // Status.CONNFAIL - The connection attempt failed
  434. // Status.AUTHENTICATING - The connection is authenticating
  435. // Status.AUTHFAIL - The authentication attempt failed
  436. // Status.CONNECTED - The connection has succeeded
  437. // Status.DISCONNECTED - The connection has been terminated
  438. // Status.DISCONNECTING - The connection is currently being terminated
  439. // Status.ATTACHED - The connection has been attached
  440. this._resetState();
  441. // we want to send this only on the initial connect
  442. this.sendDiscoInfo = true;
  443. if (this.connection._stropheConn && this.connection._stropheConn._addSysHandler) {
  444. this._sysMessageHandler = this.connection._stropheConn._addSysHandler(
  445. this._onSystemMessage.bind(this),
  446. null,
  447. 'message'
  448. );
  449. } else {
  450. logger.warn('Cannot attach strophe system handler, jiconop cannot operate');
  451. }
  452. this.connection.connect(
  453. jid,
  454. password,
  455. this.connectionHandler.bind(this, {
  456. jid,
  457. password
  458. }));
  459. }
  460. /**
  461. * Receives system messages during the connect/login process and checks for services or
  462. * @param msg The received message.
  463. * @returns {void}
  464. * @private
  465. */
  466. _onSystemMessage(msg) {
  467. // proceed only if the message has any of the expected information
  468. if ($(msg).find('>services').length === 0 && $(msg).find('>query').length === 0) {
  469. return;
  470. }
  471. this.sendDiscoInfo = false;
  472. const foundIceServers = this.connection.jingle.onReceiveStunAndTurnCredentials(msg);
  473. const { features, identities } = parseDiscoInfo(msg);
  474. this._processDiscoInfoIdentities(identities, features);
  475. // check for shard name in identities
  476. identities.forEach(i => {
  477. if (i.type === 'shard') {
  478. this.options.deploymentInfo.shard = this.connection.shard = i.name;
  479. }
  480. });
  481. if (foundIceServers || identities.size > 0 || features.size > 0) {
  482. this.connection._stropheConn.deleteHandler(this._sysMessageHandler);
  483. this._sysMessageHandler = null;
  484. }
  485. }
  486. /**
  487. * Attach to existing connection. Can be used for optimizations. For
  488. * example: if the connection is created on the server we can attach to it
  489. * and start using it.
  490. *
  491. * @param options {object} connecting options - rid, sid, jid and password.
  492. */
  493. attach(options) {
  494. this._resetState();
  495. // we want to send this only on the initial connect
  496. this.sendDiscoInfo = true;
  497. const now = this.connectionTimes.attaching = window.performance.now();
  498. logger.log('(TIME) Strophe Attaching:\t', now);
  499. this.connection.attach(options.jid, options.sid,
  500. parseInt(options.rid, 10) + 1,
  501. this.connectionHandler.bind(this, {
  502. jid: options.jid,
  503. password: options.password
  504. }));
  505. }
  506. /**
  507. * Resets any state/flag before starting a new connection.
  508. * @private
  509. */
  510. _resetState() {
  511. this.anonymousConnectionFailed = false;
  512. this.connectionFailed = false;
  513. this.lastErrorMsg = undefined;
  514. this.disconnectInProgress = undefined;
  515. }
  516. /**
  517. *
  518. * @param jid
  519. * @param password
  520. */
  521. connect(jid, password) {
  522. if (!jid) {
  523. const { anonymousdomain, domain } = this.options.hosts;
  524. let configDomain = anonymousdomain || domain;
  525. // Force authenticated domain if room is appended with '?login=true'
  526. // or if we're joining with the token
  527. // FIXME Do not rely on window.location because (1) React Native
  528. // does not have a window.location by default and (2) here we cannot
  529. // know for sure that query/search has not be stripped from
  530. // window.location by the time the following executes.
  531. const { location } = window;
  532. if (anonymousdomain) {
  533. const search = location && location.search;
  534. if ((search && search.indexOf('login=true') !== -1)
  535. || this.token) {
  536. configDomain = domain;
  537. }
  538. }
  539. // eslint-disable-next-line no-param-reassign
  540. jid = configDomain || (location && location.hostname);
  541. }
  542. return this._connect(jid, password);
  543. }
  544. /**
  545. * Joins or creates a muc with the provided jid, created from the passed
  546. * in room name and muc host and onCreateResource result.
  547. *
  548. * @param {string} roomName - The name of the muc to join.
  549. * @param {Object} options - Configuration for how to join the muc.
  550. * @param {Function} [onCreateResource] - Callback to invoke when a resource
  551. * is to be added to the jid.
  552. * @returns {Promise} Resolves with an instance of a strophe muc.
  553. */
  554. createRoom(roomName, options, onCreateResource) {
  555. // There are cases (when using subdomain) where muc can hold an uppercase part
  556. let roomjid = `${roomName}@${options.customDomain
  557. ? options.customDomain : this.options.hosts.muc.toLowerCase()}/`;
  558. const mucNickname = onCreateResource
  559. ? onCreateResource(this.connection.jid, this.authenticatedUser)
  560. : RandomUtil.randomHexString(8).toLowerCase();
  561. logger.info(`JID ${this.connection.jid} using MUC nickname ${mucNickname}`);
  562. roomjid += mucNickname;
  563. return this.connection.emuc.createRoom(roomjid, null, options);
  564. }
  565. /**
  566. * Returns the jid of the participant associated with the Strophe connection.
  567. *
  568. * @returns {string} The jid of the participant.
  569. */
  570. getJid() {
  571. return this.connection.jid;
  572. }
  573. /**
  574. * Returns the logs from strophe.jingle.
  575. * @returns {Object}
  576. */
  577. getJingleLog() {
  578. const jingle = this.connection.jingle;
  579. return jingle ? jingle.getLog() : {};
  580. }
  581. /**
  582. * Returns the logs from strophe.
  583. */
  584. getXmppLog() {
  585. return (this.connection.logger || {}).log || null;
  586. }
  587. /**
  588. *
  589. */
  590. dial(...args) {
  591. this.connection.rayo.dial(...args);
  592. }
  593. /**
  594. * Pings the server.
  595. * @param timeout how many ms before a timeout should occur.
  596. * @returns {Promise} resolved on ping success and reject on an error or
  597. * a timeout.
  598. */
  599. ping(timeout) {
  600. return new Promise((resolve, reject) => {
  601. this.connection.ping.ping(this.connection.pingDomain, resolve, reject, timeout);
  602. });
  603. }
  604. /**
  605. *
  606. */
  607. getSessions() {
  608. return this.connection.jingle.sessions;
  609. }
  610. /**
  611. * Disconnects this from the XMPP server (if this is connected).
  612. *
  613. * @param {Object} ev - Optionally, the event which triggered the necessity to
  614. * disconnect from the XMPP server (e.g. beforeunload, unload).
  615. * @returns {Promise} - Resolves when the disconnect process is finished or rejects with an error.
  616. */
  617. disconnect(ev) {
  618. if (this.disconnectInProgress) {
  619. return this.disconnectInProgress;
  620. } else if (!this.connection) {
  621. return Promise.resolve();
  622. }
  623. this.disconnectInProgress = new Promise(resolve => {
  624. const disconnectListener = (credentials, status) => {
  625. if (status === Strophe.Status.DISCONNECTED) {
  626. resolve();
  627. this.eventEmitter.removeListener(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  628. }
  629. };
  630. this.eventEmitter.on(XMPPEvents.CONNECTION_STATUS_CHANGED, disconnectListener);
  631. });
  632. this._cleanupXmppConnection(ev);
  633. return this.disconnectInProgress;
  634. }
  635. /**
  636. * The method is supposed to gracefully close the XMPP connection and the main goal is to make sure that the current
  637. * participant will be removed from the conference XMPP MUC, so that it doesn't leave a "ghost" participant behind.
  638. *
  639. * @param {Object} ev - Optionally, the event which triggered the necessity to disconnect from the XMPP server
  640. * (e.g. beforeunload, unload).
  641. * @private
  642. * @returns {void}
  643. */
  644. _cleanupXmppConnection(ev) {
  645. // XXX Strophe is asynchronously sending by default. Unfortunately, that means that there may not be enough time
  646. // to send an unavailable presence or disconnect at all. Switching Strophe to synchronous sending is not much of
  647. // an option because it may lead to a noticeable delay in navigating away from the current location. As
  648. // a compromise, we will try to increase the chances of sending an unavailable presence and/or disconnecting
  649. // within the short time span that we have upon unloading by invoking flush() on the connection. We flush() once
  650. // before disconnect() in order to attempt to have its unavailable presence at the top of the send queue. We
  651. // flush() once more after disconnect() in order to attempt to have its unavailable presence sent as soon as
  652. // possible.
  653. !this.connection.isUsingWebSocket && this.connection.flush();
  654. if (!this.connection.isUsingWebSocket && ev !== null && typeof ev !== 'undefined') {
  655. const evType = ev.type;
  656. if (evType === 'beforeunload' || evType === 'unload') {
  657. // XXX Whatever we said above, synchronous sending is the best (known) way to properly disconnect from
  658. // the XMPP server. Consequently, it may be fine to have the source code and comment it in or out
  659. // depending on whether we want to run with it for some time.
  660. this.connection.options.sync = true;
  661. // This is needed in some browsers where sync xhr sending is disabled by default on unload.
  662. if (this.connection.sendUnavailableBeacon()) {
  663. return;
  664. }
  665. }
  666. }
  667. this.connection.disconnect();
  668. if (this.connection.options.sync !== true) {
  669. this.connection.flush();
  670. }
  671. }
  672. /**
  673. *
  674. */
  675. _initStrophePlugins() {
  676. const iceConfig = {
  677. jvb: { iceServers: [ ] },
  678. p2p: { iceServers: [ ] }
  679. };
  680. const p2pStunServers = (this.options.p2p
  681. && this.options.p2p.stunServers) || DEFAULT_STUN_SERVERS;
  682. if (Array.isArray(p2pStunServers)) {
  683. logger.info('P2P STUN servers: ', p2pStunServers);
  684. iceConfig.p2p.iceServers = p2pStunServers;
  685. }
  686. if (this.options.p2p && this.options.p2p.iceTransportPolicy) {
  687. logger.info('P2P ICE transport policy: ',
  688. this.options.p2p.iceTransportPolicy);
  689. iceConfig.p2p.iceTransportPolicy
  690. = this.options.p2p.iceTransportPolicy;
  691. }
  692. this.connection.addConnectionPlugin('emuc', new MucConnectionPlugin(this));
  693. this.connection.addConnectionPlugin('jingle', new JingleConnectionPlugin(this, this.eventEmitter, iceConfig));
  694. this.connection.addConnectionPlugin('rayo', new RayoConnectionPlugin());
  695. }
  696. /**
  697. * Returns details about connection failure. Shard change or is it after
  698. * suspend.
  699. * @returns {object} contains details about a connection failure.
  700. * @private
  701. */
  702. _getConnectionFailedReasonDetails() {
  703. const details = {};
  704. // check for moving between shard if information is available
  705. if (this.options.deploymentInfo
  706. && this.options.deploymentInfo.shard
  707. && this.connection.lastResponseHeaders) {
  708. // split headers by line
  709. const headersArr = this.connection.lastResponseHeaders
  710. .trim().split(/[\r\n]+/);
  711. const headers = {};
  712. headersArr.forEach(line => {
  713. const parts = line.split(': ');
  714. const header = parts.shift();
  715. const value = parts.join(': ');
  716. headers[header] = value;
  717. });
  718. /* eslint-disable camelcase */
  719. details.shard_changed
  720. = this.options.deploymentInfo.shard
  721. !== headers['x-jitsi-shard'];
  722. /* eslint-enable camelcase */
  723. }
  724. /* eslint-disable camelcase */
  725. // check for possible suspend
  726. details.suspend_time = this.connection.ping.getPingSuspendTime();
  727. details.time_since_last_success = this.connection.getTimeSinceLastSuccess();
  728. /* eslint-enable camelcase */
  729. return details;
  730. }
  731. /**
  732. * Notifies speaker stats component if available that we are the new
  733. * dominant speaker in the conference.
  734. * @param {String} roomJid - The room jid where the speaker event occurred.
  735. */
  736. sendDominantSpeakerEvent(roomJid) {
  737. // no speaker stats component advertised
  738. if (!this.speakerStatsComponentAddress || !roomJid) {
  739. return;
  740. }
  741. const msg = $msg({ to: this.speakerStatsComponentAddress });
  742. msg.c('speakerstats', {
  743. xmlns: 'http://jitsi.org/jitmeet',
  744. room: roomJid })
  745. .up();
  746. this.connection.send(msg);
  747. }
  748. /**
  749. * Check if the given argument is a valid JSON ENDPOINT_MESSAGE string by
  750. * parsing it and checking if it has a field called 'type'.
  751. *
  752. * @param {string} jsonString check if this string is a valid json string
  753. * and contains the special structure.
  754. * @returns {boolean, object} if given object is a valid JSON string, return
  755. * the json object. Otherwise, returns false.
  756. */
  757. tryParseJSONAndVerify(jsonString) {
  758. // ignore empty strings, like message errors
  759. if (!jsonString) {
  760. return false;
  761. }
  762. try {
  763. const json = JSON.parse(jsonString);
  764. // Handle non-exception-throwing cases:
  765. // Neither JSON.parse(false) or JSON.parse(1234) throw errors,
  766. // hence the type-checking,
  767. // but... JSON.parse(null) returns null, and
  768. // typeof null === "object",
  769. // so we must check for that, too.
  770. // Thankfully, null is falsey, so this suffices:
  771. if (json && typeof json === 'object') {
  772. const type = json[JITSI_MEET_MUC_TYPE];
  773. if (typeof type !== 'undefined') {
  774. return json;
  775. }
  776. logger.debug('parsing valid json but does not have correct '
  777. + 'structure', 'topic: ', type);
  778. }
  779. } catch (e) {
  780. logger.error(`Error parsing json ${jsonString}`, e);
  781. return false;
  782. }
  783. return false;
  784. }
  785. /**
  786. * A private message is received, message that is not addressed to the muc.
  787. * We expect private message coming from plugins component if it is
  788. * enabled and running.
  789. *
  790. * @param {string} msg - The message.
  791. */
  792. _onPrivateMessage(msg) {
  793. const from = msg.getAttribute('from');
  794. if (!(from === this.speakerStatsComponentAddress
  795. || from === this.conferenceDurationComponentAddress
  796. || from === this.avModerationComponentAddress)) {
  797. return true;
  798. }
  799. const jsonMessage = $(msg).find('>json-message')
  800. .text();
  801. const parsedJson = this.tryParseJSONAndVerify(jsonMessage);
  802. if (!parsedJson) {
  803. return true;
  804. }
  805. if (parsedJson[JITSI_MEET_MUC_TYPE] === 'speakerstats' && parsedJson.users) {
  806. this.eventEmitter.emit(XMPPEvents.SPEAKER_STATS_RECEIVED, parsedJson.users);
  807. } else if (parsedJson[JITSI_MEET_MUC_TYPE] === 'conference_duration' && parsedJson.created_timestamp) {
  808. this.eventEmitter.emit(XMPPEvents.CONFERENCE_TIMESTAMP_RECEIVED, parsedJson.created_timestamp);
  809. } else if (parsedJson[JITSI_MEET_MUC_TYPE] === 'av_moderation') {
  810. this.eventEmitter.emit(XMPPEvents.AV_MODERATION_RECEIVED, parsedJson);
  811. }
  812. return true;
  813. }
  814. }