modified lib-jitsi-meet dev repo
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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