modified lib-jitsi-meet dev repo
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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