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.

ChatRoom.js 65KB

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