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

xmpp.js 39KB

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