Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ChatRoom.js 63KB

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