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

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