Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

ChatRoom.js 61KB

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