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

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