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

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