Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ChatRoom.js 58KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798
  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. // we first fire the kicked so we can show the participant
  842. // who kicked, before notifying that participant left
  843. // we fire kicked for us and for any participant kicked
  844. this.eventEmitter.emit(
  845. XMPPEvents.KICKED,
  846. isSelfPresence,
  847. actorNick,
  848. Strophe.getResourceFromJid(from));
  849. }
  850. if (isSelfPresence) {
  851. // If the status code is 110 this means we're leaving and we would
  852. // like to remove everyone else from our view, so we trigger the
  853. // event.
  854. membersKeys.forEach(jid => {
  855. const member = this.members[jid];
  856. delete this.members[jid];
  857. this.onParticipantLeft(jid, member.isFocus);
  858. });
  859. this.connection.emuc.doLeave(this.roomjid);
  860. // we fire muc_left only if this is not a kick,
  861. // kick has both statuses 110 and 307.
  862. if (!isKick) {
  863. this.eventEmitter.emit(XMPPEvents.MUC_LEFT);
  864. }
  865. } else {
  866. delete this.members[from];
  867. this.onParticipantLeft(from, false);
  868. }
  869. }
  870. /**
  871. *
  872. * @param msg
  873. * @param from
  874. */
  875. onMessage(msg, from) {
  876. const nick
  877. = $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  878. .text()
  879. || Strophe.getResourceFromJid(from);
  880. const type = msg.getAttribute('type');
  881. if (type === 'error') {
  882. const errorMsg = $(msg).find('>error>text').text();
  883. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED, errorMsg);
  884. return true;
  885. }
  886. const txt = $(msg).find('>body').text();
  887. const subject = $(msg).find('>subject');
  888. if (subject.length) {
  889. const subjectText = subject.text();
  890. if (subjectText || subjectText === '') {
  891. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  892. logger.log(`Subject is changed to ${subjectText}`);
  893. }
  894. }
  895. // xep-0203 delay
  896. let stamp = $(msg).find('>delay').attr('stamp');
  897. if (!stamp) {
  898. // or xep-0091 delay, UTC timestamp
  899. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  900. if (stamp) {
  901. // the format is CCYYMMDDThh:mm:ss
  902. const dateParts
  903. = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  904. stamp = `${dateParts[1]}-${dateParts[2]}-${dateParts[3]}Z`;
  905. }
  906. }
  907. if (from === this.roomjid) {
  908. let invite;
  909. if ($(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="104"]').length) {
  910. this.discoRoomInfo();
  911. } else if ((invite = $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>invite'))
  912. && invite.length) {
  913. const passwordSelect = $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>password');
  914. let password;
  915. if (passwordSelect && passwordSelect.length) {
  916. password = passwordSelect.text();
  917. }
  918. this.eventEmitter.emit(XMPPEvents.INVITE_MESSAGE_RECEIVED,
  919. from, invite.attr('from'), txt, password);
  920. }
  921. }
  922. const jsonMessage = $(msg).find('>json-message').text();
  923. if (jsonMessage) {
  924. const parsedJson = this.xmpp.tryParseJSONAndVerify(jsonMessage);
  925. // We emit this event if the message is a valid json, and is not
  926. // delivered after a delay, i.e. stamp is undefined.
  927. // e.g. - subtitles should not be displayed if delayed.
  928. if (parsedJson && stamp === undefined) {
  929. this.eventEmitter.emit(XMPPEvents.JSON_MESSAGE_RECEIVED,
  930. from, parsedJson);
  931. return;
  932. }
  933. }
  934. if (txt) {
  935. if (type === 'chat') {
  936. this.eventEmitter.emit(XMPPEvents.PRIVATE_MESSAGE_RECEIVED,
  937. from, nick, txt, this.myroomjid, stamp);
  938. } else if (type === 'groupchat') {
  939. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  940. from, nick, txt, this.myroomjid, stamp);
  941. }
  942. }
  943. }
  944. /**
  945. *
  946. * @param pres
  947. * @param from
  948. */
  949. onPresenceError(pres, from) {
  950. if ($(pres)
  951. .find(
  952. '>error[type="auth"]'
  953. + '>not-authorized['
  954. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  955. .length) {
  956. logger.log('on password required', from);
  957. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  958. } else if ($(pres)
  959. .find(
  960. '>error[type="cancel"]'
  961. + '>not-allowed['
  962. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  963. .length) {
  964. const toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  965. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  966. // enter the room by replying with 'not-authorized'. This would
  967. // result in reconnection from authorized domain.
  968. // We're either missing Jicofo/Prosody config for anonymous
  969. // domains or something is wrong.
  970. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR);
  971. } else {
  972. logger.warn('onPresError ', pres);
  973. this.eventEmitter.emit(
  974. XMPPEvents.ROOM_CONNECT_NOT_ALLOWED_ERROR);
  975. }
  976. } else if ($(pres).find('>error>service-unavailable').length) {
  977. logger.warn('Maximum users limit for the room has been reached',
  978. pres);
  979. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR);
  980. } else if ($(pres)
  981. .find(
  982. '>error[type="auth"]'
  983. + '>registration-required['
  984. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  985. // let's extract the lobby jid from the custom field
  986. const lobbyRoomNode = $(pres).find('>lobbyroom');
  987. let lobbyRoomJid;
  988. if (lobbyRoomNode.length) {
  989. lobbyRoomJid = lobbyRoomNode.text();
  990. }
  991. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_MEMBERS_ONLY_ERROR, lobbyRoomJid);
  992. } else {
  993. logger.warn('onPresError ', pres);
  994. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR);
  995. }
  996. }
  997. /**
  998. *
  999. * @param jid
  1000. * @param affiliation
  1001. */
  1002. setAffiliation(jid, affiliation) {
  1003. const grantIQ = $iq({
  1004. to: this.roomjid,
  1005. type: 'set'
  1006. })
  1007. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  1008. .c('item', {
  1009. affiliation,
  1010. nick: Strophe.getResourceFromJid(jid)
  1011. })
  1012. .c('reason').t(`Your affiliation has been changed to '${affiliation}'.`)
  1013. .up().up().up();
  1014. this.connection.sendIQ(
  1015. grantIQ,
  1016. result => logger.log('Set affiliation of participant with jid: ', jid, 'to', affiliation, result),
  1017. error => logger.log('Set affiliation of participant error: ', error));
  1018. }
  1019. /**
  1020. *
  1021. * @param jid
  1022. */
  1023. kick(jid) {
  1024. const kickIQ = $iq({ to: this.roomjid,
  1025. type: 'set' })
  1026. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  1027. .c('item', { nick: Strophe.getResourceFromJid(jid),
  1028. role: 'none' })
  1029. .c('reason').t('You have been kicked.').up().up().up();
  1030. this.connection.sendIQ(
  1031. kickIQ,
  1032. result => logger.log('Kick participant with jid: ', jid, result),
  1033. error => logger.log('Kick participant error: ', error));
  1034. }
  1035. /* eslint-disable max-params */
  1036. /**
  1037. *
  1038. * @param key
  1039. * @param onSuccess
  1040. * @param onError
  1041. * @param onNotSupported
  1042. */
  1043. lockRoom(key, onSuccess, onError, onNotSupported) {
  1044. // http://xmpp.org/extensions/xep-0045.html#roomconfig
  1045. this.connection.sendIQ(
  1046. $iq({
  1047. to: this.roomjid,
  1048. type: 'get'
  1049. })
  1050. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  1051. res => {
  1052. if ($(res)
  1053. .find(
  1054. '>query>x[xmlns="jabber:x:data"]'
  1055. + '>field[var="muc#roomconfig_roomsecret"]')
  1056. .length) {
  1057. const formsubmit
  1058. = $iq({
  1059. to: this.roomjid,
  1060. type: 'set'
  1061. })
  1062. .c('query', {
  1063. xmlns: 'http://jabber.org/protocol/muc#owner'
  1064. });
  1065. formsubmit.c('x', {
  1066. xmlns: 'jabber:x:data',
  1067. type: 'submit'
  1068. });
  1069. formsubmit
  1070. .c('field', { 'var': 'FORM_TYPE' })
  1071. .c('value')
  1072. .t('http://jabber.org/protocol/muc#roomconfig')
  1073. .up()
  1074. .up();
  1075. formsubmit
  1076. .c('field', { 'var': 'muc#roomconfig_roomsecret' })
  1077. .c('value')
  1078. .t(key)
  1079. .up()
  1080. .up();
  1081. formsubmit
  1082. .c('field',
  1083. { 'var': 'muc#roomconfig_passwordprotectedroom' })
  1084. .c('value')
  1085. .t(key === null || key.length === 0 ? '0' : '1')
  1086. .up()
  1087. .up();
  1088. // if members only enabled
  1089. if (this.membersOnlyEnabled) {
  1090. formsubmit
  1091. .c('field', { 'var': 'muc#roomconfig_membersonly' })
  1092. .c('value')
  1093. .t('true')
  1094. .up()
  1095. .up();
  1096. }
  1097. // Fixes a bug in prosody 0.9.+
  1098. // https://prosody.im/issues/issue/373
  1099. formsubmit
  1100. .c('field', { 'var': 'muc#roomconfig_whois' })
  1101. .c('value')
  1102. .t('anyone')
  1103. .up()
  1104. .up();
  1105. this.connection.sendIQ(formsubmit, onSuccess, onError);
  1106. } else {
  1107. onNotSupported();
  1108. }
  1109. },
  1110. onError);
  1111. }
  1112. /* eslint-enable max-params */
  1113. /**
  1114. * Turns off or on the members only config for the main room.
  1115. *
  1116. * @param {boolean} enabled - Whether to turn it on or off.
  1117. * @param onSuccess - optional callback.
  1118. * @param onError - optional callback.
  1119. */
  1120. setMembersOnly(enabled, onSuccess, onError) {
  1121. if (enabled && Object.values(this.members).filter(m => !m.isFocus).length) {
  1122. // first grant membership to all that are in the room
  1123. // currently there is a bug in prosody where it handles only the first item
  1124. // that's why we will send iq per member
  1125. Object.values(this.members).forEach(m => {
  1126. if (m.jid && !MEMBERS_AFFILIATIONS.includes(m.affiliation)) {
  1127. this.xmpp.connection.sendIQ(
  1128. $iq({
  1129. to: this.roomjid,
  1130. type: 'set' })
  1131. .c('query', {
  1132. xmlns: 'http://jabber.org/protocol/muc#admin' })
  1133. .c('item', {
  1134. 'affiliation': 'member',
  1135. 'jid': m.jid
  1136. }).up().up());
  1137. }
  1138. });
  1139. }
  1140. const errorCallback = onError ? onError : () => {}; // eslint-disable-line no-empty-function
  1141. this.xmpp.connection.sendIQ(
  1142. $iq({
  1143. to: this.roomjid,
  1144. type: 'get'
  1145. }).c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  1146. res => {
  1147. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_membersonly"]').length) {
  1148. const formToSubmit
  1149. = $iq({
  1150. to: this.roomjid,
  1151. type: 'set'
  1152. }).c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' });
  1153. formToSubmit.c('x', {
  1154. xmlns: 'jabber:x:data',
  1155. type: 'submit'
  1156. });
  1157. formToSubmit
  1158. .c('field', { 'var': 'FORM_TYPE' })
  1159. .c('value')
  1160. .t('http://jabber.org/protocol/muc#roomconfig')
  1161. .up()
  1162. .up();
  1163. formToSubmit
  1164. .c('field', { 'var': 'muc#roomconfig_membersonly' })
  1165. .c('value')
  1166. .t(enabled ? 'true' : 'false')
  1167. .up()
  1168. .up();
  1169. // if room is locked from other participant or we are locking it
  1170. if (this.locked) {
  1171. formToSubmit
  1172. .c('field',
  1173. { 'var': 'muc#roomconfig_passwordprotectedroom' })
  1174. .c('value')
  1175. .t('1')
  1176. .up()
  1177. .up();
  1178. }
  1179. this.xmpp.connection.sendIQ(formToSubmit, onSuccess, errorCallback);
  1180. } else {
  1181. errorCallback(new Error('Setting members only room not supported!'));
  1182. }
  1183. },
  1184. errorCallback);
  1185. }
  1186. /**
  1187. * Adds the key to the presence map, overriding any previous value.
  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. */
  1193. addOrReplaceInPresence(key, values) {
  1194. values.tagName = key;
  1195. const matchingNodes = this.presMap.nodes.filter(node => key === node.tagName);
  1196. // if we have found just one, let's check is it the same
  1197. if (matchingNodes.length === 1 && isEqual(matchingNodes[0], values)) {
  1198. return false;
  1199. }
  1200. this.removeFromPresence(key);
  1201. this.presMap.nodes.push(values);
  1202. this.presenceUpdateTime = Date.now();
  1203. return true;
  1204. }
  1205. /**
  1206. * Retrieves a value from the presence map.
  1207. *
  1208. * @param {string} key - The key to find the value for.
  1209. * @returns {Object?}
  1210. */
  1211. getFromPresence(key) {
  1212. return this.presMap.nodes.find(node => key === node.tagName);
  1213. }
  1214. /**
  1215. * Removes a key from the presence map.
  1216. * @param key
  1217. */
  1218. removeFromPresence(key) {
  1219. const nodes = this.presMap.nodes.filter(node => key !== node.tagName);
  1220. this.presMap.nodes = nodes;
  1221. this.presenceUpdateTime = Date.now();
  1222. }
  1223. /**
  1224. *
  1225. * @param name
  1226. * @param handler
  1227. */
  1228. addPresenceListener(name, handler) {
  1229. if (typeof handler !== 'function') {
  1230. throw new Error('"handler" is not a function');
  1231. }
  1232. let tagHandlers = this.presHandlers[name];
  1233. if (!tagHandlers) {
  1234. this.presHandlers[name] = tagHandlers = [];
  1235. }
  1236. if (tagHandlers.indexOf(handler) === -1) {
  1237. tagHandlers.push(handler);
  1238. } else {
  1239. logger.warn(
  1240. `Trying to add the same handler more than once for: ${name}`);
  1241. }
  1242. }
  1243. /**
  1244. *
  1245. * @param name
  1246. * @param handler
  1247. */
  1248. removePresenceListener(name, handler) {
  1249. const tagHandlers = this.presHandlers[name];
  1250. const handlerIdx = tagHandlers ? tagHandlers.indexOf(handler) : -1;
  1251. // eslint-disable-next-line no-negated-condition
  1252. if (handlerIdx !== -1) {
  1253. tagHandlers.splice(handlerIdx, 1);
  1254. } else {
  1255. logger.warn(`Handler for: ${name} was not registered`);
  1256. }
  1257. }
  1258. /**
  1259. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1260. * focus.
  1261. * @param mucJid the full MUC address of the user to be checked.
  1262. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus
  1263. * or <tt>false</tt> if is not. When given <tt>mucJid</tt> does not exist in
  1264. * the MUC then <tt>null</tt> is returned.
  1265. */
  1266. isFocus(mucJid) {
  1267. const member = this.members[mucJid];
  1268. if (member) {
  1269. return member.isFocus;
  1270. }
  1271. return null;
  1272. }
  1273. /**
  1274. *
  1275. */
  1276. isModerator() {
  1277. return this.role === 'moderator';
  1278. }
  1279. /**
  1280. *
  1281. * @param peerJid
  1282. */
  1283. getMemberRole(peerJid) {
  1284. if (this.members[peerJid]) {
  1285. return this.members[peerJid].role;
  1286. }
  1287. return null;
  1288. }
  1289. /**
  1290. *
  1291. * @param mute
  1292. * @param callback
  1293. */
  1294. setVideoMute(mute, callback) {
  1295. this.sendVideoInfoPresence(mute);
  1296. if (callback) {
  1297. callback(mute);
  1298. }
  1299. }
  1300. /**
  1301. *
  1302. * @param mute
  1303. * @param callback
  1304. */
  1305. setAudioMute(mute, callback) {
  1306. return this.sendAudioInfoPresence(mute, callback);
  1307. }
  1308. /**
  1309. *
  1310. * @param mute
  1311. */
  1312. addAudioInfoToPresence(mute) {
  1313. return this.addOrReplaceInPresence(
  1314. 'audiomuted',
  1315. {
  1316. attributes: { 'xmlns': 'http://jitsi.org/jitmeet/audio' },
  1317. value: mute.toString()
  1318. });
  1319. }
  1320. /**
  1321. *
  1322. * @param mute
  1323. * @param callback
  1324. */
  1325. sendAudioInfoPresence(mute, callback) {
  1326. // FIXME resend presence on CONNECTED
  1327. this.addAudioInfoToPresence(mute) && this.sendPresence();
  1328. if (callback) {
  1329. callback();
  1330. }
  1331. }
  1332. /**
  1333. *
  1334. * @param mute
  1335. */
  1336. addVideoInfoToPresence(mute) {
  1337. return this.addOrReplaceInPresence(
  1338. 'videomuted',
  1339. {
  1340. attributes: { 'xmlns': 'http://jitsi.org/jitmeet/video' },
  1341. value: mute.toString()
  1342. });
  1343. }
  1344. /**
  1345. *
  1346. * @param mute
  1347. */
  1348. sendVideoInfoPresence(mute) {
  1349. this.addVideoInfoToPresence(mute) && this.sendPresence();
  1350. }
  1351. /**
  1352. * Obtains the info about given media advertised in the MUC presence of
  1353. * the participant identified by the given endpoint JID.
  1354. * @param {string} endpointId the endpoint ID mapped to the participant
  1355. * which corresponds to MUC nickname.
  1356. * @param {MediaType} mediaType the type of the media for which presence
  1357. * info will be obtained.
  1358. * @return {PeerMediaInfo} presenceInfo an object with media presence
  1359. * info or <tt>null</tt> either if there is no presence available or if
  1360. * the media type given is invalid.
  1361. */
  1362. getMediaPresenceInfo(endpointId, mediaType) {
  1363. // Will figure out current muted status by looking up owner's presence
  1364. const pres = this.lastPresences[`${this.roomjid}/${endpointId}`];
  1365. if (!pres) {
  1366. // No presence available
  1367. return null;
  1368. }
  1369. const data = {
  1370. muted: false, // unmuted by default
  1371. videoType: undefined // no video type by default
  1372. };
  1373. let mutedNode = null;
  1374. if (mediaType === MediaType.AUDIO) {
  1375. mutedNode = filterNodeFromPresenceJSON(pres, 'audiomuted');
  1376. } else if (mediaType === MediaType.VIDEO) {
  1377. mutedNode = filterNodeFromPresenceJSON(pres, 'videomuted');
  1378. const codecTypeNode = filterNodeFromPresenceJSON(pres, 'jitsi_participant_codecType');
  1379. const videoTypeNode = filterNodeFromPresenceJSON(pres, 'videoType');
  1380. if (videoTypeNode.length > 0) {
  1381. data.videoType = videoTypeNode[0].value;
  1382. }
  1383. if (codecTypeNode.length > 0) {
  1384. data.codecType = codecTypeNode[0].value;
  1385. }
  1386. } else {
  1387. logger.error(`Unsupported media type: ${mediaType}`);
  1388. return null;
  1389. }
  1390. data.muted = mutedNode.length > 0 && mutedNode[0].value === 'true';
  1391. return data;
  1392. }
  1393. /**
  1394. * Returns true if the SIP calls are supported and false otherwise
  1395. */
  1396. isSIPCallingSupported() {
  1397. if (this.moderator) {
  1398. return this.moderator.isSipGatewayEnabled();
  1399. }
  1400. return false;
  1401. }
  1402. /**
  1403. * Dials a number.
  1404. * @param number the number
  1405. */
  1406. dial(number) {
  1407. return this.connection.rayo.dial(number, 'fromnumber',
  1408. Strophe.getBareJidFromJid(this.myroomjid), this.password,
  1409. this.focusMucJid);
  1410. }
  1411. /**
  1412. * Hangup an existing call
  1413. */
  1414. hangup() {
  1415. return this.connection.rayo.hangup();
  1416. }
  1417. /**
  1418. *
  1419. * @returns {Lobby}
  1420. */
  1421. getLobby() {
  1422. return this.lobby;
  1423. }
  1424. /**
  1425. * Returns the phone number for joining the conference.
  1426. */
  1427. getPhoneNumber() {
  1428. return this.phoneNumber;
  1429. }
  1430. /**
  1431. * Returns the pin for joining the conference with phone.
  1432. */
  1433. getPhonePin() {
  1434. return this.phonePin;
  1435. }
  1436. /**
  1437. * Returns the meeting unique ID if any came from backend.
  1438. *
  1439. * @returns {string} - The meeting ID.
  1440. */
  1441. getMeetingId() {
  1442. return this.meetingId;
  1443. }
  1444. /**
  1445. * Mutes remote participant.
  1446. * @param jid of the participant
  1447. * @param mute
  1448. * @param mediaType
  1449. */
  1450. muteParticipant(jid, mute, mediaType) {
  1451. logger.info('set mute', mute);
  1452. const iqToFocus = $iq(
  1453. { to: this.focusMucJid,
  1454. type: 'set' })
  1455. .c('mute', {
  1456. xmlns: `http://jitsi.org/jitmeet/${mediaType}`,
  1457. jid
  1458. })
  1459. .t(mute.toString())
  1460. .up();
  1461. this.connection.sendIQ(
  1462. iqToFocus,
  1463. result => logger.log('set mute', result),
  1464. error => logger.log('set mute error', error));
  1465. }
  1466. /**
  1467. * TODO: Document
  1468. * @param iq
  1469. */
  1470. onMute(iq) {
  1471. const from = iq.getAttribute('from');
  1472. if (from !== this.focusMucJid) {
  1473. logger.warn('Ignored mute from non focus peer');
  1474. return;
  1475. }
  1476. const mute = $(iq).find('mute');
  1477. if (mute.length && mute.text() === 'true') {
  1478. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, mute.attr('actor'));
  1479. } else {
  1480. // XXX Why do we support anything but muting? Why do we encode the
  1481. // value in the text of the element? Why do we use a separate XML
  1482. // namespace?
  1483. logger.warn('Ignoring a mute request which does not explicitly '
  1484. + 'specify a positive mute command.');
  1485. }
  1486. }
  1487. /**
  1488. * TODO: Document
  1489. * @param iq
  1490. */
  1491. onMuteVideo(iq) {
  1492. const from = iq.getAttribute('from');
  1493. if (from !== this.focusMucJid) {
  1494. logger.warn('Ignored mute from non focus peer');
  1495. return;
  1496. }
  1497. const mute = $(iq).find('mute');
  1498. if (mute.length && mute.text() === 'true') {
  1499. this.eventEmitter.emit(XMPPEvents.VIDEO_MUTED_BY_FOCUS, mute.attr('actor'));
  1500. } else {
  1501. // XXX Why do we support anything but muting? Why do we encode the
  1502. // value in the text of the element? Why do we use a separate XML
  1503. // namespace?
  1504. logger.warn('Ignoring a mute request which does not explicitly '
  1505. + 'specify a positive mute command.');
  1506. }
  1507. }
  1508. /**
  1509. * Clean any listeners or resources, executed on leaving.
  1510. */
  1511. clean() {
  1512. this._removeConnListeners.forEach(remove => remove());
  1513. this._removeConnListeners = [];
  1514. this.joined = false;
  1515. }
  1516. /**
  1517. * Leaves the room. Closes the jingle session.
  1518. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received
  1519. * less than 5s after sending presence unavailable. Otherwise the promise is
  1520. * rejected.
  1521. */
  1522. leave() {
  1523. return new Promise((resolve, reject) => {
  1524. const timeout = setTimeout(() => onMucLeft(true), 5000);
  1525. const eventEmitter = this.eventEmitter;
  1526. this.clean();
  1527. /**
  1528. *
  1529. * @param doReject
  1530. */
  1531. function onMucLeft(doReject = false) {
  1532. eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1533. clearTimeout(timeout);
  1534. if (doReject) {
  1535. // the timeout expired
  1536. reject(new Error('The timeout for the confirmation about '
  1537. + 'leaving the room expired.'));
  1538. } else {
  1539. resolve();
  1540. }
  1541. }
  1542. eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  1543. this.doLeave();
  1544. });
  1545. }
  1546. }
  1547. /* eslint-enable newline-per-chained-call */