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

ChatRoom.js 67KB

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