modified lib-jitsi-meet dev repo
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 61KB

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