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

ChatRoom.js 60KB

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