Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

xmpp.js 42KB

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