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.

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