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

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