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.

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