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

ChatRoom.js 70KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055
  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 'jitsi_participant_region': {
  510. member.region = node.value;
  511. break;
  512. }
  513. case 'stat': {
  514. const { attributes } = node;
  515. if (!attributes) {
  516. break;
  517. }
  518. const { name } = attributes;
  519. if (name === 'version') {
  520. member.version = attributes.value;
  521. }
  522. break;
  523. }
  524. }
  525. }
  526. if (!this.joined && !this.inProgressEmitted) {
  527. const now = this.connectionTimes['muc.join.started'] = window.performance.now();
  528. logger.log('(TIME) MUC join started:\t', now);
  529. this.eventEmitter.emit(XMPPEvents.MUC_JOIN_IN_PROGRESS);
  530. this.inProgressEmitted = true;
  531. }
  532. if (from === this.myroomjid) {
  533. const newRole
  534. = member.affiliation === 'owner' ? member.role : 'none';
  535. if (this.role !== newRole) {
  536. this.role = newRole;
  537. this.eventEmitter.emit(
  538. XMPPEvents.LOCAL_ROLE_CHANGED,
  539. this.role);
  540. }
  541. if (!this.joined) {
  542. this.joined = true;
  543. const now = this.connectionTimes['muc.joined']
  544. = window.performance.now();
  545. logger.log('(TIME) MUC joined:\t', now);
  546. // set correct initial state of locked
  547. if (this.password) {
  548. this.locked = true;
  549. }
  550. if (member.region && this.options?.deploymentInfo) {
  551. this.options.deploymentInfo.userRegion = member.region;
  552. }
  553. // Re-send presence in case any presence updates were added,
  554. // but blocked from sending, during the join process.
  555. // send the presence only if there was a modification after we had synced it
  556. if (this.presenceUpdateTime >= this.presenceSyncTime) {
  557. this.sendPresence();
  558. }
  559. // we need to reset it because of breakout rooms which will reuse connection but will invite jicofo
  560. this.xmpp.moderator.conferenceRequestSent = false;
  561. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  562. // Now let's check the disco-info to retrieve the
  563. // meeting Id if any
  564. !this.options.disableDiscoInfo && this.discoRoomInfo();
  565. }
  566. } else if (jid === undefined) {
  567. logger.info('Ignoring member with undefined JID');
  568. } else if (this.members[from] === undefined) {
  569. // new participant
  570. this.members[from] = member;
  571. logger.log('entered', from, member);
  572. hasStatusUpdate = member.status !== undefined;
  573. hasVersionUpdate = member.version !== undefined;
  574. if (member.isFocus) {
  575. this._initFocus(from, member.features);
  576. } else {
  577. // identity is being added to member joined, so external
  578. // services can be notified for that (currently identity is
  579. // not used inside library)
  580. this.eventEmitter.emit(
  581. XMPPEvents.MUC_MEMBER_JOINED,
  582. from,
  583. member.nick,
  584. member.role,
  585. member.isHiddenDomain,
  586. member.statsID,
  587. member.status,
  588. member.identity,
  589. member.botType,
  590. member.jid,
  591. member.features,
  592. member.isReplaceParticipant,
  593. member.isSilent);
  594. // we are reporting the status with the join
  595. // so we do not want a second event about status update
  596. hasStatusUpdate = false;
  597. }
  598. } else {
  599. // Presence update for existing participant
  600. // Watch role change:
  601. const memberOfThis = this.members[from];
  602. if (memberOfThis.role !== member.role) {
  603. memberOfThis.role = member.role;
  604. this.eventEmitter.emit(
  605. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  606. }
  607. // affiliation changed
  608. if (memberOfThis.affiliation !== member.affiliation) {
  609. memberOfThis.affiliation = member.affiliation;
  610. }
  611. // fire event that botType had changed
  612. if (memberOfThis.botType !== member.botType) {
  613. memberOfThis.botType = member.botType;
  614. this.eventEmitter.emit(
  615. XMPPEvents.MUC_MEMBER_BOT_TYPE_CHANGED,
  616. from,
  617. member.botType);
  618. }
  619. if (member.isFocus) {
  620. // From time to time first few presences of the focus are not
  621. // containing it's jid. That way we can mark later the focus
  622. // member instead of not marking it at all and not starting the
  623. // conference.
  624. // FIXME: Maybe there is a better way to handle this issue. It
  625. // seems there is some period of time in prosody that the
  626. // configuration form is received but not applied. And if any
  627. // participant joins during that period of time the first
  628. // presence from the focus won't contain
  629. // <item jid="focus..." />.
  630. // By default we are disabling the waiting for form submission in order to use the room
  631. // and we had enabled by default that jids are public in the room ,
  632. // so this case should not happen, if public jid is turned off we will receive the jid
  633. // when we become moderator in the room
  634. memberOfThis.isFocus = true;
  635. this._initFocus(from, member.features);
  636. }
  637. // store the new display name
  638. if (member.displayName) {
  639. memberOfThis.displayName = member.displayName;
  640. }
  641. // join without audio
  642. if (member.isSilent) {
  643. memberOfThis.isSilent = member.isSilent;
  644. }
  645. // update stored status message to be able to detect changes
  646. if (memberOfThis.status !== member.status) {
  647. hasStatusUpdate = true;
  648. memberOfThis.status = member.status;
  649. }
  650. if (memberOfThis.version !== member.version) {
  651. hasVersionUpdate = true;
  652. memberOfThis.version = member.version;
  653. }
  654. if (!isEqual(memberOfThis.features, member.features)) {
  655. memberOfThis.features = member.features;
  656. this.eventEmitter.emit(XMPPEvents.PARTICIPANT_FEATURES_CHANGED, from, member.features);
  657. }
  658. }
  659. const participantProperties = new Map();
  660. // after we had fired member or room joined events, lets fire events
  661. // for the rest info we got in presence
  662. for (let i = 0; i < nodes.length; i++) {
  663. const node = nodes[i];
  664. switch (node.tagName) {
  665. case 'nick':
  666. if (!member.isFocus) {
  667. const displayName
  668. = this.xmpp.options.displayJids
  669. ? Strophe.getResourceFromJid(from)
  670. : member.nick;
  671. this.eventEmitter.emit(
  672. XMPPEvents.DISPLAY_NAME_CHANGED,
  673. from,
  674. displayName);
  675. }
  676. break;
  677. case 'silent':
  678. this.eventEmitter.emit(
  679. XMPPEvents.SILENT_STATUS_CHANGED,
  680. from,
  681. member.isSilent);
  682. break;
  683. case 'bridgeNotAvailable':
  684. if (member.isFocus && !this.noBridgeAvailable) {
  685. this.noBridgeAvailable = true;
  686. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  687. }
  688. break;
  689. case 'conference-properties':
  690. if (member.isFocus) {
  691. const properties = {};
  692. for (let j = 0; j < node.children.length; j++) {
  693. const { attributes } = node.children[j];
  694. if (attributes && attributes.key) {
  695. properties[attributes.key] = attributes.value;
  696. }
  697. }
  698. this.eventEmitter.emit(XMPPEvents.CONFERENCE_PROPERTIES_CHANGED, properties);
  699. }
  700. break;
  701. case 'transcription-status': {
  702. const { attributes } = node;
  703. if (!attributes) {
  704. break;
  705. }
  706. const { status } = attributes;
  707. if (status && status !== this.transcriptionStatus
  708. && member.isHiddenDomain && member.features.has(FEATURE_TRANSCRIBER)) {
  709. this.transcriptionStatus = status;
  710. this.eventEmitter.emit(
  711. XMPPEvents.TRANSCRIPTION_STATUS_CHANGED,
  712. status,
  713. Strophe.getResourceFromJid(from)
  714. );
  715. }
  716. break;
  717. }
  718. case 'call-control': {
  719. const att = node.attributes;
  720. if (!att) {
  721. break;
  722. }
  723. this.phoneNumber = att.phone || null;
  724. this.phonePin = att.pin || null;
  725. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  726. break;
  727. }
  728. default: {
  729. if (node.tagName.startsWith('jitsi_participant_')) {
  730. participantProperties
  731. .set(node.tagName.substring('jitsi_participant_'.length), node.value);
  732. } else {
  733. this.processNode(node, from);
  734. }
  735. }
  736. }
  737. }
  738. // All participant properties are in `participantProperties`, call the event handlers now.
  739. const participantId = Strophe.getResourceFromJid(from);
  740. for (const [ key, value ] of participantProperties) {
  741. this.participantPropertyListener(participantId, key, value);
  742. }
  743. // Trigger status message update if necessary
  744. if (hasStatusUpdate) {
  745. this.eventEmitter.emit(
  746. XMPPEvents.PRESENCE_STATUS,
  747. from,
  748. member.status);
  749. }
  750. if (hasVersionUpdate) {
  751. logger.info(`Received version for ${jid}: ${member.version}`);
  752. }
  753. }
  754. /**
  755. * Extracts the features from the presence.
  756. * @param node the node to process.
  757. * @return features the Set of features where extracted data is added.
  758. * @private
  759. */
  760. _extractFeatures(node) {
  761. const features = new Set();
  762. for (let j = 0; j < node.children.length; j++) {
  763. const { attributes } = node.children[j];
  764. if (attributes && attributes.var) {
  765. features.add(attributes.var);
  766. }
  767. }
  768. return features;
  769. }
  770. /**
  771. * Initialize some properties when the focus participant is verified.
  772. * @param from jid of the focus
  773. * @param features the features reported in jicofo presence
  774. */
  775. _initFocus(from, features) {
  776. this.focusMucJid = from;
  777. this.focusFeatures = features;
  778. }
  779. /**
  780. * Sets the special listener to be used for "command"s whose name starts
  781. * with "jitsi_participant_".
  782. */
  783. setParticipantPropertyListener(listener) {
  784. this.participantPropertyListener = listener;
  785. }
  786. /**
  787. *
  788. * @param node
  789. * @param from
  790. */
  791. processNode(node, from) {
  792. // make sure we catch all errors coming from any handler
  793. // otherwise we can remove the presence handler from strophe
  794. try {
  795. const tagHandlers = this.presHandlers[node.tagName] ?? [];
  796. tagHandlers.forEach(handler => {
  797. handler(node, Strophe.getResourceFromJid(from), from);
  798. });
  799. } catch (e) {
  800. logger.error(`Error processing:${node.tagName} node.`, e);
  801. }
  802. }
  803. /**
  804. * Send text message to the other participants in the conference
  805. * @param message
  806. * @param elementName
  807. */
  808. sendMessage(message, elementName) {
  809. const msg = $msg({ to: this.roomjid,
  810. type: 'groupchat' });
  811. // We are adding the message in a packet extension. If this element
  812. // is different from 'body', we add a custom namespace.
  813. // e.g. for 'json-message' extension of message stanza.
  814. if (elementName === 'body') {
  815. msg.c(elementName, {}, message);
  816. } else {
  817. msg.c(elementName, { xmlns: 'http://jitsi.org/jitmeet' }, message);
  818. }
  819. this.connection.send(msg);
  820. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, message);
  821. }
  822. /**
  823. * Sends a reaction message to the other participants in the conference.
  824. * @param {string} reaction - The reaction being sent.
  825. * @param {string} messageId - The id of the message being sent.
  826. * @param {string} receiverId - The receiver of the message if it is private.
  827. */
  828. sendReaction(reaction, messageId, receiverId) {
  829. // Adds the 'to' attribute depending on if the message is private or not.
  830. const msg = receiverId ? $msg({ to: `${this.roomjid}/${receiverId}`,
  831. type: 'chat' }) : $msg({ to: this.roomjid,
  832. type: 'groupchat' });
  833. msg.c('reactions', { id: messageId,
  834. xmlns: 'urn:xmpp:reactions:0' })
  835. .c('reaction', {}, reaction)
  836. .up().c('store', { xmlns: 'urn:xmpp:hints' });
  837. this.connection.send(msg);
  838. }
  839. /* eslint-disable max-params */
  840. /**
  841. * Send private text message to another participant of the conference
  842. * @param id id/muc resource of the receiver
  843. * @param message
  844. * @param elementName
  845. */
  846. sendPrivateMessage(id, message, elementName) {
  847. const msg = $msg({ to: `${this.roomjid}/${id}`,
  848. type: 'chat' });
  849. // We are adding the message in packet. If this element is different
  850. // from 'body', we add our custom namespace for the same.
  851. // e.g. for 'json-message' message extension.
  852. if (elementName === 'body') {
  853. msg.c(elementName, message).up();
  854. } else {
  855. msg.c(elementName, { xmlns: 'http://jitsi.org/jitmeet' }, message)
  856. .up();
  857. }
  858. this.connection.send(msg);
  859. this.eventEmitter.emit(
  860. XMPPEvents.SENDING_PRIVATE_CHAT_MESSAGE, message);
  861. }
  862. /* eslint-enable max-params */
  863. /**
  864. *
  865. * @param subject
  866. */
  867. setSubject(subject) {
  868. const valueToProcess = subject ? subject.trim() : subject;
  869. if (valueToProcess === this.subject) {
  870. // subject already set to the new value
  871. return;
  872. }
  873. const msg = $msg({ to: this.roomjid,
  874. type: 'groupchat' });
  875. msg.c('subject', valueToProcess);
  876. this.connection.send(msg);
  877. }
  878. /**
  879. *
  880. * @param pres
  881. * @param from
  882. */
  883. onPresenceUnavailable(pres, from) {
  884. // ignore presence
  885. if ($(pres).find('>ignore[xmlns="http://jitsi.org/jitmeet/"]').length) {
  886. return true;
  887. }
  888. // room destroyed ?
  889. const destroySelect = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>destroy');
  890. if (destroySelect.length) {
  891. let reason;
  892. const reasonSelect
  893. = $(pres).find(
  894. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  895. + '>destroy>reason');
  896. if (reasonSelect.length) {
  897. reason = reasonSelect.text();
  898. }
  899. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason, destroySelect.attr('jid'));
  900. this.connection.emuc.doLeave(this.roomjid);
  901. return true;
  902. }
  903. // Status code 110 indicates that this notification is "self-presence".
  904. const isSelfPresence
  905. = $(pres)
  906. .find(
  907. '>x[xmlns="http://jabber.org/protocol/muc#user"]>'
  908. + 'status[code="110"]')
  909. .length;
  910. const isKick
  911. = $(pres)
  912. .find(
  913. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  914. + '>status[code="307"]')
  915. .length;
  916. const membersKeys = Object.keys(this.members);
  917. const isReplaceParticipant = $(pres).find('flip_device').length;
  918. if (isKick) {
  919. const actorSelect
  920. = $(pres)
  921. .find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item>actor');
  922. let actorNick;
  923. if (actorSelect.length) {
  924. actorNick = actorSelect.attr('nick');
  925. }
  926. let reason;
  927. const reasonSelect
  928. = $(pres).find(
  929. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  930. + '>item>reason');
  931. if (reasonSelect.length) {
  932. reason = reasonSelect.text();
  933. }
  934. // we first fire the kicked so we can show the participant
  935. // who kicked, before notifying that participant left
  936. // we fire kicked for us and for any participant kicked
  937. this.eventEmitter.emit(
  938. XMPPEvents.KICKED,
  939. isSelfPresence,
  940. actorNick,
  941. Strophe.getResourceFromJid(from),
  942. reason,
  943. isReplaceParticipant);
  944. }
  945. if (isSelfPresence) {
  946. // If the status code is 110 this means we're leaving and we would
  947. // like to remove everyone else from our view, so we trigger the
  948. // event.
  949. membersKeys.forEach(jid => {
  950. const member = this.members[jid];
  951. delete this.members[jid];
  952. delete this.lastPresences[jid];
  953. if (!member.isFocus) {
  954. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  955. }
  956. });
  957. this.connection.emuc.doLeave(this.roomjid);
  958. // we fire muc_left only if this is not a kick,
  959. // kick has both statuses 110 and 307.
  960. if (!isKick) {
  961. this.eventEmitter.emit(XMPPEvents.MUC_LEFT);
  962. }
  963. } else {
  964. const reasonSelect = $(pres).find('>status');
  965. const member = this.members[from];
  966. let reason;
  967. if (reasonSelect.length) {
  968. reason = reasonSelect.text();
  969. }
  970. delete this.members[from];
  971. delete this.lastPresences[from];
  972. // In this case we *do* fire MUC_MEMBER_LEFT for the focus?
  973. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, from, reason);
  974. if (member && member.isHiddenDomain && member.features.has(FEATURE_TRANSCRIBER)
  975. && this.transcriptionStatus !== JitsiTranscriptionStatus.OFF) {
  976. this.transcriptionStatus = JitsiTranscriptionStatus.OFF;
  977. this.eventEmitter.emit(
  978. XMPPEvents.TRANSCRIPTION_STATUS_CHANGED,
  979. this.transcriptionStatus,
  980. Strophe.getResourceFromJid(from),
  981. true /* exited abruptly */
  982. );
  983. }
  984. if (member?.isFocus) {
  985. logger.info('Focus has left the room - leaving conference');
  986. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  987. }
  988. }
  989. }
  990. /**
  991. *
  992. * @param msg
  993. * @param from
  994. */
  995. onMessage(msg, from) {
  996. const type = msg.getAttribute('type');
  997. if (type === 'error') {
  998. const settingsErrorMsg = $(msg).find('>settings-error>text').text();
  999. if (settingsErrorMsg.length) {
  1000. this.eventEmitter.emit(XMPPEvents.SETTINGS_ERROR_RECEIVED, settingsErrorMsg);
  1001. return true;
  1002. }
  1003. const errorMsg = $(msg).find('>error>text').text();
  1004. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED, errorMsg);
  1005. return true;
  1006. }
  1007. const reactions = $(msg).find('>[xmlns="urn:xmpp:reactions:0"]>reaction');
  1008. if (reactions.length > 0) {
  1009. const messageId = $(msg).find('>[xmlns="urn:xmpp:reactions:0"]').attr('id');
  1010. const reactionList = [];
  1011. reactions.each((_, reactionElem) => {
  1012. const reaction = $(reactionElem).text();
  1013. reactionList.push(reaction);
  1014. });
  1015. this.eventEmitter.emit(XMPPEvents.REACTION_RECEIVED, from, reactionList, messageId);
  1016. return true;
  1017. }
  1018. const txt = $(msg).find('>body').text();
  1019. const subject = $(msg).find('>subject');
  1020. if (subject.length) {
  1021. const subjectText = subject.text();
  1022. if (subjectText || subjectText === '') {
  1023. this.subject = subjectText.trim();
  1024. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  1025. logger.log(`Subject is changed to ${subjectText}`);
  1026. }
  1027. }
  1028. // xep-0203 delay
  1029. let stamp = $(msg).find('>delay').attr('stamp');
  1030. if (!stamp) {
  1031. // or xep-0091 delay, UTC timestamp
  1032. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  1033. if (stamp) {
  1034. // the format is CCYYMMDDThh:mm:ss
  1035. const dateParts
  1036. = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  1037. stamp = `${dateParts[1]}-${dateParts[2]}-${dateParts[3]}Z`;
  1038. }
  1039. }
  1040. if (from === this.roomjid) {
  1041. let invite;
  1042. if ($(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="104"]').length) {
  1043. this.discoRoomInfo();
  1044. } else if ((invite = $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>invite'))
  1045. && invite.length) {
  1046. const passwordSelect = $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>password');
  1047. let password;
  1048. if (passwordSelect && passwordSelect.length) {
  1049. password = passwordSelect.text();
  1050. }
  1051. this.eventEmitter.emit(XMPPEvents.INVITE_MESSAGE_RECEIVED,
  1052. from, invite.attr('from'), txt, password);
  1053. }
  1054. }
  1055. const jsonMessage = $(msg).find('>json-message').text();
  1056. if (jsonMessage) {
  1057. const parsedJson = this.xmpp.tryParseJSONAndVerify(jsonMessage);
  1058. // We emit this event if the message is a valid json, and is not
  1059. // delivered after a delay, i.e. stamp is undefined.
  1060. // e.g. - subtitles should not be displayed if delayed.
  1061. if (parsedJson && stamp === undefined) {
  1062. this.eventEmitter.emit(XMPPEvents.JSON_MESSAGE_RECEIVED,
  1063. from, parsedJson);
  1064. return;
  1065. }
  1066. }
  1067. if (txt) {
  1068. const messageId = $(msg).attr('id') || uuidv4();
  1069. if (type === 'chat') {
  1070. this.eventEmitter.emit(XMPPEvents.PRIVATE_MESSAGE_RECEIVED,
  1071. from, txt, this.myroomjid, stamp, messageId);
  1072. } else if (type === 'groupchat') {
  1073. const nickEl = $(msg).find('>nick');
  1074. let nick;
  1075. if (nickEl.length > 0) {
  1076. nick = nickEl.text();
  1077. }
  1078. // we will fire explicitly that this is a guest(isGuest:true) to the conference
  1079. // informing that this is probably a message from a guest to the conference (visitor)
  1080. // a message with explicit name set
  1081. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  1082. from, txt, this.myroomjid, stamp, nick, Boolean(nick), messageId);
  1083. }
  1084. }
  1085. }
  1086. /**
  1087. *
  1088. * @param pres
  1089. * @param from
  1090. */
  1091. onPresenceError(pres, from) {
  1092. let errorDescriptionNode;
  1093. if (from === this.myroomjid) {
  1094. // we have tried to join, and we received an error, let's send again conference-iq on next attempt
  1095. // as it may turn out that jicofo left the room if we were the first to try,
  1096. // and the user delayed the attempt for entering the password or such
  1097. this.xmpp.moderator.conferenceRequestSent = false;
  1098. }
  1099. if ($(pres)
  1100. .find(
  1101. '>error[type="auth"]'
  1102. + '>not-authorized['
  1103. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  1104. .length) {
  1105. logger.log('on password required', from);
  1106. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  1107. } else if ($(pres)
  1108. .find(
  1109. '>error[type="cancel"]'
  1110. + '>not-allowed['
  1111. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  1112. .length) {
  1113. const toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  1114. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  1115. // enter the room by replying with 'not-authorized'. This would
  1116. // result in reconnection from authorized domain.
  1117. // We're either missing Jicofo/Prosody config for anonymous
  1118. // domains or something is wrong.
  1119. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR);
  1120. } else {
  1121. logger.warn('onPresError ', pres);
  1122. const txtNode = $(pres).find('>error[type="cancel"]>text[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]');
  1123. const txt = txtNode.length && txtNode.text();
  1124. let type = AUTH_ERROR_TYPES.GENERAL;
  1125. // a race where we have sent a conference request to jicofo and jicofo was about to leave or just left
  1126. // because of no participants in the room, and we tried to create the room, without having
  1127. // permissions for that (only jicofo creates rooms)
  1128. if (txt === 'Room creation is restricted') {
  1129. type = AUTH_ERROR_TYPES.ROOM_CREATION_RESTRICTION;
  1130. if (!this._roomCreationRetries) {
  1131. this._roomCreationRetries = 0;
  1132. }
  1133. this._roomCreationRetries++;
  1134. if (this._roomCreationRetries <= 3) {
  1135. const retryDelay = getJitterDelay(
  1136. /* retry */ this._roomCreationRetries,
  1137. /* minDelay */ 500,
  1138. 1.5);
  1139. // let's retry inviting jicofo and joining the room, retries will take between 1 and 3 seconds
  1140. setTimeout(() => this.join(this.password, this.replaceParticipant), retryDelay);
  1141. return;
  1142. }
  1143. } else if ($(pres).find(
  1144. '>error[type="cancel"]>no-main-participants[xmlns="jitsi:visitors"]').length > 0) {
  1145. type = AUTH_ERROR_TYPES.NO_MAIN_PARTICIPANTS;
  1146. } else if ($(pres).find(
  1147. '>error[type="cancel"]>promotion-not-allowed[xmlns="jitsi:visitors"]').length > 0) {
  1148. type = AUTH_ERROR_TYPES.PROMOTION_NOT_ALLOWED;
  1149. } else if ($(pres).find(
  1150. '>error[type="cancel"]>no-visitors-lobby[xmlns="jitsi:visitors"]').length > 0) {
  1151. type = AUTH_ERROR_TYPES.NO_VISITORS_LOBBY;
  1152. }
  1153. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_NOT_ALLOWED_ERROR, type, txt);
  1154. }
  1155. } else if ($(pres).find('>error>service-unavailable').length) {
  1156. logger.warn('Maximum users limit for the room has been reached',
  1157. pres);
  1158. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR);
  1159. } else if ($(pres)
  1160. .find(
  1161. '>error[type="auth"]'
  1162. + '>registration-required['
  1163. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  1164. // let's extract the lobby jid from the custom field
  1165. const lobbyRoomNode = $(pres).find('>error[type="auth"]>lobbyroom');
  1166. let lobbyRoomJid;
  1167. if (lobbyRoomNode.length) {
  1168. lobbyRoomJid = lobbyRoomNode.text();
  1169. }
  1170. const waitingForHost = $(pres).find('>error[type="auth"]>waiting-for-host').length > 0;
  1171. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_MEMBERS_ONLY_ERROR, lobbyRoomJid, waitingForHost);
  1172. } else if ((errorDescriptionNode = $(pres).find(
  1173. '>error[type="modify"]>displayname-required[xmlns="http://jitsi.org/jitmeet"]')).length) {
  1174. logger.warn('display name required ', pres);
  1175. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_REQUIRED, errorDescriptionNode[0].attributes.lobby?.value);
  1176. } else {
  1177. logger.warn('onPresError ', pres);
  1178. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR);
  1179. }
  1180. }
  1181. /**
  1182. *
  1183. * @param jid
  1184. * @param affiliation
  1185. */
  1186. setAffiliation(jid, affiliation) {
  1187. const grantIQ = $iq({
  1188. to: this.roomjid,
  1189. type: 'set'
  1190. })
  1191. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  1192. .c('item', {
  1193. affiliation,
  1194. jid: Strophe.getBareJidFromJid(jid)
  1195. })
  1196. .c('reason').t(`Your affiliation has been changed to '${affiliation}'.`)
  1197. .up().up().up();
  1198. this.connection.sendIQ(
  1199. grantIQ,
  1200. result => logger.log('Set affiliation of participant with jid: ', jid, 'to', affiliation, result),
  1201. error => logger.log('Set affiliation of participant error: ', error));
  1202. }
  1203. /**
  1204. *
  1205. * @param jid
  1206. * @param reason
  1207. */
  1208. kick(jid, reason = 'You have been kicked.') {
  1209. const kickIQ = $iq({ to: this.roomjid,
  1210. type: 'set' })
  1211. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  1212. .c('item', { nick: Strophe.getResourceFromJid(jid),
  1213. role: 'none' })
  1214. .c('reason').t(reason).up().up().up();
  1215. this.connection.sendIQ(
  1216. kickIQ,
  1217. result => logger.log('Kick participant with jid: ', jid, result),
  1218. error => logger.log('Kick participant error: ', error));
  1219. }
  1220. /* eslint-disable max-params */
  1221. /**
  1222. *
  1223. * @param key
  1224. * @param onSuccess
  1225. * @param onError
  1226. * @param onNotSupported
  1227. */
  1228. lockRoom(key, onSuccess, onError, onNotSupported) {
  1229. // http://xmpp.org/extensions/xep-0045.html#roomconfig
  1230. this.connection.sendIQ(
  1231. $iq({
  1232. to: this.roomjid,
  1233. type: 'get'
  1234. })
  1235. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  1236. res => {
  1237. if ($(res)
  1238. .find(
  1239. '>query>x[xmlns="jabber:x:data"]'
  1240. + '>field[var="muc#roomconfig_roomsecret"]')
  1241. .length) {
  1242. const formsubmit
  1243. = $iq({
  1244. to: this.roomjid,
  1245. type: 'set'
  1246. })
  1247. .c('query', {
  1248. xmlns: 'http://jabber.org/protocol/muc#owner'
  1249. });
  1250. formsubmit.c('x', {
  1251. xmlns: 'jabber:x:data',
  1252. type: 'submit'
  1253. });
  1254. formsubmit
  1255. .c('field', { 'var': 'FORM_TYPE' })
  1256. .c('value')
  1257. .t('http://jabber.org/protocol/muc#roomconfig')
  1258. .up()
  1259. .up();
  1260. formsubmit
  1261. .c('field', { 'var': 'muc#roomconfig_roomsecret' })
  1262. .c('value')
  1263. .t(key)
  1264. .up()
  1265. .up();
  1266. formsubmit
  1267. .c('field',
  1268. { 'var': 'muc#roomconfig_passwordprotectedroom' })
  1269. .c('value')
  1270. .t(key === null || key.length === 0 ? '0' : '1')
  1271. .up()
  1272. .up();
  1273. // if members only enabled
  1274. if (this.membersOnlyEnabled) {
  1275. formsubmit
  1276. .c('field', { 'var': 'muc#roomconfig_membersonly' })
  1277. .c('value')
  1278. .t('true')
  1279. .up()
  1280. .up();
  1281. }
  1282. // Fixes a bug in prosody 0.9.+
  1283. // https://prosody.im/issues/issue/373
  1284. formsubmit
  1285. .c('field', { 'var': 'muc#roomconfig_whois' })
  1286. .c('value')
  1287. .t('anyone')
  1288. .up()
  1289. .up();
  1290. this.connection.sendIQ(
  1291. formsubmit,
  1292. () => {
  1293. // we set the password in chat room so we can use it
  1294. // later when dialing out
  1295. this.password = key;
  1296. onSuccess();
  1297. },
  1298. onError);
  1299. } else {
  1300. onNotSupported();
  1301. }
  1302. },
  1303. onError);
  1304. }
  1305. /* eslint-enable max-params */
  1306. /**
  1307. * Turns off or on the members only config for the main room.
  1308. *
  1309. * @param {boolean} enabled - Whether to turn it on or off.
  1310. * @param onSuccess - optional callback.
  1311. * @param onError - optional callback.
  1312. */
  1313. setMembersOnly(enabled, onSuccess, onError) {
  1314. if (enabled && Object.values(this.members).filter(m => !m.isFocus).length) {
  1315. // first grant membership to all that are in the room
  1316. const affiliationsIq = $iq({
  1317. to: this.roomjid,
  1318. type: 'set' })
  1319. .c('query', {
  1320. xmlns: 'http://jabber.org/protocol/muc#admin' });
  1321. let sendIq = false;
  1322. Object.values(this.members).forEach(m => {
  1323. if (m.jid && !MEMBERS_AFFILIATIONS.includes(m.affiliation)) {
  1324. affiliationsIq.c('item', {
  1325. 'affiliation': 'member',
  1326. 'jid': Strophe.getBareJidFromJid(m.jid)
  1327. }).up();
  1328. sendIq = true;
  1329. }
  1330. });
  1331. sendIq && this.xmpp.connection.sendIQ(affiliationsIq.up());
  1332. }
  1333. const errorCallback = onError ? onError : () => {}; // eslint-disable-line no-empty-function
  1334. this.xmpp.connection.sendIQ(
  1335. $iq({
  1336. to: this.roomjid,
  1337. type: 'get'
  1338. }).c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  1339. res => {
  1340. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_membersonly"]').length) {
  1341. const formToSubmit
  1342. = $iq({
  1343. to: this.roomjid,
  1344. type: 'set'
  1345. }).c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' });
  1346. formToSubmit.c('x', {
  1347. xmlns: 'jabber:x:data',
  1348. type: 'submit'
  1349. });
  1350. formToSubmit
  1351. .c('field', { 'var': 'FORM_TYPE' })
  1352. .c('value')
  1353. .t('http://jabber.org/protocol/muc#roomconfig')
  1354. .up()
  1355. .up();
  1356. formToSubmit
  1357. .c('field', { 'var': 'muc#roomconfig_membersonly' })
  1358. .c('value')
  1359. .t(enabled ? 'true' : 'false')
  1360. .up()
  1361. .up();
  1362. // if room is locked from other participant or we are locking it
  1363. if (this.locked) {
  1364. formToSubmit
  1365. .c('field',
  1366. { 'var': 'muc#roomconfig_passwordprotectedroom' })
  1367. .c('value')
  1368. .t('1')
  1369. .up()
  1370. .up();
  1371. }
  1372. this.xmpp.connection.sendIQ(formToSubmit, onSuccess, errorCallback);
  1373. } else {
  1374. errorCallback(new Error('Setting members only room not supported!'));
  1375. }
  1376. },
  1377. errorCallback);
  1378. }
  1379. /**
  1380. * Adds the key to the presence map, overriding any previous value.
  1381. * This method is used by jibri.
  1382. *
  1383. * @param key The key to add or replace.
  1384. * @param values The new values.
  1385. * @returns {boolean|null} <tt>true</tt> if the operation succeeded or <tt>false</tt> when no add or replce was
  1386. * performed as the value was already there.
  1387. * @deprecated Use 'addOrReplaceInPresence' instead. TODO: remove it from here and jibri.
  1388. */
  1389. addToPresence(key, values) {
  1390. return this.addOrReplaceInPresence(key, values);
  1391. }
  1392. /**
  1393. * Adds the key to the presence map, overriding any previous value.
  1394. * @param key The key to add or replace.
  1395. * @param values The new values.
  1396. * @returns {boolean|null} <tt>true</tt> if the operation succeeded or <tt>false</tt> when no add or replace was
  1397. * performed as the value was already there.
  1398. */
  1399. addOrReplaceInPresence(key, values) {
  1400. values.tagName = key;
  1401. const matchingNodes = this.presMap.nodes.filter(node => key === node.tagName);
  1402. // if we have found just one, let's check is it the same
  1403. if (matchingNodes.length === 1 && isEqual(matchingNodes[0], values)) {
  1404. return false;
  1405. }
  1406. this.removeFromPresence(key);
  1407. this.presMap.nodes.push(values);
  1408. this.presenceUpdateTime = Date.now();
  1409. return true;
  1410. }
  1411. /**
  1412. * Retrieves a value from the presence map.
  1413. *
  1414. * @param {string} key - The key to find the value for.
  1415. * @returns {Object?}
  1416. */
  1417. getFromPresence(key) {
  1418. return this.presMap.nodes.find(node => key === node.tagName);
  1419. }
  1420. /**
  1421. * Removes a key from the presence map.
  1422. * @param key
  1423. */
  1424. removeFromPresence(key) {
  1425. const nodes = this.presMap.nodes.filter(node => key !== node.tagName);
  1426. this.presMap.nodes = nodes;
  1427. this.presenceUpdateTime = Date.now();
  1428. }
  1429. /**
  1430. *
  1431. * @param name
  1432. * @param handler
  1433. */
  1434. addPresenceListener(name, handler) {
  1435. if (typeof handler !== 'function') {
  1436. throw new Error('"handler" is not a function');
  1437. }
  1438. let tagHandlers = this.presHandlers[name];
  1439. if (!tagHandlers) {
  1440. this.presHandlers[name] = tagHandlers = [];
  1441. }
  1442. if (tagHandlers.indexOf(handler) === -1) {
  1443. tagHandlers.push(handler);
  1444. } else {
  1445. logger.warn(
  1446. `Trying to add the same handler more than once for: ${name}`);
  1447. }
  1448. }
  1449. /**
  1450. *
  1451. * @param name
  1452. * @param handler
  1453. */
  1454. removePresenceListener(name, handler) {
  1455. const tagHandlers = this.presHandlers[name];
  1456. const handlerIdx = tagHandlers ? tagHandlers.indexOf(handler) : -1;
  1457. // eslint-disable-next-line no-negated-condition
  1458. if (handlerIdx !== -1) {
  1459. tagHandlers.splice(handlerIdx, 1);
  1460. } else {
  1461. logger.warn(`Handler for: ${name} was not registered`);
  1462. }
  1463. }
  1464. /**
  1465. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1466. * focus.
  1467. * @param mucJid the full MUC address of the user to be checked.
  1468. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus
  1469. * or <tt>false</tt> if is not. When given <tt>mucJid</tt> does not exist in
  1470. * the MUC then <tt>null</tt> is returned.
  1471. */
  1472. isFocus(mucJid) {
  1473. const member = this.members[mucJid];
  1474. if (member) {
  1475. return member.isFocus;
  1476. }
  1477. return null;
  1478. }
  1479. /**
  1480. *
  1481. */
  1482. isModerator() {
  1483. return this.role === 'moderator';
  1484. }
  1485. /**
  1486. * Obtains the info about given media advertised (in legacy format) in the MUC presence of the participant
  1487. * identified by the given endpoint JID. This is for mantining interop with endpoints that do not support
  1488. * source-name signaling (Jigasi and very old mobile clients).
  1489. *
  1490. * @param {string} endpointId the endpoint ID mapped to the participant which corresponds to MUC nickname.
  1491. * @param {MediaType} mediaType the type of the media for which presence info will be obtained.
  1492. * @return {PeerMediaInfo} presenceInfo an object with media presence info or <tt>null</tt> either if there
  1493. * is no presence available or if the media type given is invalid.
  1494. */
  1495. getMediaPresenceInfo(endpointId, mediaType) {
  1496. // Will figure out current muted status by looking up owner's presence
  1497. const pres = this.lastPresences[`${this.roomjid}/${endpointId}`];
  1498. if (!pres) {
  1499. // No presence available
  1500. return null;
  1501. }
  1502. const data = {
  1503. muted: true, // muted by default
  1504. videoType: mediaType === MediaType.VIDEO ? VideoType.CAMERA : undefined // 'camera' by default
  1505. };
  1506. let mutedNode = null;
  1507. if (mediaType === MediaType.AUDIO) {
  1508. mutedNode = filterNodeFromPresenceJSON(pres, 'audiomuted');
  1509. } else if (mediaType === MediaType.VIDEO) {
  1510. mutedNode = filterNodeFromPresenceJSON(pres, 'videomuted');
  1511. const codecTypeNode = filterNodeFromPresenceJSON(pres, 'jitsi_participant_codecType');
  1512. const videoTypeNode = filterNodeFromPresenceJSON(pres, 'videoType');
  1513. if (videoTypeNode.length > 0) {
  1514. data.videoType = videoTypeNode[0].value;
  1515. }
  1516. if (codecTypeNode.length > 0) {
  1517. data.codecType = codecTypeNode[0].value;
  1518. }
  1519. } else {
  1520. logger.error(`Unsupported media type: ${mediaType}`);
  1521. return null;
  1522. }
  1523. if (mutedNode.length > 0) {
  1524. data.muted = mutedNode[0].value === 'true';
  1525. }
  1526. return data;
  1527. }
  1528. /**
  1529. *
  1530. * @param peerJid
  1531. */
  1532. getMemberRole(peerJid) {
  1533. if (this.members[peerJid]) {
  1534. return this.members[peerJid].role;
  1535. }
  1536. return null;
  1537. }
  1538. /**
  1539. * Returns the last presence advertised by a MUC member.
  1540. * @param {string} mucNick
  1541. * @returns {*}
  1542. */
  1543. getLastPresence(mucNick) {
  1544. return this.lastPresences[`${this.roomjid}/${mucNick}`];
  1545. }
  1546. /**
  1547. * Dials a number.
  1548. * @param number the number
  1549. */
  1550. dial(number) {
  1551. return this.connection.rayo.dial(number, 'fromnumber',
  1552. Strophe.getBareJidFromJid(this.myroomjid), this.password,
  1553. this.focusMucJid);
  1554. }
  1555. /**
  1556. * Hangup an existing call
  1557. */
  1558. hangup() {
  1559. return this.connection.rayo.hangup();
  1560. }
  1561. /**
  1562. *
  1563. * @returns {Lobby}
  1564. */
  1565. getLobby() {
  1566. return this.lobby;
  1567. }
  1568. /**
  1569. * @returns {AVModeration}
  1570. */
  1571. getAVModeration() {
  1572. return this.avModeration;
  1573. }
  1574. /**
  1575. * @returns {BreakoutRooms}
  1576. */
  1577. getBreakoutRooms() {
  1578. return this.breakoutRooms;
  1579. }
  1580. /**
  1581. * @returns {RoomMetadata}
  1582. */
  1583. getMetadataHandler() {
  1584. return this.roomMetadata;
  1585. }
  1586. /**
  1587. * Returns the phone number for joining the conference.
  1588. */
  1589. getPhoneNumber() {
  1590. return this.phoneNumber;
  1591. }
  1592. /**
  1593. * Returns the pin for joining the conference with phone.
  1594. */
  1595. getPhonePin() {
  1596. return this.phonePin;
  1597. }
  1598. /**
  1599. * Returns the meeting unique ID if any came from backend.
  1600. *
  1601. * @returns {string} - The meeting ID.
  1602. */
  1603. getMeetingId() {
  1604. return this.meetingId;
  1605. }
  1606. /**
  1607. * Mutes remote participant.
  1608. * @param jid of the participant
  1609. * @param mute
  1610. * @param mediaType
  1611. */
  1612. muteParticipant(jid, mute, mediaType) {
  1613. logger.info('set mute', mute, jid);
  1614. const iqToFocus = $iq(
  1615. { to: this.focusMucJid,
  1616. type: 'set' })
  1617. .c('mute', {
  1618. xmlns: `http://jitsi.org/jitmeet/${mediaType}`,
  1619. jid
  1620. })
  1621. .t(mute.toString())
  1622. .up();
  1623. this.connection.sendIQ(
  1624. iqToFocus,
  1625. result => logger.log('set mute', result),
  1626. error => logger.log('set mute error', error));
  1627. }
  1628. /**
  1629. * TODO: Document
  1630. * @param iq
  1631. */
  1632. onMute(iq) {
  1633. const from = iq.getAttribute('from');
  1634. if (from !== this.focusMucJid) {
  1635. logger.warn('Ignored mute from non focus peer');
  1636. return;
  1637. }
  1638. const mute = $(iq).find('mute');
  1639. if (mute.length && mute.text() === 'true') {
  1640. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, mute.attr('actor'));
  1641. } else {
  1642. // XXX Why do we support anything but muting? Why do we encode the
  1643. // value in the text of the element? Why do we use a separate XML
  1644. // namespace?
  1645. logger.warn('Ignoring a mute request which does not explicitly '
  1646. + 'specify a positive mute command.');
  1647. }
  1648. }
  1649. /**
  1650. * TODO: Document
  1651. * @param iq
  1652. */
  1653. onMuteVideo(iq) {
  1654. const from = iq.getAttribute('from');
  1655. if (from !== this.focusMucJid) {
  1656. logger.warn('Ignored mute from non focus peer');
  1657. return;
  1658. }
  1659. const mute = $(iq).find('mute');
  1660. if (mute.length && mute.text() === 'true') {
  1661. this.eventEmitter.emit(XMPPEvents.VIDEO_MUTED_BY_FOCUS, mute.attr('actor'));
  1662. } else {
  1663. // XXX Why do we support anything but muting? Why do we encode the
  1664. // value in the text of the element? Why do we use a separate XML
  1665. // namespace?
  1666. logger.warn('Ignoring a mute request which does not explicitly '
  1667. + 'specify a positive mute command.');
  1668. }
  1669. }
  1670. /**
  1671. * Clean any listeners or resources, executed on leaving.
  1672. */
  1673. clean() {
  1674. this._removeConnListeners.forEach(remove => remove());
  1675. this._removeConnListeners = [];
  1676. this.eventsForwarder.removeListeners(
  1677. AuthenticationEvents.IDENTITY_UPDATED,
  1678. XMPPEvents.AUTHENTICATION_REQUIRED,
  1679. XMPPEvents.FOCUS_DISCONNECTED,
  1680. XMPPEvents.RESERVATION_ERROR);
  1681. this.joined = false;
  1682. this.inProgressEmitted = false;
  1683. }
  1684. /**
  1685. * Leaves the room. Closes the jingle session.
  1686. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received
  1687. * less than 5s after sending presence unavailable. Otherwise the promise is
  1688. * rejected.
  1689. */
  1690. leave(reason) {
  1691. this.avModeration.dispose();
  1692. this.breakoutRooms.dispose();
  1693. this.roomMetadata.dispose();
  1694. const promises = [];
  1695. this.lobby?.lobbyRoom && promises.push(this.lobby.leave());
  1696. promises.push(new Promise((resolve, reject) => {
  1697. let timeout = -1;
  1698. const onMucLeft = (doReject = false) => {
  1699. this.eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1700. clearTimeout(timeout);
  1701. // This will reset the joined flag to false. If we reset it earlier any self presence will be
  1702. // interpreted as muc join. That's why we reset the flag once we have received presence unavalable
  1703. // (MUC_LEFT).
  1704. this.clean();
  1705. if (doReject) {
  1706. // The timeout expired. Make sure we clean the EMUC state.
  1707. this.connection.emuc.doLeave(this.roomjid);
  1708. reject(new Error('The timeout for the confirmation about leaving the room expired.'));
  1709. } else {
  1710. resolve();
  1711. }
  1712. };
  1713. if (this.joined) {
  1714. timeout = setTimeout(() => onMucLeft(true), 5000);
  1715. this.eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  1716. this.doLeave(reason);
  1717. } else {
  1718. // we are clearing up, and we haven't joined the room
  1719. // there is no point of sending presence unavailable and check for timeout
  1720. // let's just clean
  1721. this.connection.emuc.doLeave(this.roomjid);
  1722. this.clean();
  1723. resolve();
  1724. }
  1725. }));
  1726. return Promise.allSettled(promises);
  1727. }
  1728. /**
  1729. * Ends the conference for all participants.
  1730. */
  1731. end() {
  1732. if (this.breakoutRooms.isBreakoutRoom()) {
  1733. logger.warn('Cannot end conference: this is a breakout room.');
  1734. return;
  1735. }
  1736. // Send the end conference message.
  1737. const msg = $msg({ to: this.xmpp.endConferenceComponentAddress });
  1738. msg.c('end_conference').up();
  1739. this.xmpp.connection.send(msg);
  1740. }
  1741. }
  1742. /* eslint-enable newline-per-chained-call */