modified lib-jitsi-meet dev repo
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 59KB

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