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

ChatRoom.js 65KB

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