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

ChatRoom.js 72KB

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