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

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