modified lib-jitsi-meet dev repo
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ChatRoom.js 61KB

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