Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ChatRoom.js 69KB

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