Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ChatRoom.js 59KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827
  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 { XMPPEvents } from '../../service/xmpp/XMPPEvents';
  7. import GlobalOnErrorHandler from '../util/GlobalOnErrorHandler';
  8. import Listenable from '../util/Listenable';
  9. import AVModeration from './AVModeration';
  10. import BreakoutRooms from './BreakoutRooms';
  11. import Lobby from './Lobby';
  12. import RoomMetadata from './RoomMetadata';
  13. import XmppConnection from './XmppConnection';
  14. import Moderator from './moderator';
  15. const logger = getLogger(__filename);
  16. export const parser = {
  17. packet2JSON(xmlElement, nodes) {
  18. for (const child of Array.from(xmlElement.children)) {
  19. const node = {
  20. attributes: {},
  21. children: [],
  22. tagName: child.tagName
  23. };
  24. for (const attr of Array.from(child.attributes)) {
  25. node.attributes[attr.name] = attr.value;
  26. }
  27. const text = Strophe.getText(child);
  28. if (text) {
  29. // Using Strophe.getText will do work for traversing all direct
  30. // child text nodes but returns an escaped value, which is not
  31. // desirable at this point.
  32. node.value = Strophe.xmlunescape(text);
  33. }
  34. nodes.push(node);
  35. this.packet2JSON(child, node.children);
  36. }
  37. },
  38. json2packet(nodes, packet) {
  39. for (let i = 0; i < nodes.length; i++) {
  40. const node = nodes[i];
  41. if (node) {
  42. packet.c(node.tagName, node.attributes);
  43. if (node.value) {
  44. packet.t(node.value);
  45. }
  46. if (node.children) {
  47. this.json2packet(node.children, packet);
  48. }
  49. packet.up();
  50. }
  51. }
  52. // packet.up();
  53. }
  54. };
  55. /**
  56. * Returns array of JS objects from the presence JSON associated with the passed
  57. / nodeName
  58. * @param pres the presence JSON
  59. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  60. */
  61. export function filterNodeFromPresenceJSON(pres, nodeName) {
  62. const res = [];
  63. for (let i = 0; i < pres.length; i++) {
  64. if (pres[i].tagName === nodeName) {
  65. res.push(pres[i]);
  66. }
  67. }
  68. return res;
  69. }
  70. // XXX As ChatRoom constructs XMPP stanzas and Strophe is build around the idea
  71. // of chaining function calls, allow long function call chains.
  72. /* eslint-disable newline-per-chained-call */
  73. /**
  74. * Array of affiliations that are allowed in members only room.
  75. * @type {string[]}
  76. */
  77. const MEMBERS_AFFILIATIONS = [ 'owner', 'admin', 'member' ];
  78. /**
  79. *
  80. */
  81. export default class ChatRoom extends Listenable {
  82. /* eslint-disable max-params */
  83. /**
  84. *
  85. * @param {XmppConnection} connection - The XMPP connection instance.
  86. * @param jid
  87. * @param password
  88. * @param XMPP
  89. * @param options
  90. * @param {boolean} options.disableFocus - when set to {@code false} will
  91. * not invite Jicofo into the room.
  92. * @param {boolean} options.disableDiscoInfo - when set to {@code false} will skip disco info.
  93. * This is intended to be used only for lobby rooms.
  94. * @param {boolean} options.enableLobby - when set to {@code false} will skip creating lobby room.
  95. * @param {boolean} options.hiddenFromRecorderFeatureEnabled - when set to {@code true} we will check identity tag
  96. * for node presence.
  97. */
  98. constructor(connection, jid, password, XMPP, options) {
  99. super();
  100. this.xmpp = XMPP;
  101. this.connection = connection;
  102. this.roomjid = Strophe.getBareJidFromJid(jid);
  103. this.myroomjid = jid;
  104. this.password = password;
  105. this.replaceParticipant = false;
  106. logger.info(`Joined MUC as ${this.myroomjid}`);
  107. this.members = {};
  108. this.presMap = {};
  109. this.presHandlers = {};
  110. this._removeConnListeners = [];
  111. this.joined = false;
  112. this.inProgressEmitted = false;
  113. this.role = null;
  114. this.focusMucJid = null;
  115. this.noBridgeAvailable = false;
  116. this.options = options || {};
  117. this.moderator
  118. = new Moderator(this.roomjid, this.xmpp, this.eventEmitter, {
  119. connection: this.xmpp.options,
  120. conference: this.options
  121. });
  122. if (typeof this.options.enableLobby === 'undefined' || this.options.enableLobby) {
  123. this.lobby = new Lobby(this);
  124. }
  125. this.avModeration = new AVModeration(this);
  126. this.breakoutRooms = new BreakoutRooms(this);
  127. this.roomMetadata = new RoomMetadata(this);
  128. this.initPresenceMap(options);
  129. this.lastPresences = {};
  130. this.phoneNumber = null;
  131. this.phonePin = null;
  132. this.connectionTimes = {};
  133. this.participantPropertyListener = null;
  134. this.locked = false;
  135. this.transcriptionStatus = JitsiTranscriptionStatus.OFF;
  136. }
  137. /* eslint-enable max-params */
  138. /**
  139. *
  140. */
  141. initPresenceMap(options = {}) {
  142. this.presMap.to = this.myroomjid;
  143. this.presMap.xns = 'http://jabber.org/protocol/muc';
  144. this.presMap.nodes = [];
  145. if (options.statsId) {
  146. this.presMap.nodes.push({
  147. 'tagName': 'stats-id',
  148. 'value': options.statsId
  149. });
  150. }
  151. this.presenceUpdateTime = Date.now();
  152. }
  153. /**
  154. * Joins the chat room.
  155. * @param {string} password - Password to unlock room on joining.
  156. * @returns {Promise} - resolved when join completes. At the time of this
  157. * writing it's never rejected.
  158. */
  159. join(password, replaceParticipant) {
  160. this.password = password;
  161. this.replaceParticipant = replaceParticipant;
  162. return new Promise(resolve => {
  163. this.options.disableFocus
  164. && logger.info(`Conference focus disabled for ${this.roomjid}`);
  165. const preJoin
  166. = this.options.disableFocus
  167. ? Promise.resolve()
  168. : this.moderator.allocateConferenceFocus();
  169. preJoin.then(() => {
  170. this.sendPresence(true);
  171. this._removeConnListeners.push(
  172. this.connection.addEventListener(
  173. XmppConnection.Events.CONN_STATUS_CHANGED,
  174. this.onConnStatusChanged.bind(this))
  175. );
  176. resolve();
  177. });
  178. });
  179. }
  180. /**
  181. *
  182. * @param fromJoin - Whether this is initial presence to join the room.
  183. */
  184. sendPresence(fromJoin) {
  185. const to = this.presMap.to;
  186. if (!this.connection || !this.connection.connected || !to || (!this.joined && !fromJoin)) {
  187. // Too early to send presence - not initialized
  188. return;
  189. }
  190. const pres = $pres({ to });
  191. // xep-0045 defines: "including in the initial presence stanza an empty
  192. // <x/> element qualified by the 'http://jabber.org/protocol/muc'
  193. // namespace" and subsequent presences should not include that or it can
  194. // be considered as joining, and server can send us the message history
  195. // for the room on every presence
  196. if (fromJoin) {
  197. if (this.replaceParticipant) {
  198. pres.c('flip_device').up();
  199. }
  200. pres.c('x', { xmlns: this.presMap.xns });
  201. if (this.password) {
  202. pres.c('password').t(this.password).up();
  203. }
  204. if (this.options.billingId) {
  205. pres.c('billingid').t(this.options.billingId).up();
  206. }
  207. pres.up();
  208. }
  209. parser.json2packet(this.presMap.nodes, pres);
  210. // we store time we last synced presence state
  211. this.presenceSyncTime = Date.now();
  212. this.connection.send(pres);
  213. if (fromJoin) {
  214. // XXX We're pressed for time here because we're beginning a complex
  215. // and/or lengthy conference-establishment process which supposedly
  216. // involves multiple RTTs. We don't have the time to wait for
  217. // Strophe to decide to send our IQ.
  218. this.connection.flush();
  219. }
  220. }
  221. /**
  222. * Sends the presence unavailable, signaling the server
  223. * we want to leave the room.
  224. */
  225. doLeave(reason) {
  226. logger.log('do leave', this.myroomjid);
  227. const pres = $pres({
  228. to: this.myroomjid,
  229. type: 'unavailable'
  230. });
  231. if (reason) {
  232. pres.c('status').t(reason).up();
  233. }
  234. this.presMap.length = 0;
  235. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  236. // means that there may not be enough time to send the unavailable
  237. // presence. Switching Strophe to synchronous sending is not much of an
  238. // option because it may lead to a noticeable delay in navigating away
  239. // from the current location. As a compromise, we will try to increase
  240. // the chances of sending the unavailable presence within the short time
  241. // span that we have upon unloading by invoking flush() on the
  242. // connection. We flush() once before sending/queuing the unavailable
  243. // presence in order to attemtp to have the unavailable presence at the
  244. // top of the send queue. We flush() once more after sending/queuing the
  245. // unavailable presence in order to attempt to have it sent as soon as
  246. // possible.
  247. // FIXME do not use Strophe.Connection in the ChatRoom directly
  248. !this.connection.isUsingWebSocket && this.connection.flush();
  249. this.connection.send(pres);
  250. this.connection.flush();
  251. }
  252. /**
  253. *
  254. */
  255. discoRoomInfo() {
  256. // https://xmpp.org/extensions/xep-0045.html#disco-roominfo
  257. const getInfo
  258. = $iq({
  259. type: 'get',
  260. to: this.roomjid
  261. })
  262. .c('query', { xmlns: Strophe.NS.DISCO_INFO });
  263. this.connection.sendIQ(getInfo, result => {
  264. const locked
  265. = $(result).find('>query>feature[var="muc_passwordprotected"]')
  266. .length
  267. === 1;
  268. if (locked !== this.locked) {
  269. this.eventEmitter.emit(XMPPEvents.MUC_LOCK_CHANGED, locked);
  270. this.locked = locked;
  271. }
  272. const meetingIdValEl
  273. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_meetingId"]>value');
  274. if (meetingIdValEl.length) {
  275. this.setMeetingId(meetingIdValEl.text());
  276. } else {
  277. logger.warn('No meeting ID from backend');
  278. }
  279. const membersOnly = $(result).find('>query>feature[var="muc_membersonly"]').length === 1;
  280. const lobbyRoomField
  281. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_lobbyroom"]>value');
  282. if (this.lobby) {
  283. this.lobby.setLobbyRoomJid(lobbyRoomField && lobbyRoomField.length ? lobbyRoomField.text() : undefined);
  284. }
  285. const isBreakoutField
  286. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_isbreakout"]>value');
  287. const isBreakoutRoom = Boolean(isBreakoutField?.text());
  288. this.breakoutRooms._setIsBreakoutRoom(isBreakoutRoom);
  289. const breakoutMainRoomField
  290. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_breakout_main_room"]>value');
  291. if (breakoutMainRoomField?.length) {
  292. this.breakoutRooms._setMainRoomJid(breakoutMainRoomField.text());
  293. }
  294. if (membersOnly !== this.membersOnlyEnabled) {
  295. this.membersOnlyEnabled = membersOnly;
  296. this.eventEmitter.emit(XMPPEvents.MUC_MEMBERS_ONLY_CHANGED, membersOnly);
  297. }
  298. const roomMetadataEl
  299. = $(result).find('>query>x[type="result"]>field[var="muc#roominfo_jitsimetadata"]>value');
  300. const roomMetadataText = roomMetadataEl?.text();
  301. if (roomMetadataText) {
  302. try {
  303. this.roomMetadata._handleMessages(JSON.parse(roomMetadataText));
  304. } catch (e) {
  305. logger.warn('Failed to set room metadata', e);
  306. }
  307. }
  308. }, error => {
  309. GlobalOnErrorHandler.callErrorHandler(error);
  310. logger.error('Error getting room info: ', error);
  311. });
  312. }
  313. /**
  314. * Sets the meeting unique Id (received from the backend).
  315. *
  316. * @param {string} meetingId - The new meetings id.
  317. * @returns {void}
  318. */
  319. setMeetingId(meetingId) {
  320. if (this.meetingId !== meetingId) {
  321. if (this.meetingId) {
  322. logger.warn(`Meeting Id changed from:${this.meetingId} to:${meetingId}`);
  323. }
  324. this.meetingId = meetingId;
  325. this.eventEmitter.emit(XMPPEvents.MEETING_ID_SET, meetingId);
  326. }
  327. }
  328. /**
  329. *
  330. */
  331. createNonAnonymousRoom() {
  332. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  333. if (this.options.disableDiscoInfo) {
  334. return;
  335. }
  336. const getForm = $iq({ type: 'get',
  337. to: this.roomjid })
  338. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' })
  339. .c('x', { xmlns: 'jabber:x:data',
  340. type: 'submit' });
  341. this.connection.sendIQ(getForm, form => {
  342. if (!$(form).find(
  343. '>query>x[xmlns="jabber:x:data"]'
  344. + '>field[var="muc#roomconfig_whois"]').length) {
  345. const errmsg = 'non-anonymous rooms not supported';
  346. GlobalOnErrorHandler.callErrorHandler(new Error(errmsg));
  347. logger.error(errmsg);
  348. return;
  349. }
  350. const formSubmit = $iq({ to: this.roomjid,
  351. type: 'set' })
  352. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' });
  353. formSubmit.c('x', { xmlns: 'jabber:x:data',
  354. type: 'submit' });
  355. formSubmit.c('field', { 'var': 'FORM_TYPE' })
  356. .c('value')
  357. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  358. formSubmit.c('field', { 'var': 'muc#roomconfig_whois' })
  359. .c('value').t('anyone').up().up();
  360. this.connection.sendIQ(formSubmit);
  361. }, error => {
  362. GlobalOnErrorHandler.callErrorHandler(error);
  363. logger.error('Error getting room configuration form: ', error);
  364. });
  365. }
  366. /**
  367. * Handles Xmpp Connection status updates.
  368. *
  369. * @param {Strophe.Status} status - The Strophe connection status.
  370. */
  371. onConnStatusChanged(status) {
  372. // Send cached presence when the XMPP connection is re-established, only if needed
  373. if (status === XmppConnection.Status.CONNECTED && this.presenceUpdateTime > this.presenceSyncTime) {
  374. this.sendPresence();
  375. }
  376. }
  377. /**
  378. *
  379. * @param pres
  380. */
  381. onPresence(pres) {
  382. const from = pres.getAttribute('from');
  383. const member = {};
  384. const statusEl = pres.getElementsByTagName('status')[0];
  385. if (statusEl) {
  386. member.status = statusEl.textContent || '';
  387. }
  388. let hasStatusUpdate = false;
  389. let hasVersionUpdate = false;
  390. const xElement
  391. = pres.getElementsByTagNameNS(
  392. 'http://jabber.org/protocol/muc#user', 'x')[0];
  393. const mucUserItem
  394. = xElement && xElement.getElementsByTagName('item')[0];
  395. member.isReplaceParticipant
  396. = pres.getElementsByTagName('flip_device').length;
  397. member.affiliation
  398. = mucUserItem && mucUserItem.getAttribute('affiliation');
  399. member.role = mucUserItem && mucUserItem.getAttribute('role');
  400. // Focus recognition
  401. const jid = mucUserItem && mucUserItem.getAttribute('jid');
  402. member.jid = jid;
  403. member.isFocus
  404. = jid && jid.indexOf(`${this.moderator.getFocusUserJid()}/`) === 0;
  405. member.isHiddenDomain
  406. = jid && jid.indexOf('@') > 0
  407. && this.options.hiddenDomain
  408. === jid.substring(jid.indexOf('@') + 1, jid.indexOf('/'));
  409. this.eventEmitter.emit(XMPPEvents.PRESENCE_RECEIVED, {
  410. fromHiddenDomain: member.isHiddenDomain,
  411. presence: pres
  412. });
  413. const xEl = pres.querySelector('x');
  414. if (xEl) {
  415. xEl.remove();
  416. }
  417. const nodes = [];
  418. parser.packet2JSON(pres, nodes);
  419. this.lastPresences[from] = nodes;
  420. // process nodes to extract data needed for MUC_JOINED and
  421. // MUC_MEMBER_JOINED events
  422. const extractIdentityInformation = node => {
  423. const identity = {};
  424. const userInfo = node.children.find(c => c.tagName === 'user');
  425. if (userInfo) {
  426. identity.user = {};
  427. const tags = [ 'id', 'name', 'avatar' ];
  428. if (this.options.hiddenFromRecorderFeatureEnabled) {
  429. tags.push('hidden-from-recorder');
  430. }
  431. for (const tag of tags) {
  432. const child
  433. = userInfo.children.find(c => c.tagName === tag);
  434. if (child) {
  435. identity.user[tag] = child.value;
  436. }
  437. }
  438. }
  439. const groupInfo = node.children.find(c => c.tagName === 'group');
  440. if (groupInfo) {
  441. identity.group = groupInfo.value;
  442. }
  443. return identity;
  444. };
  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);
  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. * Called when participant leaves.
  807. * @param jid the jid of the participant that leaves
  808. * @param skipEvents optional params to skip any events, including check
  809. * whether this is the focus that left
  810. * @param reason the reason for leaving (optional).
  811. */
  812. onParticipantLeft(jid, skipEvents, reason) {
  813. delete this.lastPresences[jid];
  814. if (skipEvents) {
  815. return;
  816. }
  817. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid, reason);
  818. this.moderator.onMucMemberLeft(jid);
  819. }
  820. /**
  821. *
  822. * @param pres
  823. * @param from
  824. */
  825. onPresenceUnavailable(pres, from) {
  826. // ignore presence
  827. if ($(pres).find('>ignore[xmlns="http://jitsi.org/jitmeet/"]').length) {
  828. return true;
  829. }
  830. // room destroyed ?
  831. const destroySelect = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>destroy');
  832. if (destroySelect.length) {
  833. let reason;
  834. const reasonSelect
  835. = $(pres).find(
  836. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  837. + '>destroy>reason');
  838. if (reasonSelect.length) {
  839. reason = reasonSelect.text();
  840. }
  841. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason, destroySelect.attr('jid'));
  842. this.connection.emuc.doLeave(this.roomjid);
  843. return true;
  844. }
  845. // Status code 110 indicates that this notification is "self-presence".
  846. const isSelfPresence
  847. = $(pres)
  848. .find(
  849. '>x[xmlns="http://jabber.org/protocol/muc#user"]>'
  850. + 'status[code="110"]')
  851. .length;
  852. const isKick
  853. = $(pres)
  854. .find(
  855. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  856. + '>status[code="307"]')
  857. .length;
  858. const membersKeys = Object.keys(this.members);
  859. const isReplaceParticipant = $(pres).find('flip_device').length;
  860. if (isKick) {
  861. const actorSelect
  862. = $(pres)
  863. .find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item>actor');
  864. let actorNick;
  865. if (actorSelect.length) {
  866. actorNick = actorSelect.attr('nick');
  867. }
  868. let reason;
  869. const reasonSelect
  870. = $(pres).find(
  871. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  872. + '>item>reason');
  873. if (reasonSelect.length) {
  874. reason = reasonSelect.text();
  875. }
  876. // we first fire the kicked so we can show the participant
  877. // who kicked, before notifying that participant left
  878. // we fire kicked for us and for any participant kicked
  879. this.eventEmitter.emit(
  880. XMPPEvents.KICKED,
  881. isSelfPresence,
  882. actorNick,
  883. Strophe.getResourceFromJid(from),
  884. reason,
  885. isReplaceParticipant);
  886. }
  887. if (isSelfPresence) {
  888. // If the status code is 110 this means we're leaving and we would
  889. // like to remove everyone else from our view, so we trigger the
  890. // event.
  891. membersKeys.forEach(jid => {
  892. const member = this.members[jid];
  893. delete this.members[jid];
  894. this.onParticipantLeft(jid, member.isFocus);
  895. });
  896. this.connection.emuc.doLeave(this.roomjid);
  897. // we fire muc_left only if this is not a kick,
  898. // kick has both statuses 110 and 307.
  899. if (!isKick) {
  900. this.eventEmitter.emit(XMPPEvents.MUC_LEFT);
  901. }
  902. } else {
  903. const reasonSelect = $(pres).find('>status');
  904. let reason;
  905. if (reasonSelect.length) {
  906. reason = reasonSelect.text();
  907. }
  908. delete this.members[from];
  909. this.onParticipantLeft(from, false, reason);
  910. }
  911. }
  912. /**
  913. *
  914. * @param msg
  915. * @param from
  916. */
  917. onMessage(msg, from) {
  918. const type = msg.getAttribute('type');
  919. if (type === 'error') {
  920. const settingsErrorMsg = $(msg).find('>settings-error>text').text();
  921. if (settingsErrorMsg.length) {
  922. this.eventEmitter.emit(XMPPEvents.SETTINGS_ERROR_RECEIVED, settingsErrorMsg);
  923. return true;
  924. }
  925. const errorMsg = $(msg).find('>error>text').text();
  926. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED, errorMsg);
  927. return true;
  928. }
  929. const txt = $(msg).find('>body').text();
  930. const subject = $(msg).find('>subject');
  931. if (subject.length) {
  932. const subjectText = subject.text();
  933. if (subjectText || subjectText === '') {
  934. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  935. logger.log(`Subject is changed to ${subjectText}`);
  936. }
  937. }
  938. // xep-0203 delay
  939. let stamp = $(msg).find('>delay').attr('stamp');
  940. if (!stamp) {
  941. // or xep-0091 delay, UTC timestamp
  942. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  943. if (stamp) {
  944. // the format is CCYYMMDDThh:mm:ss
  945. const dateParts
  946. = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  947. stamp = `${dateParts[1]}-${dateParts[2]}-${dateParts[3]}Z`;
  948. }
  949. }
  950. if (from === this.roomjid) {
  951. let invite;
  952. if ($(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="104"]').length) {
  953. this.discoRoomInfo();
  954. } else if ((invite = $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>invite'))
  955. && invite.length) {
  956. const passwordSelect = $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>password');
  957. let password;
  958. if (passwordSelect && passwordSelect.length) {
  959. password = passwordSelect.text();
  960. }
  961. this.eventEmitter.emit(XMPPEvents.INVITE_MESSAGE_RECEIVED,
  962. from, invite.attr('from'), txt, password);
  963. }
  964. }
  965. const jsonMessage = $(msg).find('>json-message').text();
  966. if (jsonMessage) {
  967. const parsedJson = this.xmpp.tryParseJSONAndVerify(jsonMessage);
  968. // We emit this event if the message is a valid json, and is not
  969. // delivered after a delay, i.e. stamp is undefined.
  970. // e.g. - subtitles should not be displayed if delayed.
  971. if (parsedJson && stamp === undefined) {
  972. this.eventEmitter.emit(XMPPEvents.JSON_MESSAGE_RECEIVED,
  973. from, parsedJson);
  974. return;
  975. }
  976. }
  977. if (txt) {
  978. if (type === 'chat') {
  979. this.eventEmitter.emit(XMPPEvents.PRIVATE_MESSAGE_RECEIVED,
  980. from, txt, this.myroomjid, stamp);
  981. } else if (type === 'groupchat') {
  982. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  983. from, txt, this.myroomjid, stamp);
  984. }
  985. }
  986. }
  987. /**
  988. *
  989. * @param pres
  990. * @param from
  991. */
  992. onPresenceError(pres, from) {
  993. if ($(pres)
  994. .find(
  995. '>error[type="auth"]'
  996. + '>not-authorized['
  997. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  998. .length) {
  999. logger.log('on password required', from);
  1000. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  1001. } else if ($(pres)
  1002. .find(
  1003. '>error[type="cancel"]'
  1004. + '>not-allowed['
  1005. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  1006. .length) {
  1007. const toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  1008. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  1009. // enter the room by replying with 'not-authorized'. This would
  1010. // result in reconnection from authorized domain.
  1011. // We're either missing Jicofo/Prosody config for anonymous
  1012. // domains or something is wrong.
  1013. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR);
  1014. } else {
  1015. logger.warn('onPresError ', pres);
  1016. this.eventEmitter.emit(
  1017. XMPPEvents.ROOM_CONNECT_NOT_ALLOWED_ERROR);
  1018. }
  1019. } else if ($(pres).find('>error>service-unavailable').length) {
  1020. logger.warn('Maximum users limit for the room has been reached',
  1021. pres);
  1022. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR);
  1023. } else if ($(pres)
  1024. .find(
  1025. '>error[type="auth"]'
  1026. + '>registration-required['
  1027. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  1028. // let's extract the lobby jid from the custom field
  1029. const lobbyRoomNode = $(pres).find('>error[type="auth"]>lobbyroom');
  1030. let lobbyRoomJid;
  1031. if (lobbyRoomNode.length) {
  1032. lobbyRoomJid = lobbyRoomNode.text();
  1033. } else {
  1034. // let's fallback to old location of lobbyroom node, TODO: to be removed in the future once
  1035. // everything is updated
  1036. const lobbyRoomOldNode = $(pres).find('>lobbyroom');
  1037. if (lobbyRoomOldNode.length) {
  1038. lobbyRoomJid = lobbyRoomOldNode.text();
  1039. }
  1040. }
  1041. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_MEMBERS_ONLY_ERROR, lobbyRoomJid);
  1042. } else {
  1043. logger.warn('onPresError ', pres);
  1044. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR);
  1045. }
  1046. }
  1047. /**
  1048. *
  1049. * @param jid
  1050. * @param affiliation
  1051. */
  1052. setAffiliation(jid, affiliation) {
  1053. const grantIQ = $iq({
  1054. to: this.roomjid,
  1055. type: 'set'
  1056. })
  1057. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  1058. .c('item', {
  1059. affiliation,
  1060. jid: Strophe.getBareJidFromJid(jid)
  1061. })
  1062. .c('reason').t(`Your affiliation has been changed to '${affiliation}'.`)
  1063. .up().up().up();
  1064. this.connection.sendIQ(
  1065. grantIQ,
  1066. result => logger.log('Set affiliation of participant with jid: ', jid, 'to', affiliation, result),
  1067. error => logger.log('Set affiliation of participant error: ', error));
  1068. }
  1069. /**
  1070. *
  1071. * @param jid
  1072. * @param reason
  1073. */
  1074. kick(jid, reason = 'You have been kicked.') {
  1075. const kickIQ = $iq({ to: this.roomjid,
  1076. type: 'set' })
  1077. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  1078. .c('item', { nick: Strophe.getResourceFromJid(jid),
  1079. role: 'none' })
  1080. .c('reason').t(reason).up().up().up();
  1081. this.connection.sendIQ(
  1082. kickIQ,
  1083. result => logger.log('Kick participant with jid: ', jid, result),
  1084. error => logger.log('Kick participant error: ', error));
  1085. }
  1086. /* eslint-disable max-params */
  1087. /**
  1088. *
  1089. * @param key
  1090. * @param onSuccess
  1091. * @param onError
  1092. * @param onNotSupported
  1093. */
  1094. lockRoom(key, onSuccess, onError, onNotSupported) {
  1095. // http://xmpp.org/extensions/xep-0045.html#roomconfig
  1096. this.connection.sendIQ(
  1097. $iq({
  1098. to: this.roomjid,
  1099. type: 'get'
  1100. })
  1101. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  1102. res => {
  1103. if ($(res)
  1104. .find(
  1105. '>query>x[xmlns="jabber:x:data"]'
  1106. + '>field[var="muc#roomconfig_roomsecret"]')
  1107. .length) {
  1108. const formsubmit
  1109. = $iq({
  1110. to: this.roomjid,
  1111. type: 'set'
  1112. })
  1113. .c('query', {
  1114. xmlns: 'http://jabber.org/protocol/muc#owner'
  1115. });
  1116. formsubmit.c('x', {
  1117. xmlns: 'jabber:x:data',
  1118. type: 'submit'
  1119. });
  1120. formsubmit
  1121. .c('field', { 'var': 'FORM_TYPE' })
  1122. .c('value')
  1123. .t('http://jabber.org/protocol/muc#roomconfig')
  1124. .up()
  1125. .up();
  1126. formsubmit
  1127. .c('field', { 'var': 'muc#roomconfig_roomsecret' })
  1128. .c('value')
  1129. .t(key)
  1130. .up()
  1131. .up();
  1132. formsubmit
  1133. .c('field',
  1134. { 'var': 'muc#roomconfig_passwordprotectedroom' })
  1135. .c('value')
  1136. .t(key === null || key.length === 0 ? '0' : '1')
  1137. .up()
  1138. .up();
  1139. // if members only enabled
  1140. if (this.membersOnlyEnabled) {
  1141. formsubmit
  1142. .c('field', { 'var': 'muc#roomconfig_membersonly' })
  1143. .c('value')
  1144. .t('true')
  1145. .up()
  1146. .up();
  1147. }
  1148. // Fixes a bug in prosody 0.9.+
  1149. // https://prosody.im/issues/issue/373
  1150. formsubmit
  1151. .c('field', { 'var': 'muc#roomconfig_whois' })
  1152. .c('value')
  1153. .t('anyone')
  1154. .up()
  1155. .up();
  1156. this.connection.sendIQ(
  1157. formsubmit,
  1158. () => {
  1159. // we set the password in chat room so we can use it
  1160. // later when dialing out
  1161. this.password = key;
  1162. onSuccess();
  1163. },
  1164. onError);
  1165. } else {
  1166. onNotSupported();
  1167. }
  1168. },
  1169. onError);
  1170. }
  1171. /* eslint-enable max-params */
  1172. /**
  1173. * Turns off or on the members only config for the main room.
  1174. *
  1175. * @param {boolean} enabled - Whether to turn it on or off.
  1176. * @param onSuccess - optional callback.
  1177. * @param onError - optional callback.
  1178. */
  1179. setMembersOnly(enabled, onSuccess, onError) {
  1180. if (enabled && Object.values(this.members).filter(m => !m.isFocus).length) {
  1181. // first grant membership to all that are in the room
  1182. // currently there is a bug in prosody where it handles only the first item
  1183. // that's why we will send iq per member
  1184. Object.values(this.members).forEach(m => {
  1185. if (m.jid && !MEMBERS_AFFILIATIONS.includes(m.affiliation)) {
  1186. this.xmpp.connection.sendIQ(
  1187. $iq({
  1188. to: this.roomjid,
  1189. type: 'set' })
  1190. .c('query', {
  1191. xmlns: 'http://jabber.org/protocol/muc#admin' })
  1192. .c('item', {
  1193. 'affiliation': 'member',
  1194. 'jid': Strophe.getBareJidFromJid(m.jid)
  1195. }).up().up());
  1196. }
  1197. });
  1198. }
  1199. const errorCallback = onError ? onError : () => {}; // eslint-disable-line no-empty-function
  1200. this.xmpp.connection.sendIQ(
  1201. $iq({
  1202. to: this.roomjid,
  1203. type: 'get'
  1204. }).c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  1205. res => {
  1206. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_membersonly"]').length) {
  1207. const formToSubmit
  1208. = $iq({
  1209. to: this.roomjid,
  1210. type: 'set'
  1211. }).c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' });
  1212. formToSubmit.c('x', {
  1213. xmlns: 'jabber:x:data',
  1214. type: 'submit'
  1215. });
  1216. formToSubmit
  1217. .c('field', { 'var': 'FORM_TYPE' })
  1218. .c('value')
  1219. .t('http://jabber.org/protocol/muc#roomconfig')
  1220. .up()
  1221. .up();
  1222. formToSubmit
  1223. .c('field', { 'var': 'muc#roomconfig_membersonly' })
  1224. .c('value')
  1225. .t(enabled ? 'true' : 'false')
  1226. .up()
  1227. .up();
  1228. // if room is locked from other participant or we are locking it
  1229. if (this.locked) {
  1230. formToSubmit
  1231. .c('field',
  1232. { 'var': 'muc#roomconfig_passwordprotectedroom' })
  1233. .c('value')
  1234. .t('1')
  1235. .up()
  1236. .up();
  1237. }
  1238. this.xmpp.connection.sendIQ(formToSubmit, onSuccess, errorCallback);
  1239. } else {
  1240. errorCallback(new Error('Setting members only room not supported!'));
  1241. }
  1242. },
  1243. errorCallback);
  1244. }
  1245. /**
  1246. * Adds the key to the presence map, overriding any previous value.
  1247. * This method is used by jibri.
  1248. *
  1249. * @param key The key to add or replace.
  1250. * @param values The new values.
  1251. * @returns {boolean|null} <tt>true</tt> if the operation succeeded or <tt>false</tt> when no add or replce was
  1252. * performed as the value was already there.
  1253. * @deprecated Use 'addOrReplaceInPresence' instead. TODO: remove it from here and jibri.
  1254. */
  1255. addToPresence(key, values) {
  1256. return this.addOrReplaceInPresence(key, values);
  1257. }
  1258. /**
  1259. * Adds the key to the presence map, overriding any previous value.
  1260. * @param key The key to add or replace.
  1261. * @param values The new values.
  1262. * @returns {boolean|null} <tt>true</tt> if the operation succeeded or <tt>false</tt> when no add or replace was
  1263. * performed as the value was already there.
  1264. */
  1265. addOrReplaceInPresence(key, values) {
  1266. values.tagName = key;
  1267. const matchingNodes = this.presMap.nodes.filter(node => key === node.tagName);
  1268. // if we have found just one, let's check is it the same
  1269. if (matchingNodes.length === 1 && isEqual(matchingNodes[0], values)) {
  1270. return false;
  1271. }
  1272. this.removeFromPresence(key);
  1273. this.presMap.nodes.push(values);
  1274. this.presenceUpdateTime = Date.now();
  1275. return true;
  1276. }
  1277. /**
  1278. * Retrieves a value from the presence map.
  1279. *
  1280. * @param {string} key - The key to find the value for.
  1281. * @returns {Object?}
  1282. */
  1283. getFromPresence(key) {
  1284. return this.presMap.nodes.find(node => key === node.tagName);
  1285. }
  1286. /**
  1287. * Removes a key from the presence map.
  1288. * @param key
  1289. */
  1290. removeFromPresence(key) {
  1291. const nodes = this.presMap.nodes.filter(node => key !== node.tagName);
  1292. this.presMap.nodes = nodes;
  1293. this.presenceUpdateTime = Date.now();
  1294. }
  1295. /**
  1296. *
  1297. * @param name
  1298. * @param handler
  1299. */
  1300. addPresenceListener(name, handler) {
  1301. if (typeof handler !== 'function') {
  1302. throw new Error('"handler" is not a function');
  1303. }
  1304. let tagHandlers = this.presHandlers[name];
  1305. if (!tagHandlers) {
  1306. this.presHandlers[name] = tagHandlers = [];
  1307. }
  1308. if (tagHandlers.indexOf(handler) === -1) {
  1309. tagHandlers.push(handler);
  1310. } else {
  1311. logger.warn(
  1312. `Trying to add the same handler more than once for: ${name}`);
  1313. }
  1314. }
  1315. /**
  1316. *
  1317. * @param name
  1318. * @param handler
  1319. */
  1320. removePresenceListener(name, handler) {
  1321. const tagHandlers = this.presHandlers[name];
  1322. const handlerIdx = tagHandlers ? tagHandlers.indexOf(handler) : -1;
  1323. // eslint-disable-next-line no-negated-condition
  1324. if (handlerIdx !== -1) {
  1325. tagHandlers.splice(handlerIdx, 1);
  1326. } else {
  1327. logger.warn(`Handler for: ${name} was not registered`);
  1328. }
  1329. }
  1330. /**
  1331. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1332. * focus.
  1333. * @param mucJid the full MUC address of the user to be checked.
  1334. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus
  1335. * or <tt>false</tt> if is not. When given <tt>mucJid</tt> does not exist in
  1336. * the MUC then <tt>null</tt> is returned.
  1337. */
  1338. isFocus(mucJid) {
  1339. const member = this.members[mucJid];
  1340. if (member) {
  1341. return member.isFocus;
  1342. }
  1343. return null;
  1344. }
  1345. /**
  1346. *
  1347. */
  1348. isModerator() {
  1349. return this.role === 'moderator';
  1350. }
  1351. /**
  1352. *
  1353. * @param peerJid
  1354. */
  1355. getMemberRole(peerJid) {
  1356. if (this.members[peerJid]) {
  1357. return this.members[peerJid].role;
  1358. }
  1359. return null;
  1360. }
  1361. /**
  1362. * Returns the last presence advertised by a MUC member.
  1363. * @param {string} mucNick
  1364. * @returns {*}
  1365. */
  1366. getLastPresence(mucNick) {
  1367. return this.lastPresences[`${this.roomjid}/${mucNick}`];
  1368. }
  1369. /**
  1370. * Returns true if the SIP calls are supported and false otherwise
  1371. */
  1372. isSIPCallingSupported() {
  1373. if (this.moderator) {
  1374. return this.moderator.isSipGatewayEnabled();
  1375. }
  1376. return false;
  1377. }
  1378. /**
  1379. * Dials a number.
  1380. * @param number the number
  1381. */
  1382. dial(number) {
  1383. return this.connection.rayo.dial(number, 'fromnumber',
  1384. Strophe.getBareJidFromJid(this.myroomjid), this.password,
  1385. this.focusMucJid);
  1386. }
  1387. /**
  1388. * Hangup an existing call
  1389. */
  1390. hangup() {
  1391. return this.connection.rayo.hangup();
  1392. }
  1393. /**
  1394. *
  1395. * @returns {Lobby}
  1396. */
  1397. getLobby() {
  1398. return this.lobby;
  1399. }
  1400. /**
  1401. * @returns {AVModeration}
  1402. */
  1403. getAVModeration() {
  1404. return this.avModeration;
  1405. }
  1406. /**
  1407. * @returns {BreakoutRooms}
  1408. */
  1409. getBreakoutRooms() {
  1410. return this.breakoutRooms;
  1411. }
  1412. /**
  1413. * @returns {RoomMetadata}
  1414. */
  1415. getMetadataHandler() {
  1416. return this.roomMetadata;
  1417. }
  1418. /**
  1419. * Returns the phone number for joining the conference.
  1420. */
  1421. getPhoneNumber() {
  1422. return this.phoneNumber;
  1423. }
  1424. /**
  1425. * Returns the pin for joining the conference with phone.
  1426. */
  1427. getPhonePin() {
  1428. return this.phonePin;
  1429. }
  1430. /**
  1431. * Returns the meeting unique ID if any came from backend.
  1432. *
  1433. * @returns {string} - The meeting ID.
  1434. */
  1435. getMeetingId() {
  1436. return this.meetingId;
  1437. }
  1438. /**
  1439. * Mutes remote participant.
  1440. * @param jid of the participant
  1441. * @param mute
  1442. * @param mediaType
  1443. */
  1444. muteParticipant(jid, mute, mediaType) {
  1445. logger.info('set mute', mute, jid);
  1446. const iqToFocus = $iq(
  1447. { to: this.focusMucJid,
  1448. type: 'set' })
  1449. .c('mute', {
  1450. xmlns: `http://jitsi.org/jitmeet/${mediaType}`,
  1451. jid
  1452. })
  1453. .t(mute.toString())
  1454. .up();
  1455. this.connection.sendIQ(
  1456. iqToFocus,
  1457. result => logger.log('set mute', result),
  1458. error => logger.log('set mute error', error));
  1459. }
  1460. /**
  1461. * TODO: Document
  1462. * @param iq
  1463. */
  1464. onMute(iq) {
  1465. const from = iq.getAttribute('from');
  1466. if (from !== this.focusMucJid) {
  1467. logger.warn('Ignored mute from non focus peer');
  1468. return;
  1469. }
  1470. const mute = $(iq).find('mute');
  1471. if (mute.length && mute.text() === 'true') {
  1472. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, mute.attr('actor'));
  1473. } else {
  1474. // XXX Why do we support anything but muting? Why do we encode the
  1475. // value in the text of the element? Why do we use a separate XML
  1476. // namespace?
  1477. logger.warn('Ignoring a mute request which does not explicitly '
  1478. + 'specify a positive mute command.');
  1479. }
  1480. }
  1481. /**
  1482. * TODO: Document
  1483. * @param iq
  1484. */
  1485. onMuteVideo(iq) {
  1486. const from = iq.getAttribute('from');
  1487. if (from !== this.focusMucJid) {
  1488. logger.warn('Ignored mute from non focus peer');
  1489. return;
  1490. }
  1491. const mute = $(iq).find('mute');
  1492. if (mute.length && mute.text() === 'true') {
  1493. this.eventEmitter.emit(XMPPEvents.VIDEO_MUTED_BY_FOCUS, mute.attr('actor'));
  1494. } else {
  1495. // XXX Why do we support anything but muting? Why do we encode the
  1496. // value in the text of the element? Why do we use a separate XML
  1497. // namespace?
  1498. logger.warn('Ignoring a mute request which does not explicitly '
  1499. + 'specify a positive mute command.');
  1500. }
  1501. }
  1502. /**
  1503. * Clean any listeners or resources, executed on leaving.
  1504. */
  1505. clean() {
  1506. this._removeConnListeners.forEach(remove => remove());
  1507. this._removeConnListeners = [];
  1508. this.joined = false;
  1509. this.inProgressEmitted = false;
  1510. }
  1511. /**
  1512. * Leaves the room. Closes the jingle session.
  1513. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received
  1514. * less than 5s after sending presence unavailable. Otherwise the promise is
  1515. * rejected.
  1516. */
  1517. leave(reason) {
  1518. this.avModeration.dispose();
  1519. this.breakoutRooms.dispose();
  1520. this.roomMetadata.dispose();
  1521. const promises = [];
  1522. this.lobby?.lobbyRoom && promises.push(this.lobby.leave());
  1523. promises.push(new Promise((resolve, reject) => {
  1524. let timeout = -1;
  1525. const onMucLeft = (doReject = false) => {
  1526. this.eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1527. clearTimeout(timeout);
  1528. if (doReject) {
  1529. // The timeout expired. Make sure we clean the EMUC state.
  1530. this.connection.emuc.doLeave(this.roomjid);
  1531. reject(new Error('The timeout for the confirmation about leaving the room expired.'));
  1532. } else {
  1533. resolve();
  1534. }
  1535. };
  1536. timeout = setTimeout(() => onMucLeft(true), 5000);
  1537. this.clean();
  1538. this.eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  1539. this.doLeave(reason);
  1540. }));
  1541. return Promise.allSettled(promises);
  1542. }
  1543. /**
  1544. * Ends the conference for all participants.
  1545. */
  1546. end() {
  1547. if (this.breakoutRooms.isBreakoutRoom()) {
  1548. logger.warn('Cannot end conference: this is a breakout room.');
  1549. return;
  1550. }
  1551. // Send the end conference message.
  1552. const msg = $msg({ to: this.xmpp.endConferenceComponentAddress });
  1553. msg.c('end_conference').up();
  1554. this.xmpp.connection.send(msg);
  1555. }
  1556. }
  1557. /* eslint-enable newline-per-chained-call */