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

ChatRoom.js 70KB

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