Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ChatRoom.js 61KB

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