Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

ChatRoom.js 64KB

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