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

ChatRoom.js 60KB

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