您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ChatRoom.js 66KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957
  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. // we need to reset it because of breakout rooms which will reuse connection but will invite jicofo
  543. this.xmpp.moderator.conferenceRequestSent = false;
  544. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  545. // Now let's check the disco-info to retrieve the
  546. // meeting Id if any
  547. !this.options.disableDiscoInfo && this.discoRoomInfo();
  548. }
  549. } else if (jid === undefined) {
  550. logger.info('Ignoring member with undefined JID');
  551. } else if (this.members[from] === undefined) {
  552. // new participant
  553. this.members[from] = member;
  554. logger.log('entered', from, member);
  555. hasStatusUpdate = member.status !== undefined;
  556. hasVersionUpdate = member.version !== undefined;
  557. if (member.isFocus) {
  558. this._initFocus(from, member.features);
  559. } else {
  560. // identity is being added to member joined, so external
  561. // services can be notified for that (currently identity is
  562. // not used inside library)
  563. this.eventEmitter.emit(
  564. XMPPEvents.MUC_MEMBER_JOINED,
  565. from,
  566. member.nick,
  567. member.role,
  568. member.isHiddenDomain,
  569. member.statsID,
  570. member.status,
  571. member.identity,
  572. member.botType,
  573. member.jid,
  574. member.features,
  575. member.isReplaceParticipant);
  576. // we are reporting the status with the join
  577. // so we do not want a second event about status update
  578. hasStatusUpdate = false;
  579. }
  580. } else {
  581. // Presence update for existing participant
  582. // Watch role change:
  583. const memberOfThis = this.members[from];
  584. if (memberOfThis.role !== member.role) {
  585. memberOfThis.role = member.role;
  586. this.eventEmitter.emit(
  587. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  588. }
  589. // affiliation changed
  590. if (memberOfThis.affiliation !== member.affiliation) {
  591. memberOfThis.affiliation = member.affiliation;
  592. }
  593. // fire event that botType had changed
  594. if (memberOfThis.botType !== member.botType) {
  595. memberOfThis.botType = member.botType;
  596. this.eventEmitter.emit(
  597. XMPPEvents.MUC_MEMBER_BOT_TYPE_CHANGED,
  598. from,
  599. member.botType);
  600. }
  601. if (member.isFocus) {
  602. // From time to time first few presences of the focus are not
  603. // containing it's jid. That way we can mark later the focus
  604. // member instead of not marking it at all and not starting the
  605. // conference.
  606. // FIXME: Maybe there is a better way to handle this issue. It
  607. // seems there is some period of time in prosody that the
  608. // configuration form is received but not applied. And if any
  609. // participant joins during that period of time the first
  610. // presence from the focus won't contain
  611. // <item jid="focus..." />.
  612. // By default we are disabling the waiting for form submission in order to use the room
  613. // and we had enabled by default that jids are public in the room ,
  614. // so this case should not happen, if public jid is turned off we will receive the jid
  615. // when we become moderator in the room
  616. memberOfThis.isFocus = true;
  617. this._initFocus(from, member.features);
  618. }
  619. // store the new display name
  620. if (member.displayName) {
  621. memberOfThis.displayName = member.displayName;
  622. }
  623. // update stored status message to be able to detect changes
  624. if (memberOfThis.status !== member.status) {
  625. hasStatusUpdate = true;
  626. memberOfThis.status = member.status;
  627. }
  628. if (memberOfThis.version !== member.version) {
  629. hasVersionUpdate = true;
  630. memberOfThis.version = member.version;
  631. }
  632. if (!isEqual(memberOfThis.features, member.features)) {
  633. memberOfThis.features = member.features;
  634. this.eventEmitter.emit(XMPPEvents.PARTICIPANT_FEATURES_CHANGED, from, member.features);
  635. }
  636. }
  637. // after we had fired member or room joined events, lets fire events
  638. // for the rest info we got in presence
  639. for (let i = 0; i < nodes.length; i++) {
  640. const node = nodes[i];
  641. switch (node.tagName) {
  642. case 'nick':
  643. if (!member.isFocus) {
  644. const displayName
  645. = this.xmpp.options.displayJids
  646. ? Strophe.getResourceFromJid(from)
  647. : member.nick;
  648. this.eventEmitter.emit(
  649. XMPPEvents.DISPLAY_NAME_CHANGED,
  650. from,
  651. displayName);
  652. }
  653. break;
  654. case 'bridgeNotAvailable':
  655. if (member.isFocus && !this.noBridgeAvailable) {
  656. this.noBridgeAvailable = true;
  657. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  658. }
  659. break;
  660. case 'conference-properties':
  661. if (member.isFocus) {
  662. const properties = {};
  663. for (let j = 0; j < node.children.length; j++) {
  664. const { attributes } = node.children[j];
  665. if (attributes && attributes.key) {
  666. properties[attributes.key] = attributes.value;
  667. }
  668. }
  669. this.eventEmitter.emit(XMPPEvents.CONFERENCE_PROPERTIES_CHANGED, properties);
  670. // Log if Jicofo supports restart by terminate only once. This conference property does not change
  671. // during the call.
  672. if (typeof this.restartByTerminateSupported === 'undefined') {
  673. this.restartByTerminateSupported = properties['support-terminate-restart'] === 'true';
  674. logger.info(`Jicofo supports restart by terminate: ${this.supportsRestartByTerminate()}`);
  675. }
  676. }
  677. break;
  678. case 'transcription-status': {
  679. const { attributes } = node;
  680. if (!attributes) {
  681. break;
  682. }
  683. const { status } = attributes;
  684. if (status && status !== this.transcriptionStatus) {
  685. this.transcriptionStatus = status;
  686. this.eventEmitter.emit(
  687. XMPPEvents.TRANSCRIPTION_STATUS_CHANGED,
  688. status
  689. );
  690. }
  691. break;
  692. }
  693. case 'call-control': {
  694. const att = node.attributes;
  695. if (!att) {
  696. break;
  697. }
  698. this.phoneNumber = att.phone || null;
  699. this.phonePin = att.pin || null;
  700. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  701. break;
  702. }
  703. default:
  704. this.processNode(node, from);
  705. }
  706. }
  707. // Trigger status message update if necessary
  708. if (hasStatusUpdate) {
  709. this.eventEmitter.emit(
  710. XMPPEvents.PRESENCE_STATUS,
  711. from,
  712. member.status);
  713. }
  714. if (hasVersionUpdate) {
  715. logger.info(`Received version for ${jid}: ${member.version}`);
  716. }
  717. }
  718. /**
  719. * Extracts the features from the presence.
  720. * @param node the node to process.
  721. * @return features the Set of features where extracted data is added.
  722. * @private
  723. */
  724. _extractFeatures(node) {
  725. const features = new Set();
  726. for (let j = 0; j < node.children.length; j++) {
  727. const { attributes } = node.children[j];
  728. if (attributes && attributes.var) {
  729. features.add(attributes.var);
  730. }
  731. }
  732. return features;
  733. }
  734. /**
  735. * Initialize some properties when the focus participant is verified.
  736. * @param from jid of the focus
  737. * @param features the features reported in jicofo presence
  738. */
  739. _initFocus(from, features) {
  740. this.focusMucJid = from;
  741. this.focusFeatures = features;
  742. }
  743. /**
  744. * Sets the special listener to be used for "command"s whose name starts
  745. * with "jitsi_participant_".
  746. */
  747. setParticipantPropertyListener(listener) {
  748. this.participantPropertyListener = listener;
  749. }
  750. /**
  751. * Checks if Jicofo supports restarting Jingle session after 'session-terminate'.
  752. * @returns {boolean}
  753. */
  754. supportsRestartByTerminate() {
  755. return this.restartByTerminateSupported;
  756. }
  757. /**
  758. *
  759. * @param node
  760. * @param from
  761. */
  762. processNode(node, from) {
  763. // make sure we catch all errors coming from any handler
  764. // otherwise we can remove the presence handler from strophe
  765. try {
  766. let tagHandlers = this.presHandlers[node.tagName];
  767. if (node.tagName.startsWith('jitsi_participant_')) {
  768. tagHandlers = [ this.participantPropertyListener ];
  769. }
  770. if (tagHandlers) {
  771. tagHandlers.forEach(handler => {
  772. handler(node, Strophe.getResourceFromJid(from), from);
  773. });
  774. }
  775. } catch (e) {
  776. logger.error(`Error processing:${node.tagName} node.`, e);
  777. }
  778. }
  779. /**
  780. * Send text message to the other participants in the conference
  781. * @param message
  782. * @param elementName
  783. */
  784. sendMessage(message, elementName) {
  785. const msg = $msg({ to: this.roomjid,
  786. type: 'groupchat' });
  787. // We are adding the message in a packet extension. If this element
  788. // is different from 'body', we add a custom namespace.
  789. // e.g. for 'json-message' extension of message stanza.
  790. if (elementName === 'body') {
  791. msg.c(elementName, {}, message);
  792. } else {
  793. msg.c(elementName, { xmlns: 'http://jitsi.org/jitmeet' }, message);
  794. }
  795. this.connection.send(msg);
  796. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, message);
  797. }
  798. /* eslint-disable max-params */
  799. /**
  800. * Send private text message to another participant of the conference
  801. * @param id id/muc resource of the receiver
  802. * @param message
  803. * @param elementName
  804. */
  805. sendPrivateMessage(id, message, elementName) {
  806. const msg = $msg({ to: `${this.roomjid}/${id}`,
  807. type: 'chat' });
  808. // We are adding the message in packet. If this element is different
  809. // from 'body', we add our custom namespace for the same.
  810. // e.g. for 'json-message' message extension.
  811. if (elementName === 'body') {
  812. msg.c(elementName, message).up();
  813. } else {
  814. msg.c(elementName, { xmlns: 'http://jitsi.org/jitmeet' }, message)
  815. .up();
  816. }
  817. this.connection.send(msg);
  818. this.eventEmitter.emit(
  819. XMPPEvents.SENDING_PRIVATE_CHAT_MESSAGE, message);
  820. }
  821. /* eslint-enable max-params */
  822. /**
  823. *
  824. * @param subject
  825. */
  826. setSubject(subject) {
  827. const msg = $msg({ to: this.roomjid,
  828. type: 'groupchat' });
  829. msg.c('subject', subject);
  830. this.connection.send(msg);
  831. }
  832. /**
  833. *
  834. * @param pres
  835. * @param from
  836. */
  837. onPresenceUnavailable(pres, from) {
  838. // ignore presence
  839. if ($(pres).find('>ignore[xmlns="http://jitsi.org/jitmeet/"]').length) {
  840. return true;
  841. }
  842. // room destroyed ?
  843. const destroySelect = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>destroy');
  844. if (destroySelect.length) {
  845. let reason;
  846. const reasonSelect
  847. = $(pres).find(
  848. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  849. + '>destroy>reason');
  850. if (reasonSelect.length) {
  851. reason = reasonSelect.text();
  852. }
  853. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason, destroySelect.attr('jid'));
  854. this.connection.emuc.doLeave(this.roomjid);
  855. return true;
  856. }
  857. // Status code 110 indicates that this notification is "self-presence".
  858. const isSelfPresence
  859. = $(pres)
  860. .find(
  861. '>x[xmlns="http://jabber.org/protocol/muc#user"]>'
  862. + 'status[code="110"]')
  863. .length;
  864. const isKick
  865. = $(pres)
  866. .find(
  867. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  868. + '>status[code="307"]')
  869. .length;
  870. const membersKeys = Object.keys(this.members);
  871. const isReplaceParticipant = $(pres).find('flip_device').length;
  872. if (isKick) {
  873. const actorSelect
  874. = $(pres)
  875. .find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item>actor');
  876. let actorNick;
  877. if (actorSelect.length) {
  878. actorNick = actorSelect.attr('nick');
  879. }
  880. let reason;
  881. const reasonSelect
  882. = $(pres).find(
  883. '>x[xmlns="http://jabber.org/protocol/muc#user"]'
  884. + '>item>reason');
  885. if (reasonSelect.length) {
  886. reason = reasonSelect.text();
  887. }
  888. // we first fire the kicked so we can show the participant
  889. // who kicked, before notifying that participant left
  890. // we fire kicked for us and for any participant kicked
  891. this.eventEmitter.emit(
  892. XMPPEvents.KICKED,
  893. isSelfPresence,
  894. actorNick,
  895. Strophe.getResourceFromJid(from),
  896. reason,
  897. isReplaceParticipant);
  898. }
  899. if (isSelfPresence) {
  900. // If the status code is 110 this means we're leaving and we would
  901. // like to remove everyone else from our view, so we trigger the
  902. // event.
  903. membersKeys.forEach(jid => {
  904. const member = this.members[jid];
  905. delete this.members[jid];
  906. delete this.lastPresences[jid];
  907. if (!member.isFocus) {
  908. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  909. }
  910. });
  911. this.connection.emuc.doLeave(this.roomjid);
  912. // we fire muc_left only if this is not a kick,
  913. // kick has both statuses 110 and 307.
  914. if (!isKick) {
  915. this.eventEmitter.emit(XMPPEvents.MUC_LEFT);
  916. }
  917. } else {
  918. const reasonSelect = $(pres).find('>status');
  919. const member = this.members[from];
  920. let reason;
  921. if (reasonSelect.length) {
  922. reason = reasonSelect.text();
  923. }
  924. delete this.members[from];
  925. delete this.lastPresences[from];
  926. // In this case we *do* fire MUC_MEMBER_LEFT for the focus?
  927. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, from, reason);
  928. if (member?.isFocus) {
  929. logger.info('Focus has left the room - leaving conference');
  930. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  931. }
  932. }
  933. }
  934. /**
  935. *
  936. * @param msg
  937. * @param from
  938. */
  939. onMessage(msg, from) {
  940. const type = msg.getAttribute('type');
  941. if (type === 'error') {
  942. const settingsErrorMsg = $(msg).find('>settings-error>text').text();
  943. if (settingsErrorMsg.length) {
  944. this.eventEmitter.emit(XMPPEvents.SETTINGS_ERROR_RECEIVED, settingsErrorMsg);
  945. return true;
  946. }
  947. const errorMsg = $(msg).find('>error>text').text();
  948. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED, errorMsg);
  949. return true;
  950. }
  951. const txt = $(msg).find('>body').text();
  952. const subject = $(msg).find('>subject');
  953. if (subject.length) {
  954. const subjectText = subject.text();
  955. if (subjectText || subjectText === '') {
  956. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  957. logger.log(`Subject is changed to ${subjectText}`);
  958. }
  959. }
  960. // xep-0203 delay
  961. let stamp = $(msg).find('>delay').attr('stamp');
  962. if (!stamp) {
  963. // or xep-0091 delay, UTC timestamp
  964. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  965. if (stamp) {
  966. // the format is CCYYMMDDThh:mm:ss
  967. const dateParts
  968. = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  969. stamp = `${dateParts[1]}-${dateParts[2]}-${dateParts[3]}Z`;
  970. }
  971. }
  972. if (from === this.roomjid) {
  973. let invite;
  974. if ($(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="104"]').length) {
  975. this.discoRoomInfo();
  976. } else if ((invite = $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>invite'))
  977. && invite.length) {
  978. const passwordSelect = $(msg).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>password');
  979. let password;
  980. if (passwordSelect && passwordSelect.length) {
  981. password = passwordSelect.text();
  982. }
  983. this.eventEmitter.emit(XMPPEvents.INVITE_MESSAGE_RECEIVED,
  984. from, invite.attr('from'), txt, password);
  985. }
  986. }
  987. const jsonMessage = $(msg).find('>json-message').text();
  988. if (jsonMessage) {
  989. const parsedJson = this.xmpp.tryParseJSONAndVerify(jsonMessage);
  990. // We emit this event if the message is a valid json, and is not
  991. // delivered after a delay, i.e. stamp is undefined.
  992. // e.g. - subtitles should not be displayed if delayed.
  993. if (parsedJson && stamp === undefined) {
  994. this.eventEmitter.emit(XMPPEvents.JSON_MESSAGE_RECEIVED,
  995. from, parsedJson);
  996. return;
  997. }
  998. }
  999. if (txt) {
  1000. if (type === 'chat') {
  1001. this.eventEmitter.emit(XMPPEvents.PRIVATE_MESSAGE_RECEIVED,
  1002. from, txt, this.myroomjid, stamp);
  1003. } else if (type === 'groupchat') {
  1004. const nickEl = $(msg).find('>nick');
  1005. let nick;
  1006. if (nickEl.length > 0) {
  1007. nick = nickEl.text();
  1008. }
  1009. // we will fire explicitly that this is a guest(isGuest:true) to the conference
  1010. // informing that this is probably a message from a guest to the conference (visitor)
  1011. // a message with explicit name set
  1012. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  1013. from, txt, this.myroomjid, stamp, nick, Boolean(nick));
  1014. }
  1015. }
  1016. }
  1017. /**
  1018. *
  1019. * @param pres
  1020. * @param from
  1021. */
  1022. onPresenceError(pres, from) {
  1023. let errorDescriptionNode;
  1024. if (from === this.myroomjid) {
  1025. // we have tried to join, and we received an error, let's send again conference-iq on next attempt
  1026. // as it may turn out that jicofo left the room if we were the first to try,
  1027. // and the user delayed the attempt for entering the password or such
  1028. this.xmpp.moderator.conferenceRequestSent = false;
  1029. }
  1030. if ($(pres)
  1031. .find(
  1032. '>error[type="auth"]'
  1033. + '>not-authorized['
  1034. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  1035. .length) {
  1036. logger.log('on password required', from);
  1037. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  1038. } else if ($(pres)
  1039. .find(
  1040. '>error[type="cancel"]'
  1041. + '>not-allowed['
  1042. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]')
  1043. .length) {
  1044. const toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  1045. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  1046. // enter the room by replying with 'not-authorized'. This would
  1047. // result in reconnection from authorized domain.
  1048. // We're either missing Jicofo/Prosody config for anonymous
  1049. // domains or something is wrong.
  1050. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR);
  1051. } else {
  1052. logger.warn('onPresError ', pres);
  1053. const txtNode = $(pres).find('>error[type="cancel"]>text[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]');
  1054. const txt = txtNode.length && txtNode.text();
  1055. // a race where we have sent a conference request to jicofo and jicofo was about to leave or just left
  1056. // because of no participants in the room, and we tried to create the room, without having
  1057. // permissions for that (only jicofo creates rooms)
  1058. if (txt === 'Room creation is restricted') {
  1059. if (!this._roomCreationRetries) {
  1060. this._roomCreationRetries = 0;
  1061. }
  1062. this._roomCreationRetries++;
  1063. if (this._roomCreationRetries <= 3) {
  1064. const retryDelay = getJitterDelay(
  1065. /* retry */ this._roomCreationRetries,
  1066. /* minDelay */ 500,
  1067. 1.5);
  1068. // let's retry inviting jicofo and joining the room, retries will take between 1 and 3 seconds
  1069. setTimeout(() => this.join(this.password, this.replaceParticipant), retryDelay);
  1070. return;
  1071. }
  1072. }
  1073. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_NOT_ALLOWED_ERROR, txt);
  1074. }
  1075. } else if ($(pres).find('>error>service-unavailable').length) {
  1076. logger.warn('Maximum users limit for the room has been reached',
  1077. pres);
  1078. this.eventEmitter.emit(XMPPEvents.ROOM_MAX_USERS_ERROR);
  1079. } else if ($(pres)
  1080. .find(
  1081. '>error[type="auth"]'
  1082. + '>registration-required['
  1083. + 'xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  1084. // let's extract the lobby jid from the custom field
  1085. const lobbyRoomNode = $(pres).find('>error[type="auth"]>lobbyroom');
  1086. let lobbyRoomJid;
  1087. if (lobbyRoomNode.length) {
  1088. lobbyRoomJid = lobbyRoomNode.text();
  1089. }
  1090. const waitingForHost = $(pres).find('>error[type="auth"]>waiting-for-host').length > 0;
  1091. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_MEMBERS_ONLY_ERROR, lobbyRoomJid, waitingForHost);
  1092. } else if ((errorDescriptionNode = $(pres).find(
  1093. '>error[type="modify"]>displayname-required[xmlns="http://jitsi.org/jitmeet"]')).length) {
  1094. logger.warn('display name required ', pres);
  1095. this.eventEmitter.emit(XMPPEvents.DISPLAY_NAME_REQUIRED, errorDescriptionNode[0].attributes.lobby?.value);
  1096. } else {
  1097. logger.warn('onPresError ', pres);
  1098. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR);
  1099. }
  1100. }
  1101. /**
  1102. *
  1103. * @param jid
  1104. * @param affiliation
  1105. */
  1106. setAffiliation(jid, affiliation) {
  1107. const grantIQ = $iq({
  1108. to: this.roomjid,
  1109. type: 'set'
  1110. })
  1111. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  1112. .c('item', {
  1113. affiliation,
  1114. jid: Strophe.getBareJidFromJid(jid)
  1115. })
  1116. .c('reason').t(`Your affiliation has been changed to '${affiliation}'.`)
  1117. .up().up().up();
  1118. this.connection.sendIQ(
  1119. grantIQ,
  1120. result => logger.log('Set affiliation of participant with jid: ', jid, 'to', affiliation, result),
  1121. error => logger.log('Set affiliation of participant error: ', error));
  1122. }
  1123. /**
  1124. *
  1125. * @param jid
  1126. * @param reason
  1127. */
  1128. kick(jid, reason = 'You have been kicked.') {
  1129. const kickIQ = $iq({ to: this.roomjid,
  1130. type: 'set' })
  1131. .c('query', { xmlns: 'http://jabber.org/protocol/muc#admin' })
  1132. .c('item', { nick: Strophe.getResourceFromJid(jid),
  1133. role: 'none' })
  1134. .c('reason').t(reason).up().up().up();
  1135. this.connection.sendIQ(
  1136. kickIQ,
  1137. result => logger.log('Kick participant with jid: ', jid, result),
  1138. error => logger.log('Kick participant error: ', error));
  1139. }
  1140. /* eslint-disable max-params */
  1141. /**
  1142. *
  1143. * @param key
  1144. * @param onSuccess
  1145. * @param onError
  1146. * @param onNotSupported
  1147. */
  1148. lockRoom(key, onSuccess, onError, onNotSupported) {
  1149. // http://xmpp.org/extensions/xep-0045.html#roomconfig
  1150. this.connection.sendIQ(
  1151. $iq({
  1152. to: this.roomjid,
  1153. type: 'get'
  1154. })
  1155. .c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  1156. res => {
  1157. if ($(res)
  1158. .find(
  1159. '>query>x[xmlns="jabber:x:data"]'
  1160. + '>field[var="muc#roomconfig_roomsecret"]')
  1161. .length) {
  1162. const formsubmit
  1163. = $iq({
  1164. to: this.roomjid,
  1165. type: 'set'
  1166. })
  1167. .c('query', {
  1168. xmlns: 'http://jabber.org/protocol/muc#owner'
  1169. });
  1170. formsubmit.c('x', {
  1171. xmlns: 'jabber:x:data',
  1172. type: 'submit'
  1173. });
  1174. formsubmit
  1175. .c('field', { 'var': 'FORM_TYPE' })
  1176. .c('value')
  1177. .t('http://jabber.org/protocol/muc#roomconfig')
  1178. .up()
  1179. .up();
  1180. formsubmit
  1181. .c('field', { 'var': 'muc#roomconfig_roomsecret' })
  1182. .c('value')
  1183. .t(key)
  1184. .up()
  1185. .up();
  1186. formsubmit
  1187. .c('field',
  1188. { 'var': 'muc#roomconfig_passwordprotectedroom' })
  1189. .c('value')
  1190. .t(key === null || key.length === 0 ? '0' : '1')
  1191. .up()
  1192. .up();
  1193. // if members only enabled
  1194. if (this.membersOnlyEnabled) {
  1195. formsubmit
  1196. .c('field', { 'var': 'muc#roomconfig_membersonly' })
  1197. .c('value')
  1198. .t('true')
  1199. .up()
  1200. .up();
  1201. }
  1202. // Fixes a bug in prosody 0.9.+
  1203. // https://prosody.im/issues/issue/373
  1204. formsubmit
  1205. .c('field', { 'var': 'muc#roomconfig_whois' })
  1206. .c('value')
  1207. .t('anyone')
  1208. .up()
  1209. .up();
  1210. this.connection.sendIQ(
  1211. formsubmit,
  1212. () => {
  1213. // we set the password in chat room so we can use it
  1214. // later when dialing out
  1215. this.password = key;
  1216. onSuccess();
  1217. },
  1218. onError);
  1219. } else {
  1220. onNotSupported();
  1221. }
  1222. },
  1223. onError);
  1224. }
  1225. /* eslint-enable max-params */
  1226. /**
  1227. * Turns off or on the members only config for the main room.
  1228. *
  1229. * @param {boolean} enabled - Whether to turn it on or off.
  1230. * @param onSuccess - optional callback.
  1231. * @param onError - optional callback.
  1232. */
  1233. setMembersOnly(enabled, onSuccess, onError) {
  1234. if (enabled && Object.values(this.members).filter(m => !m.isFocus).length) {
  1235. // first grant membership to all that are in the room
  1236. const affiliationsIq = $iq({
  1237. to: this.roomjid,
  1238. type: 'set' })
  1239. .c('query', {
  1240. xmlns: 'http://jabber.org/protocol/muc#admin' });
  1241. let sendIq = false;
  1242. Object.values(this.members).forEach(m => {
  1243. if (m.jid && !MEMBERS_AFFILIATIONS.includes(m.affiliation)) {
  1244. affiliationsIq.c('item', {
  1245. 'affiliation': 'member',
  1246. 'jid': Strophe.getBareJidFromJid(m.jid)
  1247. }).up();
  1248. sendIq = true;
  1249. }
  1250. });
  1251. sendIq && this.xmpp.connection.sendIQ(affiliationsIq.up());
  1252. }
  1253. const errorCallback = onError ? onError : () => {}; // eslint-disable-line no-empty-function
  1254. this.xmpp.connection.sendIQ(
  1255. $iq({
  1256. to: this.roomjid,
  1257. type: 'get'
  1258. }).c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' }),
  1259. res => {
  1260. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_membersonly"]').length) {
  1261. const formToSubmit
  1262. = $iq({
  1263. to: this.roomjid,
  1264. type: 'set'
  1265. }).c('query', { xmlns: 'http://jabber.org/protocol/muc#owner' });
  1266. formToSubmit.c('x', {
  1267. xmlns: 'jabber:x:data',
  1268. type: 'submit'
  1269. });
  1270. formToSubmit
  1271. .c('field', { 'var': 'FORM_TYPE' })
  1272. .c('value')
  1273. .t('http://jabber.org/protocol/muc#roomconfig')
  1274. .up()
  1275. .up();
  1276. formToSubmit
  1277. .c('field', { 'var': 'muc#roomconfig_membersonly' })
  1278. .c('value')
  1279. .t(enabled ? 'true' : 'false')
  1280. .up()
  1281. .up();
  1282. // if room is locked from other participant or we are locking it
  1283. if (this.locked) {
  1284. formToSubmit
  1285. .c('field',
  1286. { 'var': 'muc#roomconfig_passwordprotectedroom' })
  1287. .c('value')
  1288. .t('1')
  1289. .up()
  1290. .up();
  1291. }
  1292. this.xmpp.connection.sendIQ(formToSubmit, onSuccess, errorCallback);
  1293. } else {
  1294. errorCallback(new Error('Setting members only room not supported!'));
  1295. }
  1296. },
  1297. errorCallback);
  1298. }
  1299. /**
  1300. * Adds the key to the presence map, overriding any previous value.
  1301. * This method is used by jibri.
  1302. *
  1303. * @param key The key to add or replace.
  1304. * @param values The new values.
  1305. * @returns {boolean|null} <tt>true</tt> if the operation succeeded or <tt>false</tt> when no add or replce was
  1306. * performed as the value was already there.
  1307. * @deprecated Use 'addOrReplaceInPresence' instead. TODO: remove it from here and jibri.
  1308. */
  1309. addToPresence(key, values) {
  1310. return this.addOrReplaceInPresence(key, values);
  1311. }
  1312. /**
  1313. * Adds the key to the presence map, overriding any previous value.
  1314. * @param key The key to add or replace.
  1315. * @param values The new values.
  1316. * @returns {boolean|null} <tt>true</tt> if the operation succeeded or <tt>false</tt> when no add or replace was
  1317. * performed as the value was already there.
  1318. */
  1319. addOrReplaceInPresence(key, values) {
  1320. values.tagName = key;
  1321. const matchingNodes = this.presMap.nodes.filter(node => key === node.tagName);
  1322. // if we have found just one, let's check is it the same
  1323. if (matchingNodes.length === 1 && isEqual(matchingNodes[0], values)) {
  1324. return false;
  1325. }
  1326. this.removeFromPresence(key);
  1327. this.presMap.nodes.push(values);
  1328. this.presenceUpdateTime = Date.now();
  1329. return true;
  1330. }
  1331. /**
  1332. * Retrieves a value from the presence map.
  1333. *
  1334. * @param {string} key - The key to find the value for.
  1335. * @returns {Object?}
  1336. */
  1337. getFromPresence(key) {
  1338. return this.presMap.nodes.find(node => key === node.tagName);
  1339. }
  1340. /**
  1341. * Removes a key from the presence map.
  1342. * @param key
  1343. */
  1344. removeFromPresence(key) {
  1345. const nodes = this.presMap.nodes.filter(node => key !== node.tagName);
  1346. this.presMap.nodes = nodes;
  1347. this.presenceUpdateTime = Date.now();
  1348. }
  1349. /**
  1350. *
  1351. * @param name
  1352. * @param handler
  1353. */
  1354. addPresenceListener(name, handler) {
  1355. if (typeof handler !== 'function') {
  1356. throw new Error('"handler" is not a function');
  1357. }
  1358. let tagHandlers = this.presHandlers[name];
  1359. if (!tagHandlers) {
  1360. this.presHandlers[name] = tagHandlers = [];
  1361. }
  1362. if (tagHandlers.indexOf(handler) === -1) {
  1363. tagHandlers.push(handler);
  1364. } else {
  1365. logger.warn(
  1366. `Trying to add the same handler more than once for: ${name}`);
  1367. }
  1368. }
  1369. /**
  1370. *
  1371. * @param name
  1372. * @param handler
  1373. */
  1374. removePresenceListener(name, handler) {
  1375. const tagHandlers = this.presHandlers[name];
  1376. const handlerIdx = tagHandlers ? tagHandlers.indexOf(handler) : -1;
  1377. // eslint-disable-next-line no-negated-condition
  1378. if (handlerIdx !== -1) {
  1379. tagHandlers.splice(handlerIdx, 1);
  1380. } else {
  1381. logger.warn(`Handler for: ${name} was not registered`);
  1382. }
  1383. }
  1384. /**
  1385. * Checks if the user identified by given <tt>mucJid</tt> is the conference
  1386. * focus.
  1387. * @param mucJid the full MUC address of the user to be checked.
  1388. * @returns {boolean|null} <tt>true</tt> if MUC user is the conference focus
  1389. * or <tt>false</tt> if is not. When given <tt>mucJid</tt> does not exist in
  1390. * the MUC then <tt>null</tt> is returned.
  1391. */
  1392. isFocus(mucJid) {
  1393. const member = this.members[mucJid];
  1394. if (member) {
  1395. return member.isFocus;
  1396. }
  1397. return null;
  1398. }
  1399. /**
  1400. *
  1401. */
  1402. isModerator() {
  1403. return this.role === 'moderator';
  1404. }
  1405. /**
  1406. * Obtains the info about given media advertised (in legacy format) in the MUC presence of the participant
  1407. * identified by the given endpoint JID. This is for mantining interop with endpoints that do not support
  1408. * source-name signaling (Jigasi and very old mobile clients).
  1409. *
  1410. * @param {string} endpointId the endpoint ID mapped to the participant which corresponds to MUC nickname.
  1411. * @param {MediaType} mediaType the type of the media for which presence info will be obtained.
  1412. * @return {PeerMediaInfo} presenceInfo an object with media presence info or <tt>null</tt> either if there
  1413. * is no presence available or if the media type given is invalid.
  1414. */
  1415. getMediaPresenceInfo(endpointId, mediaType) {
  1416. // Will figure out current muted status by looking up owner's presence
  1417. const pres = this.lastPresences[`${this.roomjid}/${endpointId}`];
  1418. if (!pres) {
  1419. // No presence available
  1420. return null;
  1421. }
  1422. const data = {
  1423. muted: true, // muted by default
  1424. videoType: mediaType === MediaType.VIDEO ? VideoType.CAMERA : undefined // 'camera' by default
  1425. };
  1426. let mutedNode = null;
  1427. if (mediaType === MediaType.AUDIO) {
  1428. mutedNode = filterNodeFromPresenceJSON(pres, 'audiomuted');
  1429. } else if (mediaType === MediaType.VIDEO) {
  1430. mutedNode = filterNodeFromPresenceJSON(pres, 'videomuted');
  1431. const codecTypeNode = filterNodeFromPresenceJSON(pres, 'jitsi_participant_codecType');
  1432. const videoTypeNode = filterNodeFromPresenceJSON(pres, 'videoType');
  1433. if (videoTypeNode.length > 0) {
  1434. data.videoType = videoTypeNode[0].value;
  1435. }
  1436. if (codecTypeNode.length > 0) {
  1437. data.codecType = codecTypeNode[0].value;
  1438. }
  1439. } else {
  1440. logger.error(`Unsupported media type: ${mediaType}`);
  1441. return null;
  1442. }
  1443. if (mutedNode.length > 0) {
  1444. data.muted = mutedNode[0].value === 'true';
  1445. }
  1446. return data;
  1447. }
  1448. /**
  1449. *
  1450. * @param peerJid
  1451. */
  1452. getMemberRole(peerJid) {
  1453. if (this.members[peerJid]) {
  1454. return this.members[peerJid].role;
  1455. }
  1456. return null;
  1457. }
  1458. /**
  1459. * Returns the last presence advertised by a MUC member.
  1460. * @param {string} mucNick
  1461. * @returns {*}
  1462. */
  1463. getLastPresence(mucNick) {
  1464. return this.lastPresences[`${this.roomjid}/${mucNick}`];
  1465. }
  1466. /**
  1467. * Dials a number.
  1468. * @param number the number
  1469. */
  1470. dial(number) {
  1471. return this.connection.rayo.dial(number, 'fromnumber',
  1472. Strophe.getBareJidFromJid(this.myroomjid), this.password,
  1473. this.focusMucJid);
  1474. }
  1475. /**
  1476. * Hangup an existing call
  1477. */
  1478. hangup() {
  1479. return this.connection.rayo.hangup();
  1480. }
  1481. /**
  1482. *
  1483. * @returns {Lobby}
  1484. */
  1485. getLobby() {
  1486. return this.lobby;
  1487. }
  1488. /**
  1489. * @returns {AVModeration}
  1490. */
  1491. getAVModeration() {
  1492. return this.avModeration;
  1493. }
  1494. /**
  1495. * @returns {BreakoutRooms}
  1496. */
  1497. getBreakoutRooms() {
  1498. return this.breakoutRooms;
  1499. }
  1500. /**
  1501. * @returns {RoomMetadata}
  1502. */
  1503. getMetadataHandler() {
  1504. return this.roomMetadata;
  1505. }
  1506. /**
  1507. * Returns the phone number for joining the conference.
  1508. */
  1509. getPhoneNumber() {
  1510. return this.phoneNumber;
  1511. }
  1512. /**
  1513. * Returns the pin for joining the conference with phone.
  1514. */
  1515. getPhonePin() {
  1516. return this.phonePin;
  1517. }
  1518. /**
  1519. * Returns the meeting unique ID if any came from backend.
  1520. *
  1521. * @returns {string} - The meeting ID.
  1522. */
  1523. getMeetingId() {
  1524. return this.meetingId;
  1525. }
  1526. /**
  1527. * Mutes remote participant.
  1528. * @param jid of the participant
  1529. * @param mute
  1530. * @param mediaType
  1531. */
  1532. muteParticipant(jid, mute, mediaType) {
  1533. logger.info('set mute', mute, jid);
  1534. const iqToFocus = $iq(
  1535. { to: this.focusMucJid,
  1536. type: 'set' })
  1537. .c('mute', {
  1538. xmlns: `http://jitsi.org/jitmeet/${mediaType}`,
  1539. jid
  1540. })
  1541. .t(mute.toString())
  1542. .up();
  1543. this.connection.sendIQ(
  1544. iqToFocus,
  1545. result => logger.log('set mute', result),
  1546. error => logger.log('set mute error', error));
  1547. }
  1548. /**
  1549. * TODO: Document
  1550. * @param iq
  1551. */
  1552. onMute(iq) {
  1553. const from = iq.getAttribute('from');
  1554. if (from !== this.focusMucJid) {
  1555. logger.warn('Ignored mute from non focus peer');
  1556. return;
  1557. }
  1558. const mute = $(iq).find('mute');
  1559. if (mute.length && mute.text() === 'true') {
  1560. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, mute.attr('actor'));
  1561. } else {
  1562. // XXX Why do we support anything but muting? Why do we encode the
  1563. // value in the text of the element? Why do we use a separate XML
  1564. // namespace?
  1565. logger.warn('Ignoring a mute request which does not explicitly '
  1566. + 'specify a positive mute command.');
  1567. }
  1568. }
  1569. /**
  1570. * TODO: Document
  1571. * @param iq
  1572. */
  1573. onMuteVideo(iq) {
  1574. const from = iq.getAttribute('from');
  1575. if (from !== this.focusMucJid) {
  1576. logger.warn('Ignored mute from non focus peer');
  1577. return;
  1578. }
  1579. const mute = $(iq).find('mute');
  1580. if (mute.length && mute.text() === 'true') {
  1581. this.eventEmitter.emit(XMPPEvents.VIDEO_MUTED_BY_FOCUS, mute.attr('actor'));
  1582. } else {
  1583. // XXX Why do we support anything but muting? Why do we encode the
  1584. // value in the text of the element? Why do we use a separate XML
  1585. // namespace?
  1586. logger.warn('Ignoring a mute request which does not explicitly '
  1587. + 'specify a positive mute command.');
  1588. }
  1589. }
  1590. /**
  1591. * Clean any listeners or resources, executed on leaving.
  1592. */
  1593. clean() {
  1594. this._removeConnListeners.forEach(remove => remove());
  1595. this._removeConnListeners = [];
  1596. this.eventsForwarder.removeListeners(
  1597. AuthenticationEvents.IDENTITY_UPDATED,
  1598. XMPPEvents.AUTHENTICATION_REQUIRED,
  1599. XMPPEvents.FOCUS_DISCONNECTED,
  1600. XMPPEvents.RESERVATION_ERROR);
  1601. this.joined = false;
  1602. this.inProgressEmitted = false;
  1603. }
  1604. /**
  1605. * Leaves the room. Closes the jingle session.
  1606. * @returns {Promise} which is resolved if XMPPEvents.MUC_LEFT is received
  1607. * less than 5s after sending presence unavailable. Otherwise the promise is
  1608. * rejected.
  1609. */
  1610. leave(reason) {
  1611. this.avModeration.dispose();
  1612. this.breakoutRooms.dispose();
  1613. this.roomMetadata.dispose();
  1614. const promises = [];
  1615. this.lobby?.lobbyRoom && promises.push(this.lobby.leave());
  1616. promises.push(new Promise((resolve, reject) => {
  1617. let timeout = -1;
  1618. const onMucLeft = (doReject = false) => {
  1619. this.eventEmitter.removeListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1620. clearTimeout(timeout);
  1621. // This will reset the joined flag to false. If we reset it earlier any self presence will be
  1622. // interpreted as muc join. That's why we reset the flag once we have received presence unavalable
  1623. // (MUC_LEFT).
  1624. this.clean();
  1625. if (doReject) {
  1626. // The timeout expired. Make sure we clean the EMUC state.
  1627. this.connection.emuc.doLeave(this.roomjid);
  1628. reject(new Error('The timeout for the confirmation about leaving the room expired.'));
  1629. } else {
  1630. resolve();
  1631. }
  1632. };
  1633. if (this.joined) {
  1634. timeout = setTimeout(() => onMucLeft(true), 5000);
  1635. this.eventEmitter.on(XMPPEvents.MUC_LEFT, onMucLeft);
  1636. this.doLeave(reason);
  1637. } else {
  1638. // we are clearing up, and we haven't joined the room
  1639. // there is no point of sending presence unavailable and check for timeout
  1640. // let's just clean
  1641. this.connection.emuc.doLeave(this.roomjid);
  1642. this.clean();
  1643. resolve();
  1644. }
  1645. }));
  1646. return Promise.allSettled(promises);
  1647. }
  1648. /**
  1649. * Ends the conference for all participants.
  1650. */
  1651. end() {
  1652. if (this.breakoutRooms.isBreakoutRoom()) {
  1653. logger.warn('Cannot end conference: this is a breakout room.');
  1654. return;
  1655. }
  1656. // Send the end conference message.
  1657. const msg = $msg({ to: this.xmpp.endConferenceComponentAddress });
  1658. msg.c('end_conference').up();
  1659. this.xmpp.connection.send(msg);
  1660. }
  1661. }
  1662. /* eslint-enable newline-per-chained-call */