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

ChatRoom.js 64KB

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