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

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