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

ChatRoom.js 69KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030
  1. import { safeJsonParse } from '@jitsi/js-utils/json';
  2. import { getLogger } from '@jitsi/logger';
  3. import $ from 'jquery';
  4. import { isEqual } from 'lodash-es';
  5. import { $iq, $msg, $pres, Strophe } from 'strophe.js';
  6. import { v4 as uuidv4 } from 'uuid';
  7. import { AUTH_ERROR_TYPES } from '../../JitsiConferenceErrors';
  8. import * as JitsiTranscriptionStatus from '../../JitsiTranscriptionStatus';
  9. import { MediaType } from '../../service/RTC/MediaType';
  10. import { VideoType } from '../../service/RTC/VideoType';
  11. import AuthenticationEvents from '../../service/authentication/AuthenticationEvents';
  12. import { XMPPEvents } from '../../service/xmpp/XMPPEvents';
  13. import Settings from '../settings/Settings';
  14. import EventEmitterForwarder from '../util/EventEmitterForwarder';
  15. import Listenable from '../util/Listenable';
  16. import { getJitterDelay } from '../util/Retry';
  17. import AVModeration from './AVModeration';
  18. import BreakoutRooms from './BreakoutRooms';
  19. import Lobby from './Lobby';
  20. import RoomMetadata from './RoomMetadata';
  21. import XmppConnection from './XmppConnection';
  22. import { FEATURE_TRANSCRIBER } from './xmpp';
  23. const logger = getLogger(__filename);
  24. /**
  25. * How long we're going to wait for IQ response, before timeout error is triggered.
  26. * @type {number}
  27. */
  28. const IQ_TIMEOUT = 10000;
  29. export const parser = {
  30. packet2JSON(xmlElement, nodes) {
  31. for (const child of Array.from(xmlElement.children)) {
  32. const node = {
  33. attributes: {},
  34. children: [],
  35. tagName: child.tagName
  36. };
  37. for (const attr of Array.from(child.attributes)) {
  38. node.attributes[attr.name] = attr.value;
  39. }
  40. const text = Strophe.getText(child);
  41. if (text) {
  42. // Using Strophe.getText will do work for traversing all direct
  43. // child text nodes but returns an escaped value, which is not
  44. // desirable at this point.
  45. node.value = Strophe.xmlunescape(text);
  46. }
  47. nodes.push(node);
  48. this.packet2JSON(child, node.children);
  49. }
  50. },
  51. json2packet(nodes, packet) {
  52. for (let i = 0; i < nodes.length; i++) {
  53. const node = nodes[i];
  54. if (node) {
  55. packet.c(node.tagName, node.attributes);
  56. if (node.value) {
  57. packet.t(node.value);
  58. }
  59. if (node.children) {
  60. this.json2packet(node.children, packet);
  61. }
  62. packet.up();
  63. }
  64. }
  65. // packet.up();
  66. }
  67. };
  68. /**
  69. * Returns array of JS objects from the presence JSON associated with the passed
  70. / nodeName
  71. * @param pres the presence JSON
  72. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  73. */
  74. export function filterNodeFromPresenceJSON(pres, nodeName) {
  75. const res = [];
  76. for (let i = 0; i < pres.length; i++) {
  77. if (pres[i].tagName === nodeName) {
  78. res.push(pres[i]);
  79. }
  80. }
  81. return res;
  82. }
  83. // XXX As ChatRoom constructs XMPP stanzas and Strophe is build around the idea
  84. // of chaining function calls, allow long function call chains.
  85. /* eslint-disable newline-per-chained-call */
  86. /**
  87. * Array of affiliations that are allowed in members only room.
  88. * @type {string[]}
  89. */
  90. const MEMBERS_AFFILIATIONS = [ 'owner', 'admin', 'member' ];
  91. /**
  92. * Process nodes to extract data needed for MUC_JOINED and MUC_MEMBER_JOINED events.
  93. *
  94. */
  95. function extractIdentityInformation(node, hiddenFromRecorderFeatureEnabled) {
  96. const identity = {};
  97. const userInfo = node.children.find(c => c.tagName === 'user');
  98. if (userInfo) {
  99. identity.user = {};
  100. const tags = [ 'id', 'name', 'avatar' ];
  101. if (hiddenFromRecorderFeatureEnabled) {
  102. tags.push('hidden-from-recorder');
  103. }
  104. for (const tag of tags) {
  105. const child
  106. = userInfo.children.find(c => c.tagName === tag);
  107. if (child) {
  108. identity.user[tag] = child.value;
  109. }
  110. }
  111. }
  112. const groupInfo = node.children.find(c => c.tagName === 'group');
  113. if (groupInfo) {
  114. identity.group = groupInfo.value;
  115. }
  116. return identity;
  117. }
  118. /**
  119. *
  120. */
  121. export default class ChatRoom extends Listenable {
  122. /* eslint-disable max-params */
  123. /**
  124. *
  125. * @param {XmppConnection} connection - The XMPP connection instance.
  126. * @param jid
  127. * @param password
  128. * @param XMPP
  129. * @param options
  130. * @param {boolean} options.disableFocus - when set to {@code false} will
  131. * not invite Jicofo into the room.
  132. * @param {boolean} options.disableDiscoInfo - when set to {@code false} will skip disco info.
  133. * This is intended to be used only for lobby rooms.
  134. * @param {boolean} options.enableLobby - when set to {@code false} will skip creating lobby room.
  135. * @param {boolean} options.hiddenFromRecorderFeatureEnabled - when set to {@code true} we will check identity tag
  136. * for node presence.
  137. */
  138. constructor(connection, jid, password, xmpp, options) {
  139. super();
  140. this.xmpp = xmpp;
  141. this.connection = connection;
  142. this.roomjid = Strophe.getBareJidFromJid(jid);
  143. this.myroomjid = jid;
  144. this.password = password;
  145. this.replaceParticipant = false;
  146. logger.info(`Joining MUC as ${this.myroomjid}`);
  147. this.members = {};
  148. this.presMap = {};
  149. this.presHandlers = {};
  150. this._removeConnListeners = [];
  151. this.joined = false;
  152. this.inProgressEmitted = false;
  153. this.role = null;
  154. this.focusMucJid = null;
  155. this.noBridgeAvailable = false;
  156. this.options = options || {};
  157. this.eventsForwarder = new EventEmitterForwarder(this.xmpp.moderator, this.eventEmitter);
  158. this.eventsForwarder.forward(AuthenticationEvents.IDENTITY_UPDATED, AuthenticationEvents.IDENTITY_UPDATED);
  159. this.eventsForwarder.forward(XMPPEvents.AUTHENTICATION_REQUIRED, XMPPEvents.AUTHENTICATION_REQUIRED);
  160. this.eventsForwarder.forward(XMPPEvents.FOCUS_DISCONNECTED, XMPPEvents.FOCUS_DISCONNECTED);
  161. this.eventsForwarder.forward(XMPPEvents.RESERVATION_ERROR, XMPPEvents.RESERVATION_ERROR);
  162. if (typeof this.options.enableLobby === 'undefined' || this.options.enableLobby) {
  163. this.lobby = new Lobby(this);
  164. }
  165. this.avModeration = new AVModeration(this);
  166. this.breakoutRooms = new BreakoutRooms(this);
  167. this.roomMetadata = new RoomMetadata(this);
  168. this.initPresenceMap(options);
  169. this.lastPresences = {};
  170. this.phoneNumber = null;
  171. this.phonePin = null;
  172. this.connectionTimes = {};
  173. this.participantPropertyListener = null;
  174. this.locked = false;
  175. this.transcriptionStatus = JitsiTranscriptionStatus.OFF;
  176. this.initialDiscoRoomInfoReceived = false;
  177. }
  178. /* eslint-enable max-params */
  179. /**
  180. *
  181. */
  182. initPresenceMap(options = {}) {
  183. this.presMap.to = this.myroomjid;
  184. this.presMap.xns = 'http://jabber.org/protocol/muc';
  185. this.presMap.nodes = [];
  186. if (options.statsId) {
  187. this.presMap.nodes.push({
  188. 'tagName': 'stats-id',
  189. 'value': options.statsId
  190. });
  191. }
  192. this.presenceUpdateTime = Date.now();
  193. }
  194. /**
  195. * Joins the chat room.
  196. * @param {string} password - Password to unlock room on joining.
  197. * @returns {Promise} - resolved when join completes. At the time of this
  198. * writing it's never rejected.
  199. */
  200. join(password, replaceParticipant) {
  201. this.password = password;
  202. this.replaceParticipant = replaceParticipant;
  203. return new Promise(resolve => {
  204. this.options.disableFocus
  205. && logger.info(`Conference focus disabled for ${this.roomjid}`);
  206. const preJoin
  207. = this.options.disableFocus
  208. ? Promise.resolve()
  209. .finally(() => {
  210. this.xmpp.connection._breakoutMovingToMain = undefined;
  211. })
  212. : this.xmpp.moderator.sendConferenceRequest(this.roomjid);
  213. preJoin.then(() => {
  214. this.sendPresence(true);
  215. this._removeConnListeners.push(
  216. this.connection.addCancellableListener(
  217. XmppConnection.Events.CONN_STATUS_CHANGED,
  218. this.onConnStatusChanged.bind(this))
  219. );
  220. resolve();
  221. })
  222. .catch(e => logger.trace('PreJoin rejected', e));
  223. });
  224. }
  225. /**
  226. *
  227. * @param fromJoin - Whether this is initial presence to join the room.
  228. */
  229. sendPresence(fromJoin) {
  230. const to = this.presMap.to;
  231. if (!this.connection || !this.connection.connected || !to || (!this.joined && !fromJoin)) {
  232. // Too early to send presence - not initialized
  233. return;
  234. }
  235. const pres = $pres({ to });
  236. // xep-0045 defines: "including in the initial presence stanza an empty
  237. // <x/> element qualified by the 'http://jabber.org/protocol/muc'
  238. // namespace" and subsequent presences should not include that or it can
  239. // be considered as joining, and server can send us the message history
  240. // for the room on every presence
  241. if (fromJoin) {
  242. if (this.replaceParticipant) {
  243. pres.c('flip_device').up();
  244. }
  245. pres.c('x', { xmlns: this.presMap.xns });
  246. if (this.password) {
  247. pres.c('password').t(this.password).up();
  248. }
  249. // send the machineId with the initial presence
  250. if (this.xmpp.moderator.targetUrl) {
  251. pres.c('billingid').t(Settings.machineId).up();
  252. }
  253. pres.up();
  254. }
  255. parser.json2packet(this.presMap.nodes, pres);
  256. // we store time we last synced presence state
  257. this.presenceSyncTime = Date.now();
  258. this.connection.send(pres);
  259. if (fromJoin) {
  260. // XXX We're pressed for time here because we're beginning a complex
  261. // and/or lengthy conference-establishment process which supposedly
  262. // involves multiple RTTs. We don't have the time to wait for
  263. // Strophe to decide to send our IQ.
  264. this.connection.flush();
  265. }
  266. }
  267. /**
  268. * Sends the presence unavailable, signaling the server
  269. * we want to leave the room.
  270. */
  271. doLeave(reason) {
  272. logger.log('do leave', this.myroomjid);
  273. const pres = $pres({
  274. to: this.myroomjid,
  275. type: 'unavailable'
  276. });
  277. if (reason) {
  278. pres.c('status').t(reason).up();
  279. }
  280. this.presMap.length = 0;
  281. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  282. // means that there may not be enough time to send the unavailable
  283. // presence. Switching Strophe to synchronous sending is not much of an
  284. // option because it may lead to a noticeable delay in navigating away
  285. // from the current location. As a compromise, we will try to increase
  286. // the chances of sending the unavailable presence within the short time
  287. // span that we have upon unloading by invoking flush() on the
  288. // connection. We flush() once before sending/queuing the unavailable
  289. // presence in order to attemtp to have the unavailable presence at the
  290. // top of the send queue. We flush() once more after sending/queuing the
  291. // unavailable presence in order to attempt to have it sent as soon as
  292. // possible.
  293. // FIXME do not use Strophe.Connection in the ChatRoom directly
  294. !this.connection.isUsingWebSocket && this.connection.flush();
  295. this.connection.send(pres);
  296. this.connection.flush();
  297. }
  298. /**
  299. *
  300. */
  301. discoRoomInfo() {
  302. // https://xmpp.org/extensions/xep-0045.html#disco-roominfo
  303. const getInfo
  304. = $iq({
  305. type: 'get',
  306. to: this.roomjid
  307. })
  308. .c('query', { xmlns: Strophe.NS.DISCO_INFO });
  309. this.connection.sendIQ(getInfo, result => {
  310. const locked
  311. = $(result).find('>query>feature[var="muc_passwordprotected"]')
  312. .length
  313. === 1;
  314. if (locked !== this.locked) {
  315. this.eventEmitter.emit(XMPPEvents.MUC_LOCK_CHANGED, locked);
  316. this.locked = locked;
  317. }
  318. const meetingIdValEl
  319. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_meetingId"]>value');
  320. if (meetingIdValEl.length) {
  321. this.setMeetingId(meetingIdValEl.text());
  322. } else {
  323. logger.warn('No meeting ID from backend');
  324. }
  325. const meetingCreatedTSValEl
  326. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_created_timestamp"]>value');
  327. if (meetingCreatedTSValEl.length) {
  328. this.eventEmitter.emit(XMPPEvents.CONFERENCE_TIMESTAMP_RECEIVED, meetingCreatedTSValEl.text());
  329. } else {
  330. logger.warn('No conference duration from backend');
  331. }
  332. const membersOnly = $(result).find('>query>feature[var="muc_membersonly"]').length === 1;
  333. const lobbyRoomField
  334. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_lobbyroom"]>value');
  335. if (this.lobby) {
  336. this.lobby.setLobbyRoomJid(lobbyRoomField && lobbyRoomField.length ? lobbyRoomField.text() : undefined);
  337. }
  338. const isBreakoutField
  339. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_isbreakout"]>value');
  340. const isBreakoutRoom = Boolean(isBreakoutField?.text());
  341. this.breakoutRooms._setIsBreakoutRoom(isBreakoutRoom);
  342. const breakoutMainRoomField
  343. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_breakout_main_room"]>value');
  344. if (breakoutMainRoomField?.length) {
  345. this.breakoutRooms._setMainRoomJid(breakoutMainRoomField.text());
  346. }
  347. if (membersOnly !== this.membersOnlyEnabled) {
  348. this.membersOnlyEnabled = membersOnly;
  349. this.eventEmitter.emit(XMPPEvents.MUC_MEMBERS_ONLY_CHANGED, membersOnly);
  350. }
  351. const visitorsSupported = $(result)
  352. .find('>query>x[type="result"]>field[var="muc#roominfo_visitorsEnabled"]>value').text() === '1';
  353. if (visitorsSupported !== this.visitorsSupported) {
  354. this.visitorsSupported = visitorsSupported;
  355. this.eventEmitter.emit(XMPPEvents.MUC_VISITORS_SUPPORTED_CHANGED, visitorsSupported);
  356. }
  357. const roomMetadataEl
  358. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_jitsimetadata"]>value');
  359. const roomMetadataText = roomMetadataEl?.text();
  360. if (roomMetadataText) {
  361. try {
  362. this.roomMetadata._handleMessages(safeJsonParse(roomMetadataText));
  363. } catch (e) {
  364. logger.warn('Failed to set room metadata', e);
  365. }
  366. }
  367. this.initialDiscoRoomInfoReceived = true;
  368. this.eventEmitter.emit(XMPPEvents.ROOM_DISCO_INFO_UPDATED);
  369. }, error => {
  370. logger.error('Error getting room info: ', error);
  371. this.eventEmitter.emit(XMPPEvents.ROOM_DISCO_INFO_FAILED, error);
  372. },
  373. IQ_TIMEOUT);
  374. }
  375. /**
  376. * Sets the meeting unique Id (received from the backend).
  377. *
  378. * @param {string} meetingId - The new meetings id.
  379. * @returns {void}
  380. */
  381. setMeetingId(meetingId) {
  382. if (this.meetingId !== meetingId) {
  383. if (this.meetingId) {
  384. logger.warn(`Meeting Id changed from:${this.meetingId} to:${meetingId}`);
  385. }
  386. this.meetingId = meetingId;
  387. this.eventEmitter.emit(XMPPEvents.MEETING_ID_SET, meetingId);
  388. }
  389. }
  390. /**
  391. *
  392. */
  393. createNonAnonymousRoom() {
  394. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  395. if (this.options.disableDiscoInfo) {
  396. return;
  397. }
  398. const getForm = $iq({ type: 'get',
  399. to: this.roomjid })
  400. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' })
  401. .c('x', { xmlns: 'jabber:x:data',
  402. type: 'submit' });
  403. this.connection.sendIQ(getForm, form => {
  404. if (!$(form).find(
  405. '>query>x[xmlns="jabber:x:data"]'
  406. + '>field[var="muc#roomconfig_whois"]').length) {
  407. logger.error('non-anonymous rooms not supported');
  408. return;
  409. }
  410. const formSubmit = $iq({ to: this.roomjid,
  411. type: 'set' })
  412. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' });
  413. formSubmit.c('x', { xmlns: 'jabber:x:data',
  414. type: 'submit' });
  415. formSubmit.c('field', { 'var': 'FORM_TYPE' })
  416. .c('value')
  417. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  418. formSubmit.c('field', { 'var': 'muc#roomconfig_whois' })
  419. .c('value').t('anyone').up().up();
  420. this.connection.sendIQ(formSubmit);
  421. }, error => {
  422. logger.error('Error getting room configuration form: ', error);
  423. });
  424. }
  425. /**
  426. * Handles Xmpp Connection status updates.
  427. *
  428. * @param {Strophe.Status} status - The Strophe connection status.
  429. */
  430. onConnStatusChanged(status) {
  431. // Send cached presence when the XMPP connection is re-established, only if needed
  432. if (status === XmppConnection.Status.CONNECTED && this.presenceUpdateTime > this.presenceSyncTime) {
  433. this.sendPresence();
  434. }
  435. }
  436. /**
  437. *
  438. * @param pres
  439. */
  440. onPresence(pres) {
  441. const from = pres.getAttribute('from');
  442. const member = {};
  443. const statusEl = pres.getElementsByTagName('status')[0];
  444. if (statusEl) {
  445. member.status = statusEl.textContent || '';
  446. }
  447. let hasStatusUpdate = false;
  448. let hasVersionUpdate = false;
  449. const xElement
  450. = pres.getElementsByTagNameNS(
  451. 'http://jabber.org/protocol/muc#user', 'x')[0];
  452. const mucUserItem
  453. = xElement && xElement.getElementsByTagName('item')[0];
  454. member.isReplaceParticipant
  455. = pres.getElementsByTagName('flip_device').length;
  456. member.affiliation
  457. = mucUserItem && mucUserItem.getAttribute('affiliation');
  458. member.role = mucUserItem && mucUserItem.getAttribute('role');
  459. // Focus recognition
  460. const jid = mucUserItem && mucUserItem.getAttribute('jid');
  461. member.jid = jid;
  462. member.isFocus = this.xmpp.moderator.isFocusJid(jid);
  463. member.isHiddenDomain
  464. = jid && jid.indexOf('@') > 0
  465. && this.options.hiddenDomain
  466. === jid.substring(jid.indexOf('@') + 1, jid.indexOf('/'));
  467. this.eventEmitter.emit(XMPPEvents.PRESENCE_RECEIVED, {
  468. fromHiddenDomain: member.isHiddenDomain,
  469. presence: pres
  470. });
  471. const xEl = pres.querySelector('x');
  472. if (xEl) {
  473. xEl.remove();
  474. }
  475. const nodes = [];
  476. parser.packet2JSON(pres, nodes);
  477. this.lastPresences[from] = nodes;
  478. for (let i = 0; i < nodes.length; i++) {
  479. const node = nodes[i];
  480. switch (node.tagName) {
  481. case 'bot': {
  482. const { attributes } = node;
  483. if (!attributes) {
  484. break;
  485. }
  486. const { type } = attributes;
  487. member.botType = type;
  488. break;
  489. }
  490. case 'nick':
  491. member.nick = node.value;
  492. break;
  493. case 'silent':
  494. member.isSilent = node.value;
  495. break;
  496. case 'userId':
  497. member.id = node.value;
  498. break;
  499. case 'stats-id':
  500. member.statsID = node.value;
  501. break;
  502. case 'identity':
  503. member.identity = extractIdentityInformation(node, this.options.hiddenFromRecorderFeatureEnabled);
  504. break;
  505. case 'features': {
  506. member.features = this._extractFeatures(node);
  507. break;
  508. }
  509. case 'stat': {
  510. const { attributes } = node;
  511. if (!attributes) {
  512. break;
  513. }
  514. const { name } = attributes;
  515. if (name === 'version') {
  516. member.version = attributes.value;
  517. }
  518. break;
  519. }
  520. }
  521. }
  522. if (!this.joined && !this.inProgressEmitted) {
  523. const now = this.connectionTimes['muc.join.started'] = window.performance.now();
  524. logger.log('(TIME) MUC join started:\t', now);
  525. this.eventEmitter.emit(XMPPEvents.MUC_JOIN_IN_PROGRESS);
  526. this.inProgressEmitted = true;
  527. }
  528. if (from === this.myroomjid) {
  529. const newRole
  530. = member.affiliation === 'owner' ? member.role : 'none';
  531. if (this.role !== newRole) {
  532. this.role = newRole;
  533. this.eventEmitter.emit(
  534. XMPPEvents.LOCAL_ROLE_CHANGED,
  535. this.role);
  536. }
  537. if (!this.joined) {
  538. this.joined = true;
  539. const now = this.connectionTimes['muc.joined']
  540. = window.performance.now();
  541. logger.log('(TIME) MUC joined:\t', now);
  542. // set correct initial state of locked
  543. if (this.password) {
  544. this.locked = true;
  545. }
  546. // Re-send presence in case any presence updates were added,
  547. // but blocked from sending, during the join process.
  548. // send the presence only if there was a modification after we had synced it
  549. if (this.presenceUpdateTime >= this.presenceSyncTime) {
  550. this.sendPresence();
  551. }
  552. // we need to reset it because of breakout rooms which will reuse connection but will invite jicofo
  553. this.xmpp.moderator.conferenceRequestSent = false;
  554. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  555. // Now let's check the disco-info to retrieve the
  556. // meeting Id if any
  557. !this.options.disableDiscoInfo && this.discoRoomInfo();
  558. }
  559. } else if (jid === undefined) {
  560. logger.info('Ignoring member with undefined JID');
  561. } else if (this.members[from] === undefined) {
  562. // new participant
  563. this.members[from] = member;
  564. logger.log('entered', from, member);
  565. hasStatusUpdate = member.status !== undefined;
  566. hasVersionUpdate = member.version !== undefined;
  567. if (member.isFocus) {
  568. this._initFocus(from, member.features);
  569. } else {
  570. // identity is being added to member joined, so external
  571. // services can be notified for that (currently identity is
  572. // not used inside library)
  573. this.eventEmitter.emit(
  574. XMPPEvents.MUC_MEMBER_JOINED,
  575. from,
  576. member.nick,
  577. member.role,
  578. member.isHiddenDomain,
  579. member.statsID,
  580. member.status,
  581. member.identity,
  582. member.botType,
  583. member.jid,
  584. member.features,
  585. member.isReplaceParticipant,
  586. member.isSilent);
  587. // we are reporting the status with the join
  588. // so we do not want a second event about status update
  589. hasStatusUpdate = false;
  590. }
  591. } else {
  592. // Presence update for existing participant
  593. // Watch role change:
  594. const memberOfThis = this.members[from];
  595. if (memberOfThis.role !== member.role) {
  596. memberOfThis.role = member.role;
  597. this.eventEmitter.emit(
  598. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  599. }
  600. // affiliation changed
  601. if (memberOfThis.affiliation !== member.affiliation) {
  602. memberOfThis.affiliation = member.affiliation;
  603. }
  604. // fire event that botType had changed
  605. if (memberOfThis.botType !== member.botType) {
  606. memberOfThis.botType = member.botType;
  607. this.eventEmitter.emit(
  608. XMPPEvents.MUC_MEMBER_BOT_TYPE_CHANGED,
  609. from,
  610. member.botType);
  611. }
  612. if (member.isFocus) {
  613. // From time to time first few presences of the focus are not
  614. // containing it's jid. That way we can mark later the focus
  615. // member instead of not marking it at all and not starting the
  616. // conference.
  617. // FIXME: Maybe there is a better way to handle this issue. It
  618. // seems there is some period of time in prosody that the
  619. // configuration form is received but not applied. And if any
  620. // participant joins during that period of time the first
  621. // presence from the focus won't contain
  622. // <item jid="focus..." />.
  623. // By default we are disabling the waiting for form submission in order to use the room
  624. // and we had enabled by default that jids are public in the room ,
  625. // so this case should not happen, if public jid is turned off we will receive the jid
  626. // when we become moderator in the room
  627. memberOfThis.isFocus = true;
  628. this._initFocus(from, member.features);
  629. }
  630. // store the new display name
  631. if (member.displayName) {
  632. memberOfThis.displayName = member.displayName;
  633. }
  634. // join without audio
  635. if (member.isSilent) {
  636. memberOfThis.isSilent = member.isSilent;
  637. }
  638. // update stored status message to be able to detect changes
  639. if (memberOfThis.status !== member.status) {
  640. hasStatusUpdate = true;
  641. memberOfThis.status = member.status;
  642. }
  643. if (memberOfThis.version !== member.version) {
  644. hasVersionUpdate = true;
  645. memberOfThis.version = member.version;
  646. }
  647. if (!isEqual(memberOfThis.features, member.features)) {
  648. memberOfThis.features = member.features;
  649. this.eventEmitter.emit(XMPPEvents.PARTICIPANT_FEATURES_CHANGED, from, member.features);
  650. }
  651. }
  652. // after we had fired member or room joined events, lets fire events
  653. // for the rest info we got in presence
  654. for (let i = 0; i < nodes.length; i++) {
  655. const node = nodes[i];
  656. switch (node.tagName) {
  657. case 'nick':
  658. if (!member.isFocus) {
  659. const displayName
  660. = this.xmpp.options.displayJids
  661. ? Strophe.getResourceFromJid(from)
  662. : member.nick;
  663. this.eventEmitter.emit(
  664. XMPPEvents.DISPLAY_NAME_CHANGED,
  665. from,
  666. displayName);
  667. }
  668. break;
  669. case 'silent':
  670. this.eventEmitter.emit(
  671. XMPPEvents.SILENT_STATUS_CHANGED,
  672. from,
  673. member.isSilent);
  674. break;
  675. case 'bridgeNotAvailable':
  676. if (member.isFocus && !this.noBridgeAvailable) {
  677. this.noBridgeAvailable = true;
  678. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  679. }
  680. break;
  681. case 'conference-properties':
  682. if (member.isFocus) {
  683. const properties = {};
  684. for (let j = 0; j < node.children.length; j++) {
  685. const { attributes } = node.children[j];
  686. if (attributes && attributes.key) {
  687. properties[attributes.key] = attributes.value;
  688. }
  689. }
  690. this.eventEmitter.emit(XMPPEvents.CONFERENCE_PROPERTIES_CHANGED, properties);
  691. }
  692. break;
  693. case 'transcription-status': {
  694. const { attributes } = node;
  695. if (!attributes) {
  696. break;
  697. }
  698. const { status } = attributes;
  699. if (status && status !== this.transcriptionStatus
  700. && member.isHiddenDomain && member.features.has(FEATURE_TRANSCRIBER)) {
  701. this.transcriptionStatus = status;
  702. this.eventEmitter.emit(
  703. XMPPEvents.TRANSCRIPTION_STATUS_CHANGED,
  704. status,
  705. Strophe.getResourceFromJid(from)
  706. );
  707. }
  708. break;
  709. }
  710. case 'call-control': {
  711. const att = node.attributes;
  712. if (!att) {
  713. break;
  714. }
  715. this.phoneNumber = att.phone || null;
  716. this.phonePin = att.pin || null;
  717. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  718. break;
  719. }
  720. default:
  721. this.processNode(node, from);
  722. }
  723. }
  724. // Trigger status message update if necessary
  725. if (hasStatusUpdate) {
  726. this.eventEmitter.emit(
  727. XMPPEvents.PRESENCE_STATUS,
  728. from,
  729. member.status);
  730. }
  731. if (hasVersionUpdate) {
  732. logger.info(`Received version for ${jid}: ${member.version}`);
  733. }
  734. }
  735. /**
  736. * Extracts the features from the presence.
  737. * @param node the node to process.
  738. * @return features the Set of features where extracted data is added.
  739. * @private
  740. */
  741. _extractFeatures(node) {
  742. const features = new Set();
  743. for (let j = 0; j < node.children.length; j++) {
  744. const { attributes } = node.children[j];
  745. if (attributes && attributes.var) {
  746. features.add(attributes.var);
  747. }
  748. }
  749. return features;
  750. }
  751. /**
  752. * Initialize some properties when the focus participant is verified.
  753. * @param from jid of the focus
  754. * @param features the features reported in jicofo presence
  755. */
  756. _initFocus(from, features) {
  757. this.focusMucJid = from;
  758. this.focusFeatures = features;
  759. }
  760. /**
  761. * Sets the special listener to be used for "command"s whose name starts
  762. * with "jitsi_participant_".
  763. */
  764. setParticipantPropertyListener(listener) {
  765. this.participantPropertyListener = listener;
  766. }
  767. /**
  768. *
  769. * @param node
  770. * @param from
  771. */
  772. processNode(node, from) {
  773. // make sure we catch all errors coming from any handler
  774. // otherwise we can remove the presence handler from strophe
  775. try {
  776. let tagHandlers = this.presHandlers[node.tagName];
  777. if (node.tagName.startsWith('jitsi_participant_')) {
  778. tagHandlers = [ this.participantPropertyListener ];
  779. }
  780. if (tagHandlers) {
  781. tagHandlers.forEach(handler => {
  782. handler(node, Strophe.getResourceFromJid(from), from);
  783. });
  784. }
  785. } catch (e) {
  786. logger.error(`Error processing:${node.tagName} node.`, e);
  787. }
  788. }
  789. /**
  790. * Send text message to the other participants in the conference
  791. * @param message
  792. * @param elementName
  793. */
  794. sendMessage(message, elementName) {
  795. const msg = $msg({ to: this.roomjid,
  796. type: 'groupchat' });
  797. // We are adding the message in a packet extension. If this element
  798. // is different from 'body', we add a custom namespace.
  799. // e.g. for 'json-message' extension of message stanza.
  800. if (elementName === 'body') {
  801. msg.c(elementName, {}, message);
  802. } else {
  803. msg.c(elementName, { xmlns: 'http://jitsi.org/jitmeet' }, message);
  804. }
  805. this.connection.send(msg);
  806. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, message);
  807. }
  808. /**
  809. * Sends a reaction message to the other participants in the conference.
  810. * @param {string} reaction - The reaction being sent.
  811. * @param {string} messageId - The id of the message being sent.
  812. * @param {string} receiverId - The receiver of the message if it is private.
  813. */
  814. sendReaction(reaction, messageId, receiverId) {
  815. // Adds the 'to' attribute depending on if the message is private or not.
  816. const msg = receiverId ? $msg({ to: `${this.roomjid}/${receiverId}`,
  817. type: 'chat' }) : $msg({ to: this.roomjid,
  818. type: 'groupchat' });
  819. msg.c('reactions', { id: messageId,
  820. xmlns: 'urn:xmpp:reactions:0' })
  821. .c('reaction', {}, reaction)
  822. .up().c('store', { xmlns: 'urn:xmpp:hints' });
  823. this.connection.send(msg);
  824. }
  825. /* eslint-disable max-params */
  826. /**
  827. * Send private text message to another participant of the conference
  828. * @param id id/muc resource of the receiver
  829. * @param message
  830. * @param elementName
  831. */
  832. sendPrivateMessage(id, message, elementName) {
  833. const msg = $msg({ to: `${this.roomjid}/${id}`,
  834. type: 'chat' });
  835. // We are adding the message in packet. If this element is different
  836. // from 'body', we add our custom namespace for the same.
  837. // e.g. for 'json-message' message extension.
  838. if (elementName === 'body') {
  839. msg.c(elementName, message).up();
  840. } else {
  841. msg.c(elementName, { xmlns: 'http://jitsi.org/jitmeet' }, message)
  842. .up();
  843. }
  844. this.connection.send(msg);
  845. this.eventEmitter.emit(
  846. XMPPEvents.SENDING_PRIVATE_CHAT_MESSAGE, message);
  847. }
  848. /* eslint-enable max-params */
  849. /**
  850. *
  851. * @param subject
  852. */
  853. setSubject(subject) {
  854. const msg = $msg({ to: this.roomjid,
  855. type: 'groupchat' });
  856. msg.c('subject', subject);
  857. this.connection.send(msg);
  858. }
  859. /**
  860. *
  861. * @param pres
  862. * @param from
  863. */
  864. onPresenceUnavailable(pres, from) {
  865. // ignore presence
  866. if ($(pres).find('>ignore[xmlns="http://jitsi.org/jitmeet/"]').length) {
  867. return true;
  868. }
  869. // room destroyed ?
  870. const destroySelect = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>destroy');
  871. if (destroySelect.length) {
  872. let reason;
  873. const reasonSelect
  874. = $(pres).find(
  875. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  876. + '>destroy>reason');
  877. if (reasonSelect.length) {
  878. reason = reasonSelect.text();
  879. }
  880. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason, destroySelect.attr('jid'));
  881. this.connection.emuc.doLeave(this.roomjid);
  882. return true;
  883. }
  884. // Status code 110 indicates that this notification is "self-presence".
  885. const isSelfPresence
  886. = $(pres)
  887. .find(
  888. '>x[xmlns="http://jabber.org/protocol/muc#user"]>'
  889. + 'status[code="110"]')
  890. .length;
  891. const isKick
  892. = $(pres)
  893. .find(
  894. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  895. + '>status[code="307"]')
  896. .length;
  897. const membersKeys = Object.keys(this.members);
  898. const isReplaceParticipant = $(pres).find('flip_device').length;
  899. if (isKick) {
  900. const actorSelect
  901. = $(pres)
  902. .find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item>actor');
  903. let actorNick;
  904. if (actorSelect.length) {
  905. actorNick = actorSelect.attr('nick');
  906. }
  907. let reason;
  908. const reasonSelect
  909. = $(pres).find(
  910. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  911. + '>item>reason');
  912. if (reasonSelect.length) {
  913. reason = reasonSelect.text();
  914. }
  915. // we first fire the kicked so we can show the participant
  916. // who kicked, before notifying that participant left
  917. // we fire kicked for us and for any participant kicked
  918. this.eventEmitter.emit(
  919. XMPPEvents.KICKED,
  920. isSelfPresence,
  921. actorNick,
  922. Strophe.getResourceFromJid(from),
  923. reason,
  924. isReplaceParticipant);
  925. }
  926. if (isSelfPresence) {
  927. // If the status code is 110 this means we're leaving and we would
  928. // like to remove everyone else from our view, so we trigger the
  929. // event.
  930. membersKeys.forEach(jid => {
  931. const member = this.members[jid];
  932. delete this.members[jid];
  933. delete this.lastPresences[jid];
  934. if (!member.isFocus) {
  935. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  936. }
  937. });
  938. this.connection.emuc.doLeave(this.roomjid);
  939. // we fire muc_left only if this is not a kick,
  940. // kick has both statuses 110 and 307.
  941. if (!isKick) {
  942. this.eventEmitter.emit(XMPPEvents.MUC_LEFT);
  943. }
  944. } else {
  945. const reasonSelect = $(pres).find('>status');
  946. const member = this.members[from];
  947. let reason;
  948. if (reasonSelect.length) {
  949. reason = reasonSelect.text();
  950. }
  951. delete this.members[from];
  952. delete this.lastPresences[from];
  953. // In this case we *do* fire MUC_MEMBER_LEFT for the focus?
  954. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, from, reason);
  955. if (member && member.isHiddenDomain && member.features.has(FEATURE_TRANSCRIBER)
  956. && this.transcriptionStatus !== JitsiTranscriptionStatus.OFF) {
  957. this.transcriptionStatus = JitsiTranscriptionStatus.OFF;
  958. this.eventEmitter.emit(
  959. XMPPEvents.TRANSCRIPTION_STATUS_CHANGED,
  960. this.transcriptionStatus,
  961. Strophe.getResourceFromJid(from),
  962. true /* exited abruptly */
  963. );
  964. }
  965. if (member?.isFocus) {
  966. logger.info('Focus has left the room - leaving conference');
  967. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  968. }
  969. }
  970. }
  971. /**
  972. *
  973. * @param msg
  974. * @param from
  975. */
  976. onMessage(msg, from) {
  977. const type = msg.getAttribute('type');
  978. if (type === 'error') {
  979. const settingsErrorMsg = $(msg).find('>settings-error>text').text();
  980. if (settingsErrorMsg.length) {
  981. this.eventEmitter.emit(XMPPEvents.SETTINGS_ERROR_RECEIVED, settingsErrorMsg);
  982. return true;
  983. }
  984. const errorMsg = $(msg).find('>error>text').text();
  985. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED, errorMsg);
  986. return true;
  987. }
  988. const reactions = $(msg).find('>[xmlns="urn:xmpp:reactions:0"]>reaction');
  989. if (reactions.length > 0) {
  990. const messageId = $(msg).find('>[xmlns="urn:xmpp:reactions:0"]').attr('id');
  991. const reactionList = [];
  992. reactions.each((_, reactionElem) => {
  993. const reaction = $(reactionElem).text();
  994. reactionList.push(reaction);
  995. });
  996. this.eventEmitter.emit(XMPPEvents.REACTION_RECEIVED, from, reactionList, messageId);
  997. return true;
  998. }
  999. const txt = $(msg).find('>body').text();
  1000. const subject = $(msg).find('>subject');
  1001. if (subject.length) {
  1002. const subjectText = subject.text();
  1003. if (subjectText || subjectText === '') {
  1004. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  1005. logger.log(`Subject is changed to ${subjectText}`);
  1006. }
  1007. }
  1008. // xep-0203 delay
  1009. let stamp = $(msg).find('>delay').attr('stamp');
  1010. if (!stamp) {
  1011. // or xep-0091 delay, UTC timestamp
  1012. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  1013. if (stamp) {
  1014. // the format is CCYYMMDDThh:mm:ss
  1015. const dateParts
  1016. = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  1017. stamp = `${dateParts[1]}-${dateParts[2]}-${dateParts[3]}Z`;
  1018. }
  1019. }
  1020. if (from === this.roomjid) {
  1021. let invite;
  1022. if ($(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="104"]').length) {
  1023. this.discoRoomInfo();
  1024. } else if ((invite = $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>invite'))
  1025. && invite.length) {
  1026. const passwordSelect = $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>password');
  1027. let password;
  1028. if (passwordSelect && passwordSelect.length) {
  1029. password = passwordSelect.text();
  1030. }
  1031. this.eventEmitter.emit(XMPPEvents.INVITE_MESSAGE_RECEIVED,
  1032. from, invite.attr('from'), txt, password);
  1033. }
  1034. }
  1035. const jsonMessage = $(msg).find('>json-message').text();
  1036. if (jsonMessage) {
  1037. const parsedJson = this.xmpp.tryParseJSONAndVerify(jsonMessage);
  1038. // We emit this event if the message is a valid json, and is not
  1039. // delivered after a delay, i.e. stamp is undefined.
  1040. // e.g. - subtitles should not be displayed if delayed.
  1041. if (parsedJson && stamp === undefined) {
  1042. this.eventEmitter.emit(XMPPEvents.JSON_MESSAGE_RECEIVED,
  1043. from, parsedJson);
  1044. return;
  1045. }
  1046. }
  1047. if (txt) {
  1048. const messageId = $(msg).attr('id') || uuidv4();
  1049. if (type === 'chat') {
  1050. this.eventEmitter.emit(XMPPEvents.PRIVATE_MESSAGE_RECEIVED,
  1051. from, txt, this.myroomjid, stamp, messageId);
  1052. } else if (type === 'groupchat') {
  1053. const nickEl = $(msg).find('>nick');
  1054. let nick;
  1055. if (nickEl.length > 0) {
  1056. nick = nickEl.text();
  1057. }
  1058. // we will fire explicitly that this is a guest(isGuest:true) to the conference
  1059. // informing that this is probably a message from a guest to the conference (visitor)
  1060. // a message with explicit name set
  1061. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  1062. from, txt, this.myroomjid, stamp, nick, Boolean(nick), messageId);
  1063. }
  1064. }
  1065. }
  1066. /**
  1067. *
  1068. * @param pres
  1069. * @param from
  1070. */
  1071. onPresenceError(pres, from) {
  1072. let errorDescriptionNode;
  1073. if (from === this.myroomjid) {
  1074. // we have tried to join, and we received an error, let's send again conference-iq on next attempt
  1075. // as it may turn out that jicofo left the room if we were the first to try,
  1076. // and the user delayed the attempt for entering the password or such
  1077. this.xmpp.moderator.conferenceRequestSent = false;
  1078. }
  1079. if ($(pres)
  1080. .find(
  1081. '>error[type="auth"]'
  1082. + '>not-authorized['
  1083. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  1084. .length) {
  1085. logger.log('on password required', from);
  1086. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  1087. } else if ($(pres)
  1088. .find(
  1089. '>error[type="cancel"]'
  1090. + '>not-allowed['
  1091. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  1092. .length) {
  1093. const toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  1094. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  1095. // enter the room by replying with 'not-authorized'. This would
  1096. // result in reconnection from authorized domain.
  1097. // We're either missing Jicofo/Prosody config for anonymous
  1098. // domains or something is wrong.
  1099. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR);
  1100. } else {
  1101. logger.warn('onPresError ', pres);
  1102. const txtNode = $(pres).find('>error[type="cancel"]>text[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]');
  1103. const txt = txtNode.length && txtNode.text();
  1104. let type = AUTH_ERROR_TYPES.GENERAL;
  1105. // a race where we have sent a conference request to jicofo and jicofo was about to leave or just left
  1106. // because of no participants in the room, and we tried to create the room, without having
  1107. // permissions for that (only jicofo creates rooms)
  1108. if (txt === 'Room creation is restricted') {
  1109. type = AUTH_ERROR_TYPES.ROOM_CREATION_RESTRICTION;
  1110. if (!this._roomCreationRetries) {
  1111. this._roomCreationRetries = 0;
  1112. }
  1113. this._roomCreationRetries++;
  1114. if (this._roomCreationRetries <= 3) {
  1115. const retryDelay = getJitterDelay(
  1116. /* retry */ this._roomCreationRetries,
  1117. /* minDelay */ 500,
  1118. 1.5);
  1119. // let's retry inviting jicofo and joining the room, retries will take between 1 and 3 seconds
  1120. setTimeout(() => this.join(this.password, this.replaceParticipant), retryDelay);
  1121. return;
  1122. }
  1123. } else if ($(pres).find(
  1124. '>error[type="cancel"]>no-main-participants[xmlns="jitsi:visitors"]').length > 0) {
  1125. type = AUTH_ERROR_TYPES.NO_MAIN_PARTICIPANTS;
  1126. } else if ($(pres).find(
  1127. '>error[type="cancel"]>promotion-not-allowed[xmlns="jitsi:visitors"]').length > 0) {
  1128. type = AUTH_ERROR_TYPES.PROMOTION_NOT_ALLOWED;
  1129. } else if ($(pres).find(
  1130. '>error[type="cancel"]>no-visitors-lobby[xmlns="jitsi:visitors"]').length > 0) {
  1131. type = AUTH_ERROR_TYPES.NO_VISITORS_LOBBY;
  1132. }
  1133. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_NOT_ALLOWED_ERROR, type, txt);
  1134. }
  1135. } else if ($(pres).find('>error>service-unavailable').length) {
  1136. logger.warn('Maximum users limit for the room has been reached',
  1137. pres);
  1138. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR);
  1139. } else if ($(pres)
  1140. .find(
  1141. '>error[type="auth"]'
  1142. + '>registration-required['
  1143. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  1144. // let's extract the lobby jid from the custom field
  1145. const lobbyRoomNode = $(pres).find('>error[type="auth"]>lobbyroom');
  1146. let lobbyRoomJid;
  1147. if (lobbyRoomNode.length) {
  1148. lobbyRoomJid = lobbyRoomNode.text();
  1149. }
  1150. const waitingForHost = $(pres).find('>error[type="auth"]>waiting-for-host').length > 0;
  1151. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_MEMBERS_ONLY_ERROR, lobbyRoomJid, waitingForHost);
  1152. } else if ((errorDescriptionNode = $(pres).find(
  1153. '>error[type="modify"]>displayname-required[xmlns="http://jitsi.org/jitmeet"]')).length) {
  1154. logger.warn('display name required ', pres);
  1155. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_REQUIRED, errorDescriptionNode[0].attributes.lobby?.value);
  1156. } else {
  1157. logger.warn('onPresError ', pres);
  1158. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR);
  1159. }
  1160. }
  1161. /**
  1162. *
  1163. * @param jid
  1164. * @param affiliation
  1165. */
  1166. setAffiliation(jid, affiliation) {
  1167. const grantIQ = $iq({
  1168. to: this.roomjid,
  1169. type: 'set'
  1170. })
  1171. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  1172. .c('item', {
  1173. affiliation,
  1174. jid: Strophe.getBareJidFromJid(jid)
  1175. })
  1176. .c('reason').t(`Your affiliation has been changed to '${affiliation}'.`)
  1177. .up().up().up();
  1178. this.connection.sendIQ(
  1179. grantIQ,
  1180. result => logger.log('Set affiliation of participant with jid: ', jid, 'to', affiliation, result),
  1181. error => logger.log('Set affiliation of participant error: ', error));
  1182. }
  1183. /**
  1184. *
  1185. * @param jid
  1186. * @param reason
  1187. */
  1188. kick(jid, reason = 'You have been kicked.') {
  1189. const kickIQ = $iq({ to: this.roomjid,
  1190. type: 'set' })
  1191. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  1192. .c('item', { nick: Strophe.getResourceFromJid(jid),
  1193. role: 'none' })
  1194. .c('reason').t(reason).up().up().up();
  1195. this.connection.sendIQ(
  1196. kickIQ,
  1197. result => logger.log('Kick participant with jid: ', jid, result),
  1198. error => logger.log('Kick participant error: ', error));
  1199. }
  1200. /* eslint-disable max-params */
  1201. /**
  1202. *
  1203. * @param key
  1204. * @param onSuccess
  1205. * @param onError
  1206. * @param onNotSupported
  1207. */
  1208. lockRoom(key, onSuccess, onError, onNotSupported) {
  1209. // http://xmpp.org/extensions/xep-0045.html#roomconfig
  1210. this.connection.sendIQ(
  1211. $iq({
  1212. to: this.roomjid,
  1213. type: 'get'
  1214. })
  1215. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  1216. res => {
  1217. if ($(res)
  1218. .find(
  1219. '>query>x[xmlns="jabber:x:data"]'
  1220. + '>field[var="muc#roomconfig_roomsecret"]')
  1221. .length) {
  1222. const formsubmit
  1223. = $iq({
  1224. to: this.roomjid,
  1225. type: 'set'
  1226. })
  1227. .c('query', {
  1228. xmlns: 'http://jabber.org/protocol/muc#owner'
  1229. });
  1230. formsubmit.c('x', {
  1231. xmlns: 'jabber:x:data',
  1232. type: 'submit'
  1233. });
  1234. formsubmit
  1235. .c('field', { 'var': 'FORM_TYPE' })
  1236. .c('value')
  1237. .t('http://jabber.org/protocol/muc#roomconfig')
  1238. .up()
  1239. .up();
  1240. formsubmit
  1241. .c('field', { 'var': 'muc#roomconfig_roomsecret' })
  1242. .c('value')
  1243. .t(key)
  1244. .up()
  1245. .up();
  1246. formsubmit
  1247. .c('field',
  1248. { 'var': 'muc#roomconfig_passwordprotectedroom' })
  1249. .c('value')
  1250. .t(key === null || key.length === 0 ? '0' : '1')
  1251. .up()
  1252. .up();
  1253. // if members only enabled
  1254. if (this.membersOnlyEnabled) {
  1255. formsubmit
  1256. .c('field', { 'var': 'muc#roomconfig_membersonly' })
  1257. .c('value')
  1258. .t('true')
  1259. .up()
  1260. .up();
  1261. }
  1262. // Fixes a bug in prosody 0.9.+
  1263. // https://prosody.im/issues/issue/373
  1264. formsubmit
  1265. .c('field', { 'var': 'muc#roomconfig_whois' })
  1266. .c('value')
  1267. .t('anyone')
  1268. .up()
  1269. .up();
  1270. this.connection.sendIQ(
  1271. formsubmit,
  1272. () => {
  1273. // we set the password in chat room so we can use it
  1274. // later when dialing out
  1275. this.password = key;
  1276. onSuccess();
  1277. },
  1278. onError);
  1279. } else {
  1280. onNotSupported();
  1281. }
  1282. },
  1283. onError);
  1284. }
  1285. /* eslint-enable max-params */
  1286. /**
  1287. * Turns off or on the members only config for the main room.
  1288. *
  1289. * @param {boolean} enabled - Whether to turn it on or off.
  1290. * @param onSuccess - optional callback.
  1291. * @param onError - optional callback.
  1292. */
  1293. setMembersOnly(enabled, onSuccess, onError) {
  1294. if (enabled && Object.values(this.members).filter(m => !m.isFocus).length) {
  1295. // first grant membership to all that are in the room
  1296. const affiliationsIq = $iq({
  1297. to: this.roomjid,
  1298. type: 'set' })
  1299. .c('query', {
  1300. xmlns: 'http://jabber.org/protocol/muc#admin' });
  1301. let sendIq = false;
  1302. Object.values(this.members).forEach(m => {
  1303. if (m.jid && !MEMBERS_AFFILIATIONS.includes(m.affiliation)) {
  1304. affiliationsIq.c('item', {
  1305. 'affiliation': 'member',
  1306. 'jid': Strophe.getBareJidFromJid(m.jid)
  1307. }).up();
  1308. sendIq = true;
  1309. }
  1310. });
  1311. sendIq && this.xmpp.connection.sendIQ(affiliationsIq.up());
  1312. }
  1313. const errorCallback = onError ? onError : () => {}; // eslint-disable-line no-empty-function
  1314. this.xmpp.connection.sendIQ(
  1315. $iq({
  1316. to: this.roomjid,
  1317. type: 'get'
  1318. }).c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  1319. res => {
  1320. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_membersonly"]').length) {
  1321. const formToSubmit
  1322. = $iq({
  1323. to: this.roomjid,
  1324. type: 'set'
  1325. }).c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' });
  1326. formToSubmit.c('x', {
  1327. xmlns: 'jabber:x:data',
  1328. type: 'submit'
  1329. });
  1330. formToSubmit
  1331. .c('field', { 'var': 'FORM_TYPE' })
  1332. .c('value')
  1333. .t('http://jabber.org/protocol/muc#roomconfig')
  1334. .up()
  1335. .up();
  1336. formToSubmit
  1337. .c('field', { 'var': 'muc#roomconfig_membersonly' })
  1338. .c('value')
  1339. .t(enabled ? 'true' : 'false')
  1340. .up()
  1341. .up();
  1342. // if room is locked from other participant or we are locking it
  1343. if (this.locked) {
  1344. formToSubmit
  1345. .c('field',
  1346. { 'var': 'muc#roomconfig_passwordprotectedroom' })
  1347. .c('value')
  1348. .t('1')
  1349. .up()
  1350. .up();
  1351. }
  1352. this.xmpp.connection.sendIQ(formToSubmit, onSuccess, errorCallback);
  1353. } else {
  1354. errorCallback(new Error('Setting members only room not supported!'));
  1355. }
  1356. },
  1357. errorCallback);
  1358. }
  1359. /**
  1360. * Adds the key to the presence map, overriding any previous value.
  1361. * This method is used by jibri.
  1362. *
  1363. * @param key The key to add or replace.
  1364. * @param values The new values.
  1365. * @returns {boolean|null} <tt>true</tt> if the operation succeeded or <tt>false</tt> when no add or replce was
  1366. * performed as the value was already there.
  1367. * @deprecated Use 'addOrReplaceInPresence' instead. TODO: remove it from here and jibri.
  1368. */
  1369. addToPresence(key, values) {
  1370. return this.addOrReplaceInPresence(key, values);
  1371. }
  1372. /**
  1373. * Adds the key to the presence map, overriding any previous value.
  1374. * @param key The key to add or replace.
  1375. * @param values The new values.
  1376. * @returns {boolean|null} <tt>true</tt> if the operation succeeded or <tt>false</tt> when no add or replace was
  1377. * performed as the value was already there.
  1378. */
  1379. addOrReplaceInPresence(key, values) {
  1380. values.tagName = key;
  1381. const matchingNodes = this.presMap.nodes.filter(node => key === node.tagName);
  1382. // if we have found just one, let's check is it the same
  1383. if (matchingNodes.length === 1 && isEqual(matchingNodes[0], values)) {
  1384. return false;
  1385. }
  1386. this.removeFromPresence(key);
  1387. this.presMap.nodes.push(values);
  1388. this.presenceUpdateTime = Date.now();
  1389. return true;
  1390. }
  1391. /**
  1392. * Retrieves a value from the presence map.
  1393. *
  1394. * @param {string} key - The key to find the value for.
  1395. * @returns {Object?}
  1396. */
  1397. getFromPresence(key) {
  1398. return this.presMap.nodes.find(node => key === node.tagName);
  1399. }
  1400. /**
  1401. * Removes a key from the presence map.
  1402. * @param key
  1403. */
  1404. removeFromPresence(key) {
  1405. const nodes = this.presMap.nodes.filter(node => key !== node.tagName);
  1406. this.presMap.nodes = nodes;
  1407. this.presenceUpdateTime = Date.now();
  1408. }
  1409. /**
  1410. *
  1411. * @param name
  1412. * @param handler
  1413. */
  1414. addPresenceListener(name, handler) {
  1415. if (typeof handler !== 'function') {
  1416. throw new Error('"handler" is not a function');
  1417. }
  1418. let tagHandlers = this.presHandlers[name];
  1419. if (!tagHandlers) {
  1420. this.presHandlers[name] = tagHandlers = [];
  1421. }
  1422. if (tagHandlers.indexOf(handler) === -1) {
  1423. tagHandlers.push(handler);
  1424. } else {
  1425. logger.warn(
  1426. `Trying to add the same handler more than once for: ${name}`);
  1427. }
  1428. }
  1429. /**
  1430. *
  1431. * @param name
  1432. * @param handler
  1433. */
  1434. removePresenceListener(name, handler) {
  1435. const tagHandlers = this.presHandlers[name];
  1436. const handlerIdx = tagHandlers ? tagHandlers.indexOf(handler) : -1;
  1437. // eslint-disable-next-line no-negated-condition
  1438. if (handlerIdx !== -1) {
  1439. tagHandlers.splice(handlerIdx, 1);
  1440. } else {
  1441. logger.warn(`Handler for: ${name} was not registered`);
  1442. }
  1443. }
  1444. /**
  1445. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1446. * focus.
  1447. * @param mucJid the full MUC address of the user to be checked.
  1448. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus
  1449. * or <tt>false</tt> if is not. When given <tt>mucJid</tt> does not exist in
  1450. * the MUC then <tt>null</tt> is returned.
  1451. */
  1452. isFocus(mucJid) {
  1453. const member = this.members[mucJid];
  1454. if (member) {
  1455. return member.isFocus;
  1456. }
  1457. return null;
  1458. }
  1459. /**
  1460. *
  1461. */
  1462. isModerator() {
  1463. return this.role === 'moderator';
  1464. }
  1465. /**
  1466. * Obtains the info about given media advertised (in legacy format) in the MUC presence of the participant
  1467. * identified by the given endpoint JID. This is for mantining interop with endpoints that do not support
  1468. * source-name signaling (Jigasi and very old mobile clients).
  1469. *
  1470. * @param {string} endpointId the endpoint ID mapped to the participant which corresponds to MUC nickname.
  1471. * @param {MediaType} mediaType the type of the media for which presence info will be obtained.
  1472. * @return {PeerMediaInfo} presenceInfo an object with media presence info or <tt>null</tt> either if there
  1473. * is no presence available or if the media type given is invalid.
  1474. */
  1475. getMediaPresenceInfo(endpointId, mediaType) {
  1476. // Will figure out current muted status by looking up owner's presence
  1477. const pres = this.lastPresences[`${this.roomjid}/${endpointId}`];
  1478. if (!pres) {
  1479. // No presence available
  1480. return null;
  1481. }
  1482. const data = {
  1483. muted: true, // muted by default
  1484. videoType: mediaType === MediaType.VIDEO ? VideoType.CAMERA : undefined // 'camera' by default
  1485. };
  1486. let mutedNode = null;
  1487. if (mediaType === MediaType.AUDIO) {
  1488. mutedNode = filterNodeFromPresenceJSON(pres, 'audiomuted');
  1489. } else if (mediaType === MediaType.VIDEO) {
  1490. mutedNode = filterNodeFromPresenceJSON(pres, 'videomuted');
  1491. const codecTypeNode = filterNodeFromPresenceJSON(pres, 'jitsi_participant_codecType');
  1492. const videoTypeNode = filterNodeFromPresenceJSON(pres, 'videoType');
  1493. if (videoTypeNode.length > 0) {
  1494. data.videoType = videoTypeNode[0].value;
  1495. }
  1496. if (codecTypeNode.length > 0) {
  1497. data.codecType = codecTypeNode[0].value;
  1498. }
  1499. } else {
  1500. logger.error(`Unsupported media type: ${mediaType}`);
  1501. return null;
  1502. }
  1503. if (mutedNode.length > 0) {
  1504. data.muted = mutedNode[0].value === 'true';
  1505. }
  1506. return data;
  1507. }
  1508. /**
  1509. *
  1510. * @param peerJid
  1511. */
  1512. getMemberRole(peerJid) {
  1513. if (this.members[peerJid]) {
  1514. return this.members[peerJid].role;
  1515. }
  1516. return null;
  1517. }
  1518. /**
  1519. * Returns the last presence advertised by a MUC member.
  1520. * @param {string} mucNick
  1521. * @returns {*}
  1522. */
  1523. getLastPresence(mucNick) {
  1524. return this.lastPresences[`${this.roomjid}/${mucNick}`];
  1525. }
  1526. /**
  1527. * Dials a number.
  1528. * @param number the number
  1529. */
  1530. dial(number) {
  1531. return this.connection.rayo.dial(number, 'fromnumber',
  1532. Strophe.getBareJidFromJid(this.myroomjid), this.password,
  1533. this.focusMucJid);
  1534. }
  1535. /**
  1536. * Hangup an existing call
  1537. */
  1538. hangup() {
  1539. return this.connection.rayo.hangup();
  1540. }
  1541. /**
  1542. *
  1543. * @returns {Lobby}
  1544. */
  1545. getLobby() {
  1546. return this.lobby;
  1547. }
  1548. /**
  1549. * @returns {AVModeration}
  1550. */
  1551. getAVModeration() {
  1552. return this.avModeration;
  1553. }
  1554. /**
  1555. * @returns {BreakoutRooms}
  1556. */
  1557. getBreakoutRooms() {
  1558. return this.breakoutRooms;
  1559. }
  1560. /**
  1561. * @returns {RoomMetadata}
  1562. */
  1563. getMetadataHandler() {
  1564. return this.roomMetadata;
  1565. }
  1566. /**
  1567. * Returns the phone number for joining the conference.
  1568. */
  1569. getPhoneNumber() {
  1570. return this.phoneNumber;
  1571. }
  1572. /**
  1573. * Returns the pin for joining the conference with phone.
  1574. */
  1575. getPhonePin() {
  1576. return this.phonePin;
  1577. }
  1578. /**
  1579. * Returns the meeting unique ID if any came from backend.
  1580. *
  1581. * @returns {string} - The meeting ID.
  1582. */
  1583. getMeetingId() {
  1584. return this.meetingId;
  1585. }
  1586. /**
  1587. * Mutes remote participant.
  1588. * @param jid of the participant
  1589. * @param mute
  1590. * @param mediaType
  1591. */
  1592. muteParticipant(jid, mute, mediaType) {
  1593. logger.info('set mute', mute, jid);
  1594. const iqToFocus = $iq(
  1595. { to: this.focusMucJid,
  1596. type: 'set' })
  1597. .c('mute', {
  1598. xmlns: `http://jitsi.org/jitmeet/${mediaType}`,
  1599. jid
  1600. })
  1601. .t(mute.toString())
  1602. .up();
  1603. this.connection.sendIQ(
  1604. iqToFocus,
  1605. result => logger.log('set mute', result),
  1606. error => logger.log('set mute error', error));
  1607. }
  1608. /**
  1609. * TODO: Document
  1610. * @param iq
  1611. */
  1612. onMute(iq) {
  1613. const from = iq.getAttribute('from');
  1614. if (from !== this.focusMucJid) {
  1615. logger.warn('Ignored mute from non focus peer');
  1616. return;
  1617. }
  1618. const mute = $(iq).find('mute');
  1619. if (mute.length && mute.text() === 'true') {
  1620. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, mute.attr('actor'));
  1621. } else {
  1622. // XXX Why do we support anything but muting? Why do we encode the
  1623. // value in the text of the element? Why do we use a separate XML
  1624. // namespace?
  1625. logger.warn('Ignoring a mute request which does not explicitly '
  1626. + 'specify a positive mute command.');
  1627. }
  1628. }
  1629. /**
  1630. * TODO: Document
  1631. * @param iq
  1632. */
  1633. onMuteVideo(iq) {
  1634. const from = iq.getAttribute('from');
  1635. if (from !== this.focusMucJid) {
  1636. logger.warn('Ignored mute from non focus peer');
  1637. return;
  1638. }
  1639. const mute = $(iq).find('mute');
  1640. if (mute.length && mute.text() === 'true') {
  1641. this.eventEmitter.emit(XMPPEvents.VIDEO_MUTED_BY_FOCUS, mute.attr('actor'));
  1642. } else {
  1643. // XXX Why do we support anything but muting? Why do we encode the
  1644. // value in the text of the element? Why do we use a separate XML
  1645. // namespace?
  1646. logger.warn('Ignoring a mute request which does not explicitly '
  1647. + 'specify a positive mute command.');
  1648. }
  1649. }
  1650. /**
  1651. * Clean any listeners or resources, executed on leaving.
  1652. */
  1653. clean() {
  1654. this._removeConnListeners.forEach(remove => remove());
  1655. this._removeConnListeners = [];
  1656. this.eventsForwarder.removeListeners(
  1657. AuthenticationEvents.IDENTITY_UPDATED,
  1658. XMPPEvents.AUTHENTICATION_REQUIRED,
  1659. XMPPEvents.FOCUS_DISCONNECTED,
  1660. XMPPEvents.RESERVATION_ERROR);
  1661. this.joined = false;
  1662. this.inProgressEmitted = false;
  1663. }
  1664. /**
  1665. * Leaves the room. Closes the jingle session.
  1666. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received
  1667. * less than 5s after sending presence unavailable. Otherwise the promise is
  1668. * rejected.
  1669. */
  1670. leave(reason) {
  1671. this.avModeration.dispose();
  1672. this.breakoutRooms.dispose();
  1673. this.roomMetadata.dispose();
  1674. const promises = [];
  1675. this.lobby?.lobbyRoom && promises.push(this.lobby.leave());
  1676. promises.push(new Promise((resolve, reject) => {
  1677. let timeout = -1;
  1678. const onMucLeft = (doReject = false) => {
  1679. this.eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1680. clearTimeout(timeout);
  1681. // This will reset the joined flag to false. If we reset it earlier any self presence will be
  1682. // interpreted as muc join. That's why we reset the flag once we have received presence unavalable
  1683. // (MUC_LEFT).
  1684. this.clean();
  1685. if (doReject) {
  1686. // The timeout expired. Make sure we clean the EMUC state.
  1687. this.connection.emuc.doLeave(this.roomjid);
  1688. reject(new Error('The timeout for the confirmation about leaving the room expired.'));
  1689. } else {
  1690. resolve();
  1691. }
  1692. };
  1693. if (this.joined) {
  1694. timeout = setTimeout(() => onMucLeft(true), 5000);
  1695. this.eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  1696. this.doLeave(reason);
  1697. } else {
  1698. // we are clearing up, and we haven't joined the room
  1699. // there is no point of sending presence unavailable and check for timeout
  1700. // let's just clean
  1701. this.connection.emuc.doLeave(this.roomjid);
  1702. this.clean();
  1703. resolve();
  1704. }
  1705. }));
  1706. return Promise.allSettled(promises);
  1707. }
  1708. /**
  1709. * Ends the conference for all participants.
  1710. */
  1711. end() {
  1712. if (this.breakoutRooms.isBreakoutRoom()) {
  1713. logger.warn('Cannot end conference: this is a breakout room.');
  1714. return;
  1715. }
  1716. // Send the end conference message.
  1717. const msg = $msg({ to: this.xmpp.endConferenceComponentAddress });
  1718. msg.c('end_conference').up();
  1719. this.xmpp.connection.send(msg);
  1720. }
  1721. }
  1722. /* eslint-enable newline-per-chained-call */