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 56KB

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