You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ChatRoom.js 46KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  1. /* global $, __filename */
  2. import { getLogger } from 'jitsi-meet-logger';
  3. import { $iq, $msg, $pres, Strophe } from 'strophe.js';
  4. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  5. import * as JitsiTranscriptionStatus from '../../JitsiTranscriptionStatus';
  6. import Listenable from '../util/Listenable';
  7. import * as MediaType from '../../service/RTC/MediaType';
  8. import { createConferenceEvent } from '../../service/statistics/AnalyticsEvents';
  9. import XMPPEvents from '../../service/xmpp/XMPPEvents';
  10. import Statistics from '../statistics/statistics';
  11. import Moderator from './moderator';
  12. const logger = getLogger(__filename);
  13. export const parser = {
  14. packet2JSON(xmlElement, nodes) {
  15. for (const child of Array.from(xmlElement.children)) {
  16. const node = {
  17. attributes: {},
  18. children: [],
  19. tagName: child.tagName
  20. };
  21. for (const attr of Array.from(child.attributes)) {
  22. node.attributes[attr.name] = attr.value;
  23. }
  24. const text = Strophe.getText(child);
  25. if (text) {
  26. // Using Strophe.getText will do work for traversing all direct
  27. // child text nodes but returns an escaped value, which is not
  28. // desirable at this point.
  29. node.value = Strophe.xmlunescape(text);
  30. }
  31. nodes.push(node);
  32. this.packet2JSON(child, node.children);
  33. }
  34. },
  35. json2packet(nodes, packet) {
  36. for (let i = 0; i < nodes.length; i++) {
  37. const node = nodes[i];
  38. if (node) {
  39. packet.c(node.tagName, node.attributes);
  40. if (node.value) {
  41. packet.t(node.value);
  42. }
  43. if (node.children) {
  44. this.json2packet(node.children, packet);
  45. }
  46. packet.up();
  47. }
  48. }
  49. // packet.up();
  50. }
  51. };
  52. /**
  53. * Returns array of JS objects from the presence JSON associated with the passed
  54. / nodeName
  55. * @param pres the presence JSON
  56. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  57. */
  58. function filterNodeFromPresenceJSON(pres, nodeName) {
  59. const res = [];
  60. for (let i = 0; i < pres.length; i++) {
  61. if (pres[i].tagName === nodeName) {
  62. res.push(pres[i]);
  63. }
  64. }
  65. return res;
  66. }
  67. // XXX As ChatRoom constructs XMPP stanzas and Strophe is build around the idea
  68. // of chaining function calls, allow long function call chains.
  69. /* eslint-disable newline-per-chained-call */
  70. /**
  71. *
  72. */
  73. export default class ChatRoom extends Listenable {
  74. /* eslint-disable max-params */
  75. /**
  76. *
  77. * @param {XmppConnection} connection - The XMPP connection instance.
  78. * @param jid
  79. * @param password
  80. * @param XMPP
  81. * @param options
  82. * @param {boolean} options.disableFocus - when set to {@code false} will
  83. * not invite Jicofo into the room. This is intended to be used only by
  84. * jitsi-meet-spot.
  85. */
  86. constructor(connection, jid, password, XMPP, options) {
  87. super();
  88. this.xmpp = XMPP;
  89. this.connection = connection;
  90. this.roomjid = Strophe.getBareJidFromJid(jid);
  91. this.myroomjid = jid;
  92. this.password = password;
  93. logger.info(`Joined MUC as ${this.myroomjid}`);
  94. this.members = {};
  95. this.presMap = {};
  96. this.presHandlers = {};
  97. this.joined = false;
  98. this.role = null;
  99. this.focusMucJid = null;
  100. this.noBridgeAvailable = false;
  101. this.options = options || {};
  102. this.moderator
  103. = new Moderator(this.roomjid, this.xmpp, this.eventEmitter, {
  104. connection: this.xmpp.options,
  105. conference: this.options
  106. });
  107. this.initPresenceMap(options);
  108. this.lastPresences = {};
  109. this.phoneNumber = null;
  110. this.phonePin = null;
  111. this.connectionTimes = {};
  112. this.participantPropertyListener = null;
  113. this.locked = false;
  114. this.transcriptionStatus = JitsiTranscriptionStatus.OFF;
  115. }
  116. /* eslint-enable max-params */
  117. /**
  118. *
  119. */
  120. initPresenceMap(options = {}) {
  121. this.presMap.to = this.myroomjid;
  122. this.presMap.xns = 'http://jabber.org/protocol/muc';
  123. this.presMap.nodes = [];
  124. if (options.statsId) {
  125. this.presMap.nodes.push({
  126. 'tagName': 'stats-id',
  127. 'value': options.statsId
  128. });
  129. }
  130. // We need to broadcast 'videomuted' status from the beginning, cause
  131. // Jicofo makes decisions based on that. Initialize it with 'false'
  132. // here.
  133. this.addVideoInfoToPresence(false);
  134. if (options.deploymentInfo && options.deploymentInfo.userRegion) {
  135. this.presMap.nodes.push({
  136. 'tagName': 'region',
  137. 'attributes': {
  138. id: options.deploymentInfo.userRegion,
  139. xmlns: 'http://jitsi.org/jitsi-meet'
  140. }
  141. });
  142. }
  143. }
  144. /**
  145. * Joins the chat room.
  146. * @param password
  147. * @returns {Promise} - resolved when join completes. At the time of this
  148. * writing it's never rejected.
  149. */
  150. join(password) {
  151. this.password = password;
  152. return new Promise(resolve => {
  153. this.options.disableFocus
  154. && logger.info('Conference focus disabled');
  155. const preJoin
  156. = this.options.disableFocus
  157. ? Promise.resolve()
  158. : this.moderator.allocateConferenceFocus();
  159. preJoin.then(() => {
  160. this.sendPresence(true);
  161. resolve();
  162. });
  163. });
  164. }
  165. /**
  166. *
  167. * @param fromJoin
  168. */
  169. sendPresence(fromJoin) {
  170. const to = this.presMap.to;
  171. if (!this.connection || !this.connection.connected || !to || (!this.joined && !fromJoin)) {
  172. // Too early to send presence - not initialized
  173. return;
  174. }
  175. const pres = $pres({ to });
  176. // xep-0045 defines: "including in the initial presence stanza an empty
  177. // <x/> element qualified by the 'http://jabber.org/protocol/muc'
  178. // namespace" and subsequent presences should not include that or it can
  179. // be considered as joining, and server can send us the message history
  180. // for the room on every presence
  181. if (fromJoin) {
  182. pres.c('x', { xmlns: this.presMap.xns });
  183. if (this.password) {
  184. pres.c('password').t(this.password).up();
  185. }
  186. pres.up();
  187. }
  188. parser.json2packet(this.presMap.nodes, pres);
  189. this.connection.send(pres);
  190. if (fromJoin) {
  191. // XXX We're pressed for time here because we're beginning a complex
  192. // and/or lengthy conference-establishment process which supposedly
  193. // involves multiple RTTs. We don't have the time to wait for
  194. // Strophe to decide to send our IQ.
  195. this.connection.flush();
  196. }
  197. }
  198. /**
  199. * Sends the presence unavailable, signaling the server
  200. * we want to leave the room.
  201. */
  202. doLeave() {
  203. logger.log('do leave', this.myroomjid);
  204. const pres = $pres({ to: this.myroomjid,
  205. type: 'unavailable' });
  206. this.presMap.length = 0;
  207. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  208. // means that there may not be enough time to send the unavailable
  209. // presence. Switching Strophe to synchronous sending is not much of an
  210. // option because it may lead to a noticeable delay in navigating away
  211. // from the current location. As a compromise, we will try to increase
  212. // the chances of sending the unavailable presence within the short time
  213. // span that we have upon unloading by invoking flush() on the
  214. // connection. We flush() once before sending/queuing the unavailable
  215. // presence in order to attemtp to have the unavailable presence at the
  216. // top of the send queue. We flush() once more after sending/queuing the
  217. // unavailable presence in order to attempt to have it sent as soon as
  218. // possible.
  219. // FIXME do not use Strophe.Connection in the ChatRoom directly
  220. !this.connection.isUsingWebSocket && this.connection.flush();
  221. this.connection.send(pres);
  222. this.connection.flush();
  223. }
  224. /**
  225. *
  226. */
  227. discoRoomInfo() {
  228. // https://xmpp.org/extensions/xep-0045.html#disco-roominfo
  229. const getInfo
  230. = $iq({
  231. type: 'get',
  232. to: this.roomjid
  233. })
  234. .c('query', { xmlns: Strophe.NS.DISCO_INFO });
  235. this.connection.sendIQ(getInfo, result => {
  236. const locked
  237. = $(result).find('>query>feature[var="muc_passwordprotected"]')
  238. .length
  239. === 1;
  240. if (locked !== this.locked) {
  241. this.eventEmitter.emit(XMPPEvents.MUC_LOCK_CHANGED, locked);
  242. this.locked = locked;
  243. }
  244. const meetingIdValEl
  245. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_meetingId"]>value');
  246. if (meetingIdValEl.length) {
  247. this.setMeetingId(meetingIdValEl.text());
  248. } else {
  249. logger.trace('No meeting ID from backend');
  250. }
  251. }, error => {
  252. GlobalOnErrorHandler.callErrorHandler(error);
  253. logger.error('Error getting room info: ', error);
  254. });
  255. }
  256. /**
  257. * Sets the meeting unique Id (received from the backend).
  258. *
  259. * @param {string} meetingId - The new meetings id.
  260. * @returns {void}
  261. */
  262. setMeetingId(meetingId) {
  263. if (this.meetingId !== meetingId) {
  264. if (this.meetingId) {
  265. logger.warn(`Meeting Id changed from:${this.meetingId} to:${meetingId}`);
  266. }
  267. this.meetingId = meetingId;
  268. // The name of the action is a little bit confusing but it seems this is the preferred name by the consumers
  269. // of the analytics events.
  270. Statistics.sendAnalytics(createConferenceEvent('joined', { meetingId }));
  271. }
  272. }
  273. /**
  274. *
  275. */
  276. createNonAnonymousRoom() {
  277. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  278. const getForm = $iq({ type: 'get',
  279. to: this.roomjid })
  280. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' })
  281. .c('x', { xmlns: 'jabber:x:data',
  282. type: 'submit' });
  283. const self = this;
  284. this.connection.sendIQ(getForm, form => {
  285. if (!$(form).find(
  286. '>query>x[xmlns="jabber:x:data"]'
  287. + '>field[var="muc#roomconfig_whois"]').length) {
  288. const errmsg = 'non-anonymous rooms not supported';
  289. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  290. logger.error(errmsg);
  291. return;
  292. }
  293. const formSubmit = $iq({ to: self.roomjid,
  294. type: 'set' })
  295. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' });
  296. formSubmit.c('x', { xmlns: 'jabber:x:data',
  297. type: 'submit' });
  298. formSubmit.c('field', { 'var': 'FORM_TYPE' })
  299. .c('value')
  300. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  301. formSubmit.c('field', { 'var': 'muc#roomconfig_whois' })
  302. .c('value').t('anyone').up().up();
  303. self.connection.sendIQ(formSubmit);
  304. }, error => {
  305. GlobalOnErrorHandler.callErrorHandler(error);
  306. logger.error('Error getting room configuration form: ', error);
  307. });
  308. }
  309. /**
  310. *
  311. * @param pres
  312. */
  313. onPresence(pres) {
  314. const from = pres.getAttribute('from');
  315. const member = {};
  316. const statusEl = pres.getElementsByTagName('status')[0];
  317. if (statusEl) {
  318. member.status = statusEl.textContent || '';
  319. }
  320. let hasStatusUpdate = false;
  321. let hasVersionUpdate = false;
  322. const xElement
  323. = pres.getElementsByTagNameNS(
  324. 'http://jabber.org/protocol/muc#user', 'x')[0];
  325. const mucUserItem
  326. = xElement && xElement.getElementsByTagName('item')[0];
  327. member.affiliation
  328. = mucUserItem && mucUserItem.getAttribute('affiliation');
  329. member.role = mucUserItem && mucUserItem.getAttribute('role');
  330. // Focus recognition
  331. const jid = mucUserItem && mucUserItem.getAttribute('jid');
  332. member.jid = jid;
  333. member.isFocus
  334. = jid && jid.indexOf(`${this.moderator.getFocusUserJid()}/`) === 0;
  335. member.isHiddenDomain
  336. = jid && jid.indexOf('@') > 0
  337. && this.options.hiddenDomain
  338. === jid.substring(jid.indexOf('@') + 1, jid.indexOf('/'));
  339. this.eventEmitter.emit(XMPPEvents.PRESENCE_RECEIVED, {
  340. fromHiddenDomain: member.isHiddenDomain,
  341. presence: pres
  342. });
  343. const xEl = pres.querySelector('x');
  344. if (xEl) {
  345. xEl.remove();
  346. }
  347. const nodes = [];
  348. parser.packet2JSON(pres, nodes);
  349. this.lastPresences[from] = nodes;
  350. // process nodes to extract data needed for MUC_JOINED and
  351. // MUC_MEMBER_JOINED events
  352. const extractIdentityInformation = node => {
  353. const identity = {};
  354. const userInfo = node.children.find(c => c.tagName === 'user');
  355. if (userInfo) {
  356. identity.user = {};
  357. for (const tag of [ 'id', 'name', 'avatar' ]) {
  358. const child
  359. = userInfo.children.find(c => c.tagName === tag);
  360. if (child) {
  361. identity.user[tag] = child.value;
  362. }
  363. }
  364. }
  365. const groupInfo = node.children.find(c => c.tagName === 'group');
  366. if (groupInfo) {
  367. identity.group = groupInfo.value;
  368. }
  369. return identity;
  370. };
  371. for (let i = 0; i < nodes.length; i++) {
  372. const node = nodes[i];
  373. switch (node.tagName) {
  374. case 'bot': {
  375. const { attributes } = node;
  376. if (!attributes) {
  377. break;
  378. }
  379. const { type } = attributes;
  380. member.botType = type;
  381. break;
  382. }
  383. case 'nick':
  384. member.nick = node.value;
  385. break;
  386. case 'userId':
  387. member.id = node.value;
  388. break;
  389. case 'stats-id':
  390. member.statsID = node.value;
  391. break;
  392. case 'identity':
  393. member.identity = extractIdentityInformation(node);
  394. break;
  395. case 'stat': {
  396. const { attributes } = node;
  397. if (!attributes) {
  398. break;
  399. }
  400. const { name } = attributes;
  401. if (name === 'version') {
  402. member.version = attributes.value;
  403. }
  404. break;
  405. }
  406. }
  407. }
  408. if (from === this.myroomjid) {
  409. const newRole
  410. = member.affiliation === 'owner' ? member.role : 'none';
  411. if (this.role !== newRole) {
  412. this.role = newRole;
  413. this.eventEmitter.emit(
  414. XMPPEvents.LOCAL_ROLE_CHANGED,
  415. this.role);
  416. }
  417. if (!this.joined) {
  418. this.joined = true;
  419. const now = this.connectionTimes['muc.joined']
  420. = window.performance.now();
  421. logger.log('(TIME) MUC joined:\t', now);
  422. // set correct initial state of locked
  423. if (this.password) {
  424. this.locked = true;
  425. }
  426. // Re-send presence in case any presence updates were added,
  427. // but blocked from sending, during the join process.
  428. this.sendPresence();
  429. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  430. // Now let's check the disco-info to retrieve the
  431. // meeting Id if any
  432. this.discoRoomInfo();
  433. }
  434. } else if (jid === undefined) {
  435. logger.info('Ignoring member with undefined JID');
  436. } else if (this.members[from] === undefined) {
  437. // new participant
  438. this.members[from] = member;
  439. logger.log('entered', from, member);
  440. hasStatusUpdate = member.status !== undefined;
  441. hasVersionUpdate = member.version !== undefined;
  442. if (member.isFocus) {
  443. this._initFocus(from, jid);
  444. } else {
  445. // identity is being added to member joined, so external
  446. // services can be notified for that (currently identity is
  447. // not used inside library)
  448. this.eventEmitter.emit(
  449. XMPPEvents.MUC_MEMBER_JOINED,
  450. from,
  451. member.nick,
  452. member.role,
  453. member.isHiddenDomain,
  454. member.statsID,
  455. member.status,
  456. member.identity,
  457. member.botType);
  458. // we are reporting the status with the join
  459. // so we do not want a second event about status update
  460. hasStatusUpdate = false;
  461. }
  462. } else {
  463. // Presence update for existing participant
  464. // Watch role change:
  465. const memberOfThis = this.members[from];
  466. if (memberOfThis.role !== member.role) {
  467. memberOfThis.role = member.role;
  468. this.eventEmitter.emit(
  469. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  470. }
  471. // fire event that botType had changed
  472. if (memberOfThis.botType !== member.botType) {
  473. memberOfThis.botType = member.botType;
  474. this.eventEmitter.emit(
  475. XMPPEvents.MUC_MEMBER_BOT_TYPE_CHANGED,
  476. from,
  477. member.botType);
  478. }
  479. if (member.isFocus) {
  480. // From time to time first few presences of the focus are not
  481. // containing it's jid. That way we can mark later the focus
  482. // member instead of not marking it at all and not starting the
  483. // conference.
  484. // FIXME: Maybe there is a better way to handle this issue. It
  485. // seems there is some period of time in prosody that the
  486. // configuration form is received but not applied. And if any
  487. // participant joins during that period of time the first
  488. // presence from the focus won't contain
  489. // <item jid="focus..." />.
  490. memberOfThis.isFocus = true;
  491. this._initFocus(from, jid);
  492. }
  493. // store the new display name
  494. if (member.displayName) {
  495. memberOfThis.displayName = member.displayName;
  496. }
  497. // update stored status message to be able to detect changes
  498. if (memberOfThis.status !== member.status) {
  499. hasStatusUpdate = true;
  500. memberOfThis.status = member.status;
  501. }
  502. if (memberOfThis.version !== member.version) {
  503. hasVersionUpdate = true;
  504. memberOfThis.version = member.version;
  505. }
  506. }
  507. // after we had fired member or room joined events, lets fire events
  508. // for the rest info we got in presence
  509. for (let i = 0; i < nodes.length; i++) {
  510. const node = nodes[i];
  511. switch (node.tagName) {
  512. case 'nick':
  513. if (!member.isFocus) {
  514. const displayName
  515. = this.xmpp.options.displayJids
  516. ? Strophe.getResourceFromJid(from)
  517. : member.nick;
  518. this.eventEmitter.emit(
  519. XMPPEvents.DISPLAY_NAME_CHANGED,
  520. from,
  521. displayName);
  522. }
  523. break;
  524. case 'bridgeNotAvailable':
  525. if (member.isFocus && !this.noBridgeAvailable) {
  526. this.noBridgeAvailable = true;
  527. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  528. }
  529. break;
  530. case 'conference-properties':
  531. if (member.isFocus) {
  532. const properties = {};
  533. for (let j = 0; j < node.children.length; j++) {
  534. const { attributes } = node.children[j];
  535. if (attributes && attributes.key) {
  536. properties[attributes.key] = attributes.value;
  537. }
  538. }
  539. this.eventEmitter.emit(
  540. XMPPEvents.CONFERENCE_PROPERTIES_CHANGED, properties);
  541. }
  542. break;
  543. case 'transcription-status': {
  544. const { attributes } = node;
  545. if (!attributes) {
  546. break;
  547. }
  548. const { status } = attributes;
  549. if (status && status !== this.transcriptionStatus) {
  550. this.transcriptionStatus = status;
  551. this.eventEmitter.emit(
  552. XMPPEvents.TRANSCRIPTION_STATUS_CHANGED,
  553. status
  554. );
  555. }
  556. break;
  557. }
  558. case 'call-control': {
  559. const att = node.attributes;
  560. if (!att) {
  561. break;
  562. }
  563. this.phoneNumber = att.phone || null;
  564. this.phonePin = att.pin || null;
  565. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  566. break;
  567. }
  568. default:
  569. this.processNode(node, from);
  570. }
  571. }
  572. // Trigger status message update if necessary
  573. if (hasStatusUpdate) {
  574. this.eventEmitter.emit(
  575. XMPPEvents.PRESENCE_STATUS,
  576. from,
  577. member.status);
  578. }
  579. if (hasVersionUpdate) {
  580. logger.info(`Received version for ${jid}: ${member.version}`);
  581. }
  582. }
  583. /**
  584. * Initialize some properties when the focus participant is verified.
  585. * @param from jid of the focus
  586. * @param mucJid the jid of the focus in the muc
  587. */
  588. _initFocus(from, mucJid) {
  589. this.focusMucJid = from;
  590. logger.info(`Ignore focus: ${from}, real JID: ${mucJid}`);
  591. }
  592. /**
  593. * Sets the special listener to be used for "command"s whose name starts
  594. * with "jitsi_participant_".
  595. */
  596. setParticipantPropertyListener(listener) {
  597. this.participantPropertyListener = listener;
  598. }
  599. /**
  600. *
  601. * @param node
  602. * @param from
  603. */
  604. processNode(node, from) {
  605. // make sure we catch all errors coming from any handler
  606. // otherwise we can remove the presence handler from strophe
  607. try {
  608. let tagHandlers = this.presHandlers[node.tagName];
  609. if (node.tagName.startsWith('jitsi_participant_')) {
  610. tagHandlers = [ this.participantPropertyListener ];
  611. }
  612. if (tagHandlers) {
  613. tagHandlers.forEach(handler => {
  614. handler(node, Strophe.getResourceFromJid(from), from);
  615. });
  616. }
  617. } catch (e) {
  618. GlobalOnErrorHandler.callErrorHandler(e);
  619. logger.error(`Error processing:${node.tagName} node.`, e);
  620. }
  621. }
  622. /**
  623. * Send text message to the other participants in the conference
  624. * @param message
  625. * @param elementName
  626. * @param nickname
  627. */
  628. sendMessage(message, elementName, nickname) {
  629. const msg = $msg({ to: this.roomjid,
  630. type: 'groupchat' });
  631. // We are adding the message in a packet extension. If this element
  632. // is different from 'body', we add a custom namespace.
  633. // e.g. for 'json-message' extension of message stanza.
  634. if (elementName === 'body') {
  635. msg.c(elementName, message).up();
  636. } else {
  637. msg.c(elementName, { xmlns: 'http://jitsi.org/jitmeet' }, message)
  638. .up();
  639. }
  640. if (nickname) {
  641. msg.c('nick', { xmlns: 'http://jabber.org/protocol/nick' })
  642. .t(nickname)
  643. .up()
  644. .up();
  645. }
  646. this.connection.send(msg);
  647. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, message);
  648. }
  649. /* eslint-disable max-params */
  650. /**
  651. * Send private text message to another participant of the conference
  652. * @param id id/muc resource of the receiver
  653. * @param message
  654. * @param elementName
  655. * @param nickname
  656. */
  657. sendPrivateMessage(id, message, elementName, nickname) {
  658. const msg = $msg({ to: `${this.roomjid}/${id}`,
  659. type: 'chat' });
  660. // We are adding the message in packet. If this element is different
  661. // from 'body', we add our custom namespace for the same.
  662. // e.g. for 'json-message' message extension.
  663. if (elementName === 'body') {
  664. msg.c(elementName, message).up();
  665. } else {
  666. msg.c(elementName, { xmlns: 'http://jitsi.org/jitmeet' }, message)
  667. .up();
  668. }
  669. if (nickname) {
  670. msg.c('nick', { xmlns: 'http://jabber.org/protocol/nick' })
  671. .t(nickname)
  672. .up()
  673. .up();
  674. }
  675. this.connection.send(msg);
  676. this.eventEmitter.emit(
  677. XMPPEvents.SENDING_PRIVATE_CHAT_MESSAGE, message);
  678. }
  679. /* eslint-enable max-params */
  680. /**
  681. *
  682. * @param subject
  683. */
  684. setSubject(subject) {
  685. const msg = $msg({ to: this.roomjid,
  686. type: 'groupchat' });
  687. msg.c('subject', subject);
  688. this.connection.send(msg);
  689. }
  690. /**
  691. * Called when participant leaves.
  692. * @param jid the jid of the participant that leaves
  693. * @param skipEvents optional params to skip any events, including check
  694. * whether this is the focus that left
  695. */
  696. onParticipantLeft(jid, skipEvents) {
  697. delete this.lastPresences[jid];
  698. if (skipEvents) {
  699. return;
  700. }
  701. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  702. this.moderator.onMucMemberLeft(jid);
  703. }
  704. /**
  705. *
  706. * @param pres
  707. * @param from
  708. */
  709. onPresenceUnavailable(pres, from) {
  710. // ignore presence
  711. if ($(pres).find('>ignore[xmlns="http://jitsi.org/jitmeet/"]').length) {
  712. return true;
  713. }
  714. // room destroyed ?
  715. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]'
  716. + '>destroy').length) {
  717. let reason;
  718. const reasonSelect
  719. = $(pres).find(
  720. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  721. + '>destroy>reason');
  722. if (reasonSelect.length) {
  723. reason = reasonSelect.text();
  724. }
  725. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  726. this.connection.emuc.doLeave(this.roomjid);
  727. return true;
  728. }
  729. // Status code 110 indicates that this notification is "self-presence".
  730. const isSelfPresence
  731. = $(pres)
  732. .find(
  733. '>x[xmlns="http://jabber.org/protocol/muc#user"]>'
  734. + 'status[code="110"]')
  735. .length;
  736. const isKick
  737. = $(pres)
  738. .find(
  739. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  740. + '>status[code="307"]')
  741. .length;
  742. const membersKeys = Object.keys(this.members);
  743. if (isKick) {
  744. const actorSelect
  745. = $(pres)
  746. .find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item>actor');
  747. let actorNick;
  748. if (actorSelect.length) {
  749. actorNick = actorSelect.attr('nick');
  750. }
  751. // if no member is found this is the case we had kicked someone
  752. // and we are not in the list of members
  753. if (membersKeys.find(jid => Strophe.getResourceFromJid(jid) === actorNick)) {
  754. // we first fire the kicked so we can show the participant
  755. // who kicked, before notifying that participant left
  756. // we fire kicked for us and for any participant kicked
  757. this.eventEmitter.emit(
  758. XMPPEvents.KICKED,
  759. isSelfPresence,
  760. actorNick,
  761. Strophe.getResourceFromJid(from));
  762. }
  763. }
  764. if (!isSelfPresence) {
  765. delete this.members[from];
  766. this.onParticipantLeft(from, false);
  767. } else if (membersKeys.length > 0) {
  768. // If the status code is 110 this means we're leaving and we would
  769. // like to remove everyone else from our view, so we trigger the
  770. // event.
  771. membersKeys.forEach(jid => {
  772. const member = this.members[jid];
  773. delete this.members[jid];
  774. this.onParticipantLeft(jid, member.isFocus);
  775. });
  776. this.connection.emuc.doLeave(this.roomjid);
  777. // we fire muc_left only if this is not a kick,
  778. // kick has both statuses 110 and 307.
  779. if (!isKick) {
  780. this.eventEmitter.emit(XMPPEvents.MUC_LEFT);
  781. }
  782. }
  783. }
  784. /**
  785. *
  786. * @param msg
  787. * @param from
  788. */
  789. onMessage(msg, from) {
  790. const nick
  791. = $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  792. .text()
  793. || Strophe.getResourceFromJid(from);
  794. const type = msg.getAttribute('type');
  795. if (type === 'error') {
  796. const errorMsg = $(msg).find('>error>text').text();
  797. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED, errorMsg);
  798. return true;
  799. }
  800. const txt = $(msg).find('>body').text();
  801. const subject = $(msg).find('>subject');
  802. if (subject.length) {
  803. const subjectText = subject.text();
  804. if (subjectText || subjectText === '') {
  805. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  806. logger.log(`Subject is changed to ${subjectText}`);
  807. }
  808. }
  809. // xep-0203 delay
  810. let stamp = $(msg).find('>delay').attr('stamp');
  811. if (!stamp) {
  812. // or xep-0091 delay, UTC timestamp
  813. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  814. if (stamp) {
  815. // the format is CCYYMMDDThh:mm:ss
  816. const dateParts
  817. = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  818. stamp = `${dateParts[1]}-${dateParts[2]}-${dateParts[3]}Z`;
  819. }
  820. }
  821. if (from === this.roomjid
  822. && $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="104"]').length) {
  823. this.discoRoomInfo();
  824. }
  825. const jsonMessage = $(msg).find('>json-message').text();
  826. const parsedJson = this.xmpp.tryParseJSONAndVerify(jsonMessage);
  827. // We emit this event if the message is a valid json, and is not
  828. // delivered after a delay, i.e. stamp is undefined.
  829. // e.g. - subtitles should not be displayed if delayed.
  830. if (parsedJson && stamp === undefined) {
  831. this.eventEmitter.emit(XMPPEvents.JSON_MESSAGE_RECEIVED,
  832. from, parsedJson);
  833. return;
  834. }
  835. if (txt) {
  836. if (type === 'chat') {
  837. this.eventEmitter.emit(XMPPEvents.PRIVATE_MESSAGE_RECEIVED,
  838. from, nick, txt, this.myroomjid, stamp);
  839. } else if (type === 'groupchat') {
  840. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  841. from, nick, txt, this.myroomjid, stamp);
  842. }
  843. }
  844. }
  845. /**
  846. *
  847. * @param pres
  848. * @param from
  849. */
  850. onPresenceError(pres, from) {
  851. if ($(pres)
  852. .find(
  853. '>error[type="auth"]'
  854. + '>not-authorized['
  855. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  856. .length) {
  857. logger.log('on password required', from);
  858. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  859. } else if ($(pres)
  860. .find(
  861. '>error[type="cancel"]'
  862. + '>not-allowed['
  863. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  864. .length) {
  865. const toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  866. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  867. // enter the room by replying with 'not-authorized'. This would
  868. // result in reconnection from authorized domain.
  869. // We're either missing Jicofo/Prosody config for anonymous
  870. // domains or something is wrong.
  871. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR);
  872. } else {
  873. logger.warn('onPresError ', pres);
  874. this.eventEmitter.emit(
  875. XMPPEvents.ROOM_CONNECT_NOT_ALLOWED_ERROR);
  876. }
  877. } else if ($(pres).find('>error>service-unavailable').length) {
  878. logger.warn('Maximum users limit for the room has been reached',
  879. pres);
  880. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR);
  881. } else {
  882. logger.warn('onPresError ', pres);
  883. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR);
  884. }
  885. }
  886. /**
  887. *
  888. * @param jid
  889. */
  890. kick(jid) {
  891. const kickIQ = $iq({ to: this.roomjid,
  892. type: 'set' })
  893. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  894. .c('item', { nick: Strophe.getResourceFromJid(jid),
  895. role: 'none' })
  896. .c('reason').t('You have been kicked.').up().up().up();
  897. this.connection.sendIQ(
  898. kickIQ,
  899. result => logger.log('Kick participant with jid: ', jid, result),
  900. error => logger.log('Kick participant error: ', error));
  901. }
  902. /* eslint-disable max-params */
  903. /**
  904. *
  905. * @param key
  906. * @param onSuccess
  907. * @param onError
  908. * @param onNotSupported
  909. */
  910. lockRoom(key, onSuccess, onError, onNotSupported) {
  911. // http://xmpp.org/extensions/xep-0045.html#roomconfig
  912. this.connection.sendIQ(
  913. $iq({
  914. to: this.roomjid,
  915. type: 'get'
  916. })
  917. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  918. res => {
  919. if ($(res)
  920. .find(
  921. '>query>x[xmlns="jabber:x:data"]'
  922. + '>field[var="muc#roomconfig_roomsecret"]')
  923. .length) {
  924. const formsubmit
  925. = $iq({
  926. to: this.roomjid,
  927. type: 'set'
  928. })
  929. .c('query', {
  930. xmlns: 'http://jabber.org/protocol/muc#owner'
  931. });
  932. formsubmit.c('x', {
  933. xmlns: 'jabber:x:data',
  934. type: 'submit'
  935. });
  936. formsubmit
  937. .c('field', { 'var': 'FORM_TYPE' })
  938. .c('value')
  939. .t('http://jabber.org/protocol/muc#roomconfig')
  940. .up()
  941. .up();
  942. formsubmit
  943. .c('field', { 'var': 'muc#roomconfig_roomsecret' })
  944. .c('value')
  945. .t(key)
  946. .up()
  947. .up();
  948. // Fixes a bug in prosody 0.9.+
  949. // https://prosody.im/issues/issue/373
  950. formsubmit
  951. .c('field', { 'var': 'muc#roomconfig_whois' })
  952. .c('value')
  953. .t('anyone')
  954. .up()
  955. .up();
  956. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  957. this.connection.sendIQ(formsubmit, onSuccess, onError);
  958. } else {
  959. onNotSupported();
  960. }
  961. },
  962. onError);
  963. }
  964. /* eslint-enable max-params */
  965. /**
  966. *
  967. * @param key
  968. * @param values
  969. */
  970. addToPresence(key, values) {
  971. values.tagName = key;
  972. this.removeFromPresence(key);
  973. this.presMap.nodes.push(values);
  974. }
  975. /**
  976. * Retreives a value from the presence map.
  977. *
  978. * @param {string} key - The key to find the value for.
  979. * @returns {Object?}
  980. */
  981. getFromPresence(key) {
  982. return this.presMap.nodes.find(node => key === node.tagName);
  983. }
  984. /**
  985. *
  986. * @param key
  987. */
  988. removeFromPresence(key) {
  989. const nodes = this.presMap.nodes.filter(node => key !== node.tagName);
  990. this.presMap.nodes = nodes;
  991. }
  992. /**
  993. *
  994. * @param name
  995. * @param handler
  996. */
  997. addPresenceListener(name, handler) {
  998. if (typeof handler !== 'function') {
  999. throw new Error('"handler" is not a function');
  1000. }
  1001. let tagHandlers = this.presHandlers[name];
  1002. if (!tagHandlers) {
  1003. this.presHandlers[name] = tagHandlers = [];
  1004. }
  1005. if (tagHandlers.indexOf(handler) === -1) {
  1006. tagHandlers.push(handler);
  1007. } else {
  1008. logger.warn(
  1009. `Trying to add the same handler more than once for: ${name}`);
  1010. }
  1011. }
  1012. /**
  1013. *
  1014. * @param name
  1015. * @param handler
  1016. */
  1017. removePresenceListener(name, handler) {
  1018. const tagHandlers = this.presHandlers[name];
  1019. const handlerIdx = tagHandlers ? tagHandlers.indexOf(handler) : -1;
  1020. // eslint-disable-next-line no-negated-condition
  1021. if (handlerIdx !== -1) {
  1022. tagHandlers.splice(handlerIdx, 1);
  1023. } else {
  1024. logger.warn(`Handler for: ${name} was not registered`);
  1025. }
  1026. }
  1027. /**
  1028. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1029. * focus.
  1030. * @param mucJid the full MUC address of the user to be checked.
  1031. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus
  1032. * or <tt>false</tt> if is not. When given <tt>mucJid</tt> does not exist in
  1033. * the MUC then <tt>null</tt> is returned.
  1034. */
  1035. isFocus(mucJid) {
  1036. const member = this.members[mucJid];
  1037. if (member) {
  1038. return member.isFocus;
  1039. }
  1040. return null;
  1041. }
  1042. /**
  1043. *
  1044. */
  1045. isModerator() {
  1046. return this.role === 'moderator';
  1047. }
  1048. /**
  1049. *
  1050. * @param peerJid
  1051. */
  1052. getMemberRole(peerJid) {
  1053. if (this.members[peerJid]) {
  1054. return this.members[peerJid].role;
  1055. }
  1056. return null;
  1057. }
  1058. /**
  1059. *
  1060. * @param mute
  1061. * @param callback
  1062. */
  1063. setVideoMute(mute, callback) {
  1064. this.sendVideoInfoPresence(mute);
  1065. if (callback) {
  1066. callback(mute);
  1067. }
  1068. }
  1069. /**
  1070. *
  1071. * @param mute
  1072. * @param callback
  1073. */
  1074. setAudioMute(mute, callback) {
  1075. return this.sendAudioInfoPresence(mute, callback);
  1076. }
  1077. /**
  1078. *
  1079. * @param mute
  1080. */
  1081. addAudioInfoToPresence(mute) {
  1082. this.removeFromPresence('audiomuted');
  1083. this.addToPresence(
  1084. 'audiomuted',
  1085. {
  1086. attributes: { 'xmlns': 'http://jitsi.org/jitmeet/audio' },
  1087. value: mute.toString()
  1088. });
  1089. }
  1090. /**
  1091. *
  1092. * @param mute
  1093. * @param callback
  1094. */
  1095. sendAudioInfoPresence(mute, callback) {
  1096. this.addAudioInfoToPresence(mute);
  1097. // FIXME resend presence on CONNECTED
  1098. this.sendPresence();
  1099. if (callback) {
  1100. callback();
  1101. }
  1102. }
  1103. /**
  1104. *
  1105. * @param mute
  1106. */
  1107. addVideoInfoToPresence(mute) {
  1108. this.removeFromPresence('videomuted');
  1109. this.addToPresence(
  1110. 'videomuted',
  1111. {
  1112. attributes: { 'xmlns': 'http://jitsi.org/jitmeet/video' },
  1113. value: mute.toString()
  1114. });
  1115. }
  1116. /**
  1117. *
  1118. * @param mute
  1119. */
  1120. sendVideoInfoPresence(mute) {
  1121. this.addVideoInfoToPresence(mute);
  1122. this.sendPresence();
  1123. }
  1124. /**
  1125. * Obtains the info about given media advertised in the MUC presence of
  1126. * the participant identified by the given endpoint JID.
  1127. * @param {string} endpointId the endpoint ID mapped to the participant
  1128. * which corresponds to MUC nickname.
  1129. * @param {MediaType} mediaType the type of the media for which presence
  1130. * info will be obtained.
  1131. * @return {PeerMediaInfo} presenceInfo an object with media presence
  1132. * info or <tt>null</tt> either if there is no presence available or if
  1133. * the media type given is invalid.
  1134. */
  1135. getMediaPresenceInfo(endpointId, mediaType) {
  1136. // Will figure out current muted status by looking up owner's presence
  1137. const pres = this.lastPresences[`${this.roomjid}/${endpointId}`];
  1138. if (!pres) {
  1139. // No presence available
  1140. return null;
  1141. }
  1142. const data = {
  1143. muted: false, // unmuted by default
  1144. videoType: undefined // no video type by default
  1145. };
  1146. let mutedNode = null;
  1147. if (mediaType === MediaType.AUDIO) {
  1148. mutedNode = filterNodeFromPresenceJSON(pres, 'audiomuted');
  1149. } else if (mediaType === MediaType.VIDEO) {
  1150. mutedNode = filterNodeFromPresenceJSON(pres, 'videomuted');
  1151. const videoTypeNode = filterNodeFromPresenceJSON(pres, 'videoType');
  1152. if (videoTypeNode.length > 0) {
  1153. data.videoType = videoTypeNode[0].value;
  1154. }
  1155. } else {
  1156. logger.error(`Unsupported media type: ${mediaType}`);
  1157. return null;
  1158. }
  1159. data.muted = mutedNode.length > 0 && mutedNode[0].value === 'true';
  1160. return data;
  1161. }
  1162. /**
  1163. * Returns true if the SIP calls are supported and false otherwise
  1164. */
  1165. isSIPCallingSupported() {
  1166. if (this.moderator) {
  1167. return this.moderator.isSipGatewayEnabled();
  1168. }
  1169. return false;
  1170. }
  1171. /**
  1172. * Dials a number.
  1173. * @param number the number
  1174. */
  1175. dial(number) {
  1176. return this.connection.rayo.dial(number, 'fromnumber',
  1177. Strophe.getBareJidFromJid(this.myroomjid), this.password,
  1178. this.focusMucJid);
  1179. }
  1180. /**
  1181. * Hangup an existing call
  1182. */
  1183. hangup() {
  1184. return this.connection.rayo.hangup();
  1185. }
  1186. /**
  1187. * Returns the phone number for joining the conference.
  1188. */
  1189. getPhoneNumber() {
  1190. return this.phoneNumber;
  1191. }
  1192. /**
  1193. * Returns the pin for joining the conference with phone.
  1194. */
  1195. getPhonePin() {
  1196. return this.phonePin;
  1197. }
  1198. /**
  1199. * Returns the meeting unique ID if any came from backend.
  1200. *
  1201. * @returns {string} - The meeting ID.
  1202. */
  1203. getMeetingId() {
  1204. return this.meetingId;
  1205. }
  1206. /**
  1207. * Mutes remote participant.
  1208. * @param jid of the participant
  1209. * @param mute
  1210. */
  1211. muteParticipant(jid, mute) {
  1212. logger.info('set mute', mute);
  1213. const iqToFocus = $iq(
  1214. { to: this.focusMucJid,
  1215. type: 'set' })
  1216. .c('mute', {
  1217. xmlns: 'http://jitsi.org/jitmeet/audio',
  1218. jid
  1219. })
  1220. .t(mute.toString())
  1221. .up();
  1222. this.connection.sendIQ(
  1223. iqToFocus,
  1224. result => logger.log('set mute', result),
  1225. error => logger.log('set mute error', error));
  1226. }
  1227. /**
  1228. * TODO: Document
  1229. * @param iq
  1230. */
  1231. onMute(iq) {
  1232. const from = iq.getAttribute('from');
  1233. if (from !== this.focusMucJid) {
  1234. logger.warn('Ignored mute from non focus peer');
  1235. return;
  1236. }
  1237. const mute = $(iq).find('mute');
  1238. if (mute.length && mute.text() === 'true') {
  1239. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, mute.attr('actor'));
  1240. } else {
  1241. // XXX Why do we support anything but muting? Why do we encode the
  1242. // value in the text of the element? Why do we use a separate XML
  1243. // namespace?
  1244. logger.warn('Ignoring a mute request which does not explicitly '
  1245. + 'specify a positive mute command.');
  1246. }
  1247. }
  1248. /**
  1249. * Leaves the room. Closes the jingle session.
  1250. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received
  1251. * less than 5s after sending presence unavailable. Otherwise the promise is
  1252. * rejected.
  1253. */
  1254. leave() {
  1255. return new Promise((resolve, reject) => {
  1256. const timeout = setTimeout(() => onMucLeft(true), 5000);
  1257. const eventEmitter = this.eventEmitter;
  1258. /**
  1259. *
  1260. * @param doReject
  1261. */
  1262. function onMucLeft(doReject = false) {
  1263. eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1264. clearTimeout(timeout);
  1265. if (doReject) {
  1266. // the timeout expired
  1267. reject(new Error('The timeout for the confirmation about '
  1268. + 'leaving the room expired.'));
  1269. } else {
  1270. resolve();
  1271. }
  1272. }
  1273. eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  1274. this.doLeave();
  1275. });
  1276. }
  1277. }
  1278. /* eslint-enable newline-per-chained-call */