Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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