您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ChatRoom.js 64KB

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