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

ChatRoom.js 67KB

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