You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ChatRoom.js 58KB

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