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

ChatRoom.js 47KB

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