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 61KB

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