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

xmpp.js 40KB

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