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 64KB

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