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

ChatRoom.js 47KB

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