You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ChatRoom.js 59KB

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