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

ChatRoom.js 65KB

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