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.

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