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

ChatRoom.js 59KB

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