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

xmpp.js 40KB

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