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.

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